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 |
|---|---|---|---|---|---|
RebootRevival/FFXI_Test | scripts/zones/Southern_San_dOria/npcs/Vaquelage.lua | 3 | 1533 | -----------------------------------
-- Area: Southern San dOria
-- NPC: Vaquelage
-- Type: Item Deliverer NPC
-- !pos 17.396 1.699 -29.357 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, ITEM_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
onpon4/naev | dat/missions/sirius/achack/achack01.lua | 1 | 6361 | --[[
<?xml version='1.0' encoding='utf8'?>
<mission name="Sirian Bounty">
<flags>
<unique />
</flags>
<avail>
<priority>19</priority>
<planet>The Wringer</planet>
<chance>50</chance>
<location>Bar</location>
</avail>
<notes>
<campaign>Academy Hack</campaign>
</notes>
</mission>
--]]
--[[
-- This is the first mission in the Academy Hack minor campaign.
--]]
require "missions/sirius/common"
require "numstring"
title1 = _("A Sirian with a grudge")
text1 = _([[You find a young Fyrra man sitting uncomfortably amidst the uncouth characters that frequent the Wringer. He seems to be here with a purpose, but nobody seems to be giving him the time of day. Curious, you decide to talk to the man and find out why he is here.
"Well met, stranger," the young Sirian greets you. "My name is Harja. I'm looking for someone who can help me with this... problem I have, it requires some violence. But nobody I've talked to so far seems interested! I thought this place was supposed to be filled with mercenaries and killers for hire. I can't believe how difficult this is!"
Harja clearly seems frustrated. And it seems he's here to hire someone to do some dirty work for him. Maybe it was not such a good idea to talk to him after all?
"Listen," he continues. "I don't intend to bore you with my personal sob story, so let's just say there's someone I want dead, a dangerous criminal. This woman did something to me cycles ago that just can't go unpunished. I've got money, I'm willing to pay. All you need to do is locate her, and discreetly take her out. I don't care how you do it. I don't even care if you enjoy it. Just come back when she's dead, and I'll pay you 400,000 credits. Do we have a deal?"]])
text2 = _([["Great! I was about to give up hope that I would find anyone with enough guts to do this for me. Okay, so, let me tell you about your target. She's a member of the Serra echelon, and she's got long, brown hair and blue eyes. She can usually be found in Sirius space, I believe she'll be on %s in the %s system right now. Come back to me when she's dead, and I'll give you your reward!"
Harja leaves the spacedock bar, satisfied that he's finally found someone to take his request. You can't help but wonder why he would try to hire a mercenary in a place like the Wringer, though. If the target is such a dangerous criminal, then wouldn't he be better off posting a bounty mission on the public board? Oh well, it's none of your business. You accepted the job, now all that's left is to complete it.]])
title2 = _("A Sirian military officer")
text3 = _([[You approach the young officer, determined to find out what you've gotten yourself involved with. You hope this was just a big mistake.
"Good day, pilot," the officer greets you as you approach her table. She seems quite polite, and nothing indicates that she is anything less than completely respectable. "Is there something I can help you with?"
You introduce yourself and explain that in your travels you've come across a man who tried to hire you to murder her. When you mention that his name is Harja, the officer's eyes go wide.
"Are you sure? Unbelievable. Just unbelievable. I know the man you speak of, and I certainly don't count him as one of my friends. But I assure you, what he told you about me is a complete lie. Yes, there is bad blood between us, it's rather personal. But as you can see my record is clean, or I wouldn't have been accepted into the military.
"I appreciate that you used your better judgment instead of recklessly trying to attack me, which would have ended badly for at least one of us. You said Harja offered you 400,000 credits for my death, yes? I will arrange for half that again to be deposited into your account. Consider it a token of gratitude. Now, it seems I may have a situation to take care of..."
The officer excuses herself from the table and heads to the local military station. You are satisfied for now that you got paid without having to get your hands dirty. You just hope this won't come back to bite you in the butt one day.]])
-- Mission info stuff
harjaname = _("A Fyrra civilian")
harjadesc = _("You see a young Fyrra man with a determined expression on his face.")
joannename = _("A Serra military officer")
joannedesc = _("This woman matches the description Harja gave you... But she's a military officer! This can't be right. You'd better talk to her and find out what's going on.")
osd_msg = {}
osd_title = _("Sirian Bounty")
osd_msg[1] = _("Fly to %s")
osd_msg[2] = _("Find your target on %s and kill her")
osd_msg["__save"] = true
misn_desc = _([[A Sirian man named Harja has hired you to dispatch a "dangerous criminal" who supposedly committed some kind of crime against him.]])
misn_reward = creditstring(400000) -- 400K
log_text = _([[A Sirian man named Harja hired you to kill a Sirius military officer, claiming that she was a "dangerous criminal". Rather than carrying out the mission, you told her about the plot, and she rewarded you by paying half what Harja would have paid for her death.]])
function create()
-- This mission ONLY spawns if the system it's in is not claimed by another mission. Special hack to mutex with Dark Shadow.
if not misn.claim(system.cur()) then
abort()
end
misn.setNPC(harjaname, "sirius/unique/harja.png", harjadesc)
end
function accept()
if not tk.yesno(title1, text1) then
abort()
end
destplanet, destsys = planet.get("Racheka")
tk.msg(title1, text2:format(destplanet:name(), destsys:name()))
osd_msg[1] = osd_msg[1]:format(destsys:name())
osd_msg[2] = osd_msg[2]:format(destplanet:name())
misn.accept()
misn.osdCreate(osd_title, osd_msg)
misn.setDesc(misn_desc)
misn.setReward(misn_reward)
misn.markerAdd(destsys, "high")
hook.land("land")
hook.enter("enter")
end
function land()
if planet.cur() == destplanet then
misn.npcAdd("talkJoanne", joannename, "sirius/unique/joanne.png", joannedesc, 4)
end
end
function enter()
if system.cur() == destsys then
misn.osdActive(2)
else
misn.osdActive(1)
end
end
function talkJoanne()
tk.msg(title2, text3)
player.pay(200000) -- 200K
srs_addAcHackLog( log_text )
misn.finish(true)
end
function abort()
misn.finish(false)
end
| gpl-3.0 |
mamaddeveloper/tel | bot/seedbot.lua | 1 | 8491 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite"
},
sudo_users = {94477327,134618808},--Sudo users
disabled_channels = {},
realm = {},--Realms Id
moderation = {data = 'data/moderation.json'},
about_text = [[Skybot v1
An advance Administration bot based on yagop/telegram-bot
Admins
@GenerousMan_bot [Developer]
@ultrabotadmin_powerbot
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
return group id or user id
!help
!lock [member|name|bots]
Locks [member|name|bots]
!unlock [member|name|photo|bots]
Unlocks [member|name|photo|bots]
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!newlink
create/revoke your group link
!link
returns group link
!owner
returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] <text>
Save <text> as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
returns user id
"!res @username"
!log
will return group logs
!banlist
will return group ban list
**U can use both "/" and "!"
*Only owner and mods can add bots in group
*Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
apwiede/nodemcu-firmware-2.0 | lua_modules/ds18b20/ds18b20.lua | 18 | 3492 | --------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Vowstar <vowstar@nodemcu.com>
-- 2015/02/14 sza2 <sza2trash@gmail.com> Fix for negative values
--------------------------------------------------------------------------------
-- Set module name as parameter of require
local modname = ...
local M = {}
_G[modname] = M
--------------------------------------------------------------------------------
-- Local used variables
--------------------------------------------------------------------------------
-- DS18B20 dq pin
local pin = nil
-- DS18B20 default pin
local defaultPin = 9
--------------------------------------------------------------------------------
-- Local used modules
--------------------------------------------------------------------------------
-- Table module
local table = table
-- String module
local string = string
-- One wire module
local ow = ow
-- Timer module
local tmr = tmr
-- Limited to local environment
setfenv(1,M)
--------------------------------------------------------------------------------
-- Implementation
--------------------------------------------------------------------------------
C = 'C'
F = 'F'
K = 'K'
function setup(dq)
pin = dq
if(pin == nil) then
pin = defaultPin
end
ow.setup(pin)
end
function addrs()
setup(pin)
tbl = {}
ow.reset_search(pin)
repeat
addr = ow.search(pin)
if(addr ~= nil) then
table.insert(tbl, addr)
end
tmr.wdclr()
until (addr == nil)
ow.reset_search(pin)
return tbl
end
function readNumber(addr, unit)
result = nil
setup(pin)
flag = false
if(addr == nil) then
ow.reset_search(pin)
count = 0
repeat
count = count + 1
addr = ow.search(pin)
tmr.wdclr()
until((addr ~= nil) or (count > 100))
ow.reset_search(pin)
end
if(addr == nil) then
return result
end
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
-- print("Device is a DS18S20 family device.")
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
-- tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
-- print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
-- print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
-- print("CRC="..crc)
if (crc == data:byte(9)) then
t = (data:byte(1) + data:byte(2) * 256)
if (t > 32767) then
t = t - 65536
end
if (addr:byte(1) == 0x28) then
t = t * 625 -- DS18B20, 4 fractional bits
else
t = t * 5000 -- DS18S20, 1 fractional bit
end
if(unit == nil or unit == 'C') then
-- do nothing
elseif(unit == 'F') then
t = t * 1.8 + 320000
elseif(unit == 'K') then
t = t + 2731500
else
return nil
end
t = t / 10000
return t
end
tmr.wdclr()
else
-- print("Device family is not recognized.")
end
else
-- print("CRC is not valid!")
end
return result
end
function read(addr, unit)
t = readNumber(addr, unit)
if (t == nil) then
return nil
else
return t
end
end
-- Return module table
return M
| mit |
RebootRevival/FFXI_Test | scripts/zones/Spire_of_Holla/bcnms/ancient_flames_beckon.lua | 29 | 4222 | -----------------------------------
-- Area: Spire_of_Holla
-- Name: ancient_flames_backon
-- KSNM30
-----------------------------------
package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/globals/teleports");
require("scripts/zones/Spire_of_Holla/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
print("instance code ");
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- printf("leavecode: %u",leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then
if (player:hasKeyItem(LIGHT_OF_MEA) and player:hasKeyItem(LIGHT_OF_DEM)) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,3);
elseif (player:hasKeyItem(LIGHT_OF_MEA) or player:hasKeyItem(LIGHT_OF_DEM)) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,2);
end
elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,1);
else
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); -- can't tell which cs is playing when you're doing it again to help
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7D01) then
if (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then
if (player:hasKeyItem(LIGHT_OF_MEA) and player:hasKeyItem(LIGHT_OF_DEM)) then
player:addExp(1500);
player:addKeyItem(LIGHT_OF_HOLLA);
player:messageSpecial(CANT_REMEMBER,LIGHT_OF_HOLLA);
player:completeMission(COP,THE_MOTHERCRYSTALS);
player:setVar("PromathiaStatus",0)
player:addMission(COP,AN_INVITATION_WEST);
player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_LUFAISE,0,1);
elseif (not(player:hasKeyItem(LIGHT_OF_HOLLA))) then
player:setVar("cspromy3",1)
player:addKeyItem(LIGHT_OF_HOLLA);
player:addExp(1500);
player:messageSpecial(CANT_REMEMBER,LIGHT_OF_HOLLA);
player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMHOLLA,0,1);
end
elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS) then
player:addExp(1500);
player:completeMission(COP,BELOW_THE_ARKS);
player:addMission(COP,THE_MOTHERCRYSTALS)
player:setVar("cspromy2",1)
player:setVar("PromathiaStatus",0)
player:addKeyItem(LIGHT_OF_HOLLA);
player:messageSpecial(CANT_REMEMBER,LIGHT_OF_HOLLA);
player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMHOLLA,0,1);
else
player:addExp(1500);
player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMHOLLA,0,1);
end
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/spells/bluemagic/sudden_lunge.lua | 3 | 2102 | -----------------------------------------
-- Spell: Sudden Lunge
-- Damage varies with TP. Additional effect: "Stun."
-- Spell cost: 18 MP
-- Monster Type: Vermin
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 4
-- Stat Bonus: HP-5 MP-5 DEX+1 AGI+1
-- Level: 95
-- Casting Time: 0.5 seconds
-- Recast Time: 15 seconds
-- Skillchain Element(s):
-- Combos: Store TP
-----------------------------------------
require("scripts/globals/bluemagic");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- onMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT);
local params = {};
params.diff = nil;
params.attribute = MOD_INT;
params.skillType = SKILL_BLU;
params.bonus = 0;
params.effect = EFFECT_STUN;
resist = applyResistanceEffect(caster, target, spell, params)
local params = {};
-- Todo: determine if these param values are retail
params.tpmod = TPMOD_DAMAGE;
params.dmgtype = DMGTYPE_SLASH;
params.scattr = SC_DETONATION;
params.numhits = 1;
params.multiplier = 1.875;
params.tp150 = 1.25;
params.tp300 = 1.50;
params.azuretp = 1.4375;
params.duppercap = 100;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.4;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
local damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
if (resist > 0.25) then -- This line may need adjusting for retail accuracy.
target:addStatusEffect(EFFECT_STUN, 1, 0, 20 * resist); -- Wiki says duration of "up to" 20 second..
end
return damage;
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Aht_Urhgan_Whitegate/npcs/_1e9.lua | 3 | 1153 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: _1e9 (Gate: The Pit)
-- !pos 80 -1.949 -107.94
-- Used to enter "The Colosseum" zone.
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(133);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 133 and option == 1) then
player:setPos(-600, 0, 40, 254, 71)
end
end; | gpl-3.0 |
sjmGithub/csi280LearningExperience | share/lua/playlist/france2.lua | 113 | 2115 | --[[
$Id$
Copyright © 2008 the VideoLAN team
Authors: Antoine Cellerier <dionoea 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.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "jt.france2.fr/player/" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "class=\"editiondate\"" ) then
_,_,editiondate = string.find( line, "<h1>(.-)</h1>" )
end
if string.match( line, "mms.*%.wmv" ) then
_,_,video = string.find( line, "mms(.-%.wmv)" )
video = "mmsh"..video
table.insert( p, { path = video; name = editiondate } )
end
if string.match( line, "class=\"subjecttimer\"" ) then
oldtime = time
_,_,time = string.find( line, "href=\"(.-)\"" )
if oldtime then
table.insert( p, { path = video; name = name; duration = time - oldtime; options = { ':start-time='..tostring(oldtime); ':stop-time='..tostring(time) } } )
end
name = vlc.strings.resolve_xml_special_chars( string.gsub( line, "^.*>(.*)<..*$", "%1" ) )
end
end
if oldtime then
table.insert( p, { path = video; name = name; options = { ':start-time='..tostring(time) } } )
end
return p
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Upper_Jeuno/npcs/Mejuone.lua | 17 | 1150 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Mejuone
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MEJUONE_SHOP_DIALOG);
stock = {0x11C1,62, -- Gysahl Greens
0x0348,7, -- Chocobo Feather
0x439B,9} -- Dart
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
sajadaltaie/sejobot | plugins/plugins.lua | 2 | 5891 | --------------------------------------------------
-- ____ ____ _____ --
-- | \| _ )_ _|___ ____ __ __ --
-- | |_ ) _ \ | |/ ·__| _ \_| \/ | --
-- |____/|____/ |_|\____/\_____|_/\/\_| --
-- --
--------------------------------------------------
-- --
-- Developers: @Josepdal & @MaSkAoS --
-- Support: @Skneos, @iicc1 & @serx666 --
-- --
--------------------------------------------------
do
to_id = ""
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_plugins(only_enabled)
local text = 'ℹ️ '..lang_text(to_id, 'plugins')..':\n'
local psum = 0
for k, v in pairs( plugins_names( )) do
-- ✅ enabled, ❎ disabled
local status = '❎'
psum = psum+1
pact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✅'
end
pact = pact+1
end
if not only_enabled or status == '✅' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..status..' '..v..'\n'
end
end
local text = text..'\n🔢 '..psum..' '..lang_text(to_id, 'installedPlugins')..'\n✅ '
..pact..' '..lang_text(to_id, 'pEnabled')..'\n❎ '..psum-pact..' '..lang_text(to_id, 'pDisabled')..''
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'ℹ️ '..lang_text(to_id, 'isEnabled:1')..' '..plugin_name..' '..lang_text(to_id, 'isEnabled:2')
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'ℹ️ '..lang_text(to_id, 'notExist:1')..' '..plugin_name..' '..lang_text(to_id, 'notExist:2')
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'ℹ️ '..lang_text(to_id, 'notExist:1')..' '..name..' '..lang_text(to_id, 'notExist:1')
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'ℹ️ '..lang_text(to_id, 'notEnabled:1')..' '..name..' '..lang_text(to_id, 'notEnabled:2')
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return 'ℹ️ '..lang_text(to_id, 'pNotExists')
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'ℹ️ '..lang_text(to_id, 'pDisChat:1')..' '..plugin..' '..lang_text(to_id, 'pDisChat:2')
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'ℹ️ '..lang_text(to_id, 'anyDisPlugin')
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'ℹ️ '..lang_text(to_id, 'anyDisPluginChat')
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'ℹ️ '..lang_text(to_id, 'notDisabled')
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'ℹ️ '..lang_text(to_id, 'enabledAgain:1')..' '..plugin..' '..lang_text(to_id, 'enabledAgain:2')
end
local function run(msg, matches)
to_id = msg.to.id
-- Show the available plugins
if permissions(msg.from.id, msg.to.id, "plugins") then
if matches[1] == '#plugins' then
return list_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' then
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' then
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' then
return reload_plugins(true)
end
else
return '🚫 '..lang_text(msg.to.id, 'require_sudo')
end
end
return {
patterns = {
"^#plugins$",
"^#plugins? (enable) ([%w_%.%-]+)$",
"^#plugins? (disable) ([%w_%.%-]+)$",
"^#plugins? (enable) ([%w_%.%-]+) (chat)",
"^#plugins? (disable) ([%w_%.%-]+) (chat)",
"^#plugins? (reload)$" },
run = run
}
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/globals/items/serving_of_karni_yarik.lua | 12 | 1645 | -----------------------------------------
-- ID: 5588
-- Item: serving_of_karni_yarik
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Agility 3
-- Vitality -1
-- Attack % 20 (cap 65)
-- Ranged Attack % 20 (cap 65)
-- Evasion +6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5588);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 3);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 65);
target:addMod(MOD_FOOD_RATTP, 20);
target:addMod(MOD_FOOD_RATT_CAP, 65);
target:addMod(MOD_EVA, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 3);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 65);
target:delMod(MOD_FOOD_RATTP, 20);
target:delMod(MOD_FOOD_RATT_CAP, 65);
target:delMod(MOD_EVA, 6);
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Western_Adoulin/npcs/Barenngo.lua | 3 | 1458 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Barenngo
-- Type: Standard NPC and Quest NPC
-- Involved with Quests: 'Dont Ever Leaf Me'
-- @zone 256
-- !pos -101 3 14 256
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DELM = player:getQuestStatus(ADOULIN, DONT_EVER_LEAF_ME);
if ((DELM == QUEST_ACCEPTED) and (player:getVar("DELM_Barenngo_Branch") < 1)) then
-- Progresses Quest: 'Dont Ever Leaf Me'
player:startEvent(0x1397);
elseif ((DELM == QUEST_ACCEPTED) and (player:getVar("DELM_Barenngo_Branch") < 2)) then
-- Reminds player of hint for Quest: 'Dont Ever Leaf Me'
player:startEvent(0x1398);
else
-- Standard dialogue
player:startEvent(0x139A);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x1397) then
-- Progresses Quest: 'Dont Ever Leaf Me'
player:setVar("DELM_Barenngo_Branch", 1);
end
end;
| gpl-3.0 |
petoju/awesome | tests/examples/awful/titlebar/default.lua | 3 | 2026 | --DOC_GEN_IMAGE --DOC_HIDE
--DOC_NO_USAGE
local place = require("awful.placement") --DOC_HIDE
local awful = { titlebar = require("awful.titlebar"), --DOC_HIDE
button = require("awful.button"), --DOC_HIDE
} --DOC_HIDE
local wibox = require("wibox") --DOC_HIDE
local gears = {table = require("gears.table")} --DOC_HIDE
local c = client.gen_fake {hide_first=true} --DOC_HIDE
place.maximize(c, {honor_padding=true, honor_workarea=true}) --DOC_HIDE
-- Create a titlebar for the client.
-- By default, `ruled.client` will create one, but all it does is to call this
-- function.
local top_titlebar = awful.titlebar(c, {
size = 20,
bg_normal = "#ff0000",
})
-- buttons for the titlebar
local buttons = gears.table.join(
awful.button({ }, 1, function()
client.focus = c
c:raise()
awful.mouse.client.move(c)
end),
awful.button({ }, 3, function()
client.focus = c
c:raise()
awful.mouse.client.resize(c)
end)
)
top_titlebar : setup {
{ -- Left
awful.titlebar.widget.iconwidget(c),
buttons = buttons,
layout = wibox.layout.fixed.horizontal
},
{ -- Middle
{ -- Title
align = "center",
widget = awful.titlebar.widget.titlewidget(c)
},
buttons = buttons,
layout = wibox.layout.flex.horizontal
},
{ -- Right
awful.titlebar.widget.floatingbutton (c),
awful.titlebar.widget.maximizedbutton(c),
awful.titlebar.widget.stickybutton (c),
awful.titlebar.widget.ontopbutton (c),
awful.titlebar.widget.closebutton (c),
layout = wibox.layout.fixed.horizontal()
},
layout = wibox.layout.align.horizontal
}
--DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
CCAAHH/telegram-bot-supergroups | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Southern_San_dOria_[S]/npcs/Moogle.lua | 3 | 1190 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Moogle
-- @zone 80
-- !pos <many>
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/moghouse")
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
moogleTrade(player,npc,trade);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (not moogleTrigger(player,npc)) then
player:startEvent(0x003D);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x7530) then
player:setVar("MoghouseExplication",0);
end
end; | gpl-3.0 |
rudolfmleziva/AdministratorTeritorial | cocos2d/cocos/scripting/lua-bindings/auto/api/Grid3D.lua | 10 | 1361 |
--------------------------------
-- @module Grid3D
-- @extend GridBase
-- @parent_module cc
--------------------------------
--
-- @function [parent=#Grid3D] getNeedDepthTestForBlit
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Grid3D] setNeedDepthTestForBlit
-- @param self
-- @param #bool neededDepthTest
--------------------------------
-- @overload self, size_table
-- @overload self, size_table, cc.Texture2D, bool
-- @function [parent=#Grid3D] create
-- @param self
-- @param #size_table gridSize
-- @param #cc.Texture2D texture
-- @param #bool flipped
-- @return Grid3D#Grid3D ret (return value: cc.Grid3D)
--------------------------------
--
-- @function [parent=#Grid3D] calculateVertexPoints
-- @param self
--------------------------------
--
-- @function [parent=#Grid3D] beforeBlit
-- @param self
--------------------------------
--
-- @function [parent=#Grid3D] afterBlit
-- @param self
--------------------------------
--
-- @function [parent=#Grid3D] reuse
-- @param self
--------------------------------
--
-- @function [parent=#Grid3D] blit
-- @param self
--------------------------------
-- js ctor
-- @function [parent=#Grid3D] Grid3D
-- @param self
return nil
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Windurst_Waters/npcs/Otete.lua | 17 | 1423 | -----------------------------------
-- Area: Windurst_Waters
-- NPC: Otete
-- Only sells when Windurst controlls Li'Telor Region
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(LITELOR);
if (RegionOwner ~= NATION_WINDURST) then
player:showText(npc,OTETE_CLOSED_DIALOG);
else
player:showText(npc,OTETE_OPEN_DIALOG);
stock = {
0x026F, 119, --Bay Leaves
0x103A, 6440 --Holy Water
}
showShop(player,WINDURST,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Cloister_of_Flames/mobs/Ifrit_Prime.lua | 23 | 1783 | -----------------------------------------------------
-- Area: Cloister of Flames
-- MOB: Ifrit Prime
-- Involved in Quest: Trial by Fire
-- Involved in Mission: ASA-4 Sugar Coated Directive
-----------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/status");
-----------------------------------
-- OnMobFight Action
-----------------------------------
function onMobFight(mob, target)
local mobId = mob:getID();
-- ASA-4: Astral Flow Behavior - Guaranteed to Use At Least 5 times before killable, at specified intervals.
if (mob:getBattlefield():getBcnmID() == 547 and GetMobAction(mobId) == ACTION_ATTACK) then
local astralFlows = mob:getLocalVar("astralflows");
if ((astralFlows == 0 and mob:getHPP() <= 80)
or (astralFlows == 1 and mob:getHPP() <= 60)
or (astralFlows == 2 and mob:getHPP() <= 40)
or (astralFlows == 3 and mob:getHPP() <= 20)
or (astralFlows == 4 and mob:getHPP() <= 1)) then
mob:setLocalVar("astralflows",astralFlows + 1);
mob:useMobAbility(848);
if (astralFlows >= 5) then
mob:setUnkillable(false);
end
end
end
end;
-----------------------------------
-- OnMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
-- ASA-4: Avatar is Unkillable Until Its Used Astral Flow At Least 5 times At Specified Intervals
if (mob:getBattlefield():getBcnmID() == 547) then
mob:setLocalVar("astralflows","0");
mob:setUnkillable(true);
end
end;
-----------------------------------
-- OnMobDeath Action
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
| gpl-3.0 |
onpon4/naev | dat/missions/flf/dvk/flf_dvk06.lua | 1 | 11911 | --[[
<?xml version='1.0' encoding='utf8'?>
<mission name="Assault on Haleb">
<flags>
<unique />
</flags>
<avail>
<priority>10</priority>
<chance>30</chance>
<done>Alliance of Inconvenience</done>
<location>Bar</location>
<faction>FLF</faction>
<cond>faction.playerStanding("FLF") >= 80</cond>
</avail>
<notes>
<campaign>Save the Frontier</campaign>
</notes>
</mission>
--]]
--[[
Assault on Haleb
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 3 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, see <http://www.gnu.org/licenses/>.
--]]
require "numstring"
local fleet = require "fleet"
require "missions/flf/flf_common"
-- Localization stuff
title = {}
text = {}
title[1] = _("Here we go again")
text[1] = _([["%s, we were just saying you should join in on this one! It's another great victory against the Dvaered oppressors, and we'd like you to lead the way to victory once again! Are you in?"]])
title[2] = _("Not This Time")
text[2] = _([["Okay. Just let me know if you change your mind."]])
title[3] = _("Another Decisive Strike")
text[3] = _([["Excellent!" You take a seat. "So once again, our mission today is the destruction of a loathed Dvaered base: Raglan Outpost! The plan is pretty much the same as before: we have tasked a group of pirates with creating a disturbance nearby, and we have planted a bomb within the outpost to aid in its destruction. You just need to decide when to strike and let your teammates know.
The one thing that will be different, though, is that you're likely to find more Dvaered ships guarding Raglan Outpost compared to Raelid Outpost, and it might be a little harder to destroy. So be extra careful!" Time to get your ship ready for battle, then.]])
title[4] = _("Another Day, Another Victory")
text[4] = _([[If your comrades were happy about your victory at Raelid, they are ecstatic about your victory at Haleb. As you enter the station, you are met with cheers from what seems to be everyone. It takes you longer than usual to make it to Benito as a result. "Congratulations," she says. "That was an astounding victory, sure to set back the Dvaered oppressors substantially! This is the first time we've pushed them out of Frontier space, and for that, we all thank you. If you haven't noticed, you've made yourself into a bit of a hero!
"Here is your pay, %s. May we have another great victory later on! Down with the oppressors!" You exchange some more words with Benito, party with the others for a period or two, and then make your way back to your ship for some much-needed rest.]])
misn_title = _("Assault on Haleb")
misn_desc = _("Join with the other FLF pilots for the assault on Raglan Outpost.")
misn_reward = _("Another great victory against the Dvaereds")
npc_name = _("Benito")
npc_desc = _("Benito is seated at a table with several other FLF soldiers. She motions for you to come over.")
osd_title = _("Assault on Haleb")
osd_desc = {}
osd_desc[1] = _("Fly to the %s system and meet with the group of FLF ships")
osd_desc[2] = _("Wait until the coast is clear, then hail one of your wingmates")
osd_desc[3] = _("Attack Raglan Outpost until it is destroyed")
osd_desc[4] = _("Return to FLF base")
osd_desc["__save"] = true
flfcomm = {}
flfcomm[1] = _("You're just in time, %s! The chaos is just about to unfold.")
flfcomm[2] = _("You heard the boss! Let's grind that station to dust!")
civcomm = _("Help! SOS! We are under attack! In need of immediate assistance!")
log_text = _([[You led the charge to destroy Raglan Outpost, a source of deep penetration of Dvaered forces into the Frontier. As a result, Dvaered forces have started to be pushed out of Frontier space, the first time the FLF has ever done so and a major victory for the Frontier.]])
function create ()
missys = system.get("Haleb")
if not misn.claim(missys) then
misn.finish(false)
end
misn.setNPC(npc_name, "flf/unique/benito.png", npc_desc)
end
function accept ()
if tk.yesno(title[1], text[1]:format(player.name())) then
tk.msg(title[3], text[3])
misn.accept()
osd_desc[1] = osd_desc[1]:format(missys:name())
misn.osdCreate(osd_title, osd_desc)
misn.setTitle(misn_title)
misn.setDesc(misn_desc:format(missys:name()))
marker = misn.markerAdd(missys, "plot")
misn.setReward(misn_reward)
credits = 750000
reputation = 5
started = false
attacked_station = false
completed = false
hook.enter("enter")
else
tk.msg(title[2], text[2])
misn.finish(false)
end
end
function enter ()
if not completed then
started = false
attacked_station = false
misn.osdActive(1)
if timer_start_hook ~= nil then hook.rm(timer_start_hook) end
if timer_pirates_hook ~= nil then hook.rm(timer_pirates_hook) end
if diff.isApplied("raglan_outpost_death") then
diff.remove("raglan_outpost_death")
end
if system.cur() == missys then
pilot.clear()
pilot.toggleSpawn(false)
local ro, ms, s
ro, s = planet.get("Raglan Outpost")
-- Spawn Raglan Outpost ship
dv_base = pilot.add("Raglan Outpost", "Dvaered", ro:pos() , nil,
{ai="dvaered_norun", noequip=true})
dv_base:control()
dv_base:setNoDisable()
dv_base:setNoboard()
dv_base:setNoLand()
dv_base:setVisible()
dv_base:setHilight()
hook.pilot(dv_base, "attacked", "pilot_attacked_station")
hook.pilot(dv_base, "death", "pilot_death_station")
-- Spawn Dvaered ships
local dv_ships = {
"Dvaered Goddard", "Dvaered Ancestor", "Dvaered Phalanx", "Dvaered Vigilance", "Dvaered Ancestor", "Dvaered Phalanx", "Dvaered Vigilance", "Dvaered Ancestor", "Dvaered Ancestor",
"Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta",
"Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta", "Dvaered Vendetta"}
dv_fleet = fleet.add(1, dv_ships, "Dvaered", ro:pos(), nil, {ai="dvaered_norun"})
for i, j in ipairs(dv_fleet) do
j:control()
j:setVisible()
hook.pilot(j, "attacked", "pilot_attacked")
end
-- Spawn FLF ships
local jmp, jmp2
jmp, jpm2 = jump.get("Haleb", "Theras")
flf_fleet = fleet.add(4, {"Vendetta", "Vendetta", "Lancelot"}, "FLF", jmp:pos() , {_("FLF Vendetta"), _("FLF Vendetta"), _("FLF Lancelot")})
for i, j in ipairs(flf_fleet) do
j:control()
j:brake()
j:face(dv_base:pos(), true)
j:setVisplayer()
j:setHilight()
hook.pilot(j, "attacked", "pilot_attacked")
end
timer_start_hook = hook.timer(4, "timer_start")
diff.apply("raglan_outpost_death")
end
end
end
function timer_start ()
if timer_start_hook ~= nil then hook.rm(timer_start_hook) end
local player_pos = player.pos()
local proximity = false
for i, j in ipairs(flf_fleet) do
local dist = player_pos:dist(j:pos())
if dist < 500 then proximity = true end
end
if proximity then
started = true
flf_fleet[1]:comm(flfcomm[1]:format(player.name()))
timer_pirates_hook = hook.timer(4, "timer_pirates")
misn.osdActive(2)
for i, j in ipairs(flf_fleet) do
j:setHilight(false)
hook.hail("hail")
end
civ_fleet = {}
local choices = {
"Civilian Llama", "Civilian Gawain", "Trader Llama",
"Trader Koala", "Trader Mule" }
local src = system.get("Triap")
for i = 1, 16 do
local choice = choices[ rnd.rnd(1, #choices) ]
local nf = pilot.addFleet(choice, src)
civ_fleet[ #civ_fleet + 1 ] = nf[1]
end
local dest = system.get("Slaccid")
for i, j in ipairs(civ_fleet) do
j:control()
j:hyperspace(dest)
j:setVisible()
hook.pilot(j, "attacked", "pilot_attacked_civilian")
end
else
timer_start_hook = hook.timer(0.05, "timer_start")
end
end
function timer_pirates ()
civ_fleet[1]:comm(civcomm)
local src = system.get("Triap")
pir_boss = pilot.add("Pirate Kestrel", "Pirate", src)
pir_fleet = {pir_boss}
hook.pilot(pir_boss, "death", "pilot_death_kestrel")
local choices = {
"Pirate Hyena", "Pirate Shark", "Pirate Admonisher",
"Pirate Vendetta", "Pirate Ancestor" }
for i = 1, 9 do
local choice = choices[ rnd.rnd(1, #choices) ]
local nf = pilot.addFleet(choice, src)
pir_fleet[ #pir_fleet + 1 ] = nf[1]
end
for i, j in ipairs(pir_fleet) do
j:control()
j:setVisible()
j:setFriendly()
j:attack()
hook.pilot(j, "attacked", "pilot_attacked")
end
for i, j in ipairs(dv_fleet) do
if j:exists() then
j:attack(pir_boss)
end
end
end
function hail ()
player.commClose()
if not attacked_station then
local comm_done = false
for i, j in ipairs(flf_fleet) do
if j:exists() then
j:attack(dv_base)
if not comm_done then
j:comm(flfcomm[2])
comm_done = true
end
end
end
attacked_station = true
misn.osdActive(3)
end
end
function pilot_attacked(pilot, attacker, arg)
pilot:control(false)
end
function pilot_attacked_civilian(pilot, attacker, arg)
pilot:control(false)
attacker:control(false)
end
function pilot_attacked_station(pilot, attacker, arg)
for i, j in ipairs(dv_fleet) do
if j:exists() then
j:control(false)
j:setHostile()
end
end
for i, j in ipairs(flf_fleet) do
if j:exists() then
j:setVisible()
end
end
end
function pilot_death_civilian(pilot, attacker, arg)
for i, j in ipairs(pir_fleet) do
if j:exists() then
j:control(false)
end
end
end
function pilot_death_kestrel(pilot, attacker, arg)
for i, j in ipairs(dv_fleet) do
if j:exists() then
j:control(false)
end
end
end
function pilot_death_station(pilot, attacker, arg)
for i, j in ipairs(flf_fleet) do
if j:exists() then
j:control(false)
j:changeAI("flf")
end
end
for i, j in ipairs(pir_fleet) do
if j:exists() then
j:control(false)
end
end
completed = true
pilot.toggleSpawn(true)
misn.osdActive(4)
if marker ~= nil then misn.markerRm(marker) end
hook.land("land")
end
function land ()
if planet.cur():faction() == faction.get("FLF") then
tk.msg(title[4], text[4]:format(player.name()))
finish()
end
end
function finish ()
player.pay(credits)
flf_setReputation(90)
faction.get("FLF"):modPlayer(reputation)
flf_addLog(log_text)
misn.finish(true)
end
function abort ()
if completed then
finish()
else
if diff.isApplied("raglan_outpost_death") then
diff.remove("raglan_outpost_death")
end
if dv_base ~= nil and dv_base:exists() then
dv_base:rm()
end
misn.finish(false)
end
end
| gpl-3.0 |
hfjgjfg/jjjn | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Lower_Delkfutts_Tower/npcs/_544.lua | 3 | 1684 | -----------------------------------
-- Area: Lower Delkfutt's Tower
-- NPC: Cermet Door
-- Notes: Door opens when you trade Delkfutt Key to it
-- !pos 345 0.1 20 184
-----------------------------------
package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Lower_Delkfutts_Tower/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(549,1) and trade:getItemCount() == 1) then -- Trade Delkfutt Key
player:startEvent(0x0010);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(DELKFUTT_KEY)) then
player:startEvent(0x0010);
else
player:startEvent(0x000a); -- door is firmly shut
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--print("CSID:",csid);
--print("RESULT:",option);
if (csid == 0x0010 and option == 1) then
if (player:hasKeyItem(DELKFUTT_KEY) == false) then
player:tradeComplete();
player:messageSpecial(KEYITEM_OBTAINED,DELKFUTT_KEY);
player:addKeyItem(DELKFUTT_KEY);
end
end
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/PsoXja/npcs/Treasure_Chest.lua | 17 | 3465 | -----------------------------------
-- Area: Pso'Xja
-- NPC: Treasure Chest
-- @zone 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/zones/PsoXja/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1064,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1064,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: Map -----------
if (player:hasKeyItem(MAP_OF_PSOXJA) == false) then
questItemNeeded = 1;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 1) then
player:addKeyItem(MAP_OF_PSOXJA);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_PSOXJA); -- Map of Pso'Xja
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1064);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
mzguanglin/LuCI | modules/niu/luasrc/model/cbi/niu/traffic/qos1.lua | 49 | 3073 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local fs = require "nixio.fs"
m = Map("qos", translate("Manage Prioritization (QoS)"), translate([[Different
kinds of network traffic usually have different transmission requirements.
For example the important factor for a large HTTP-download is bandwith whereas
VoIP has a large focus on low packet latency. Prioritization takes these quality
of service factors into account and optimizes priorities to allow reasonable
performance for time critical services.]]))
s = m:section(NamedSection, "wan", "interface", translate("General Settings"),
translate([[For QoS to work correctly you need to provide the upload and
download speed of your internet connection. Values are in kilobits per second.
For comparison a standard consumer ADSL connection has between 1000 and 25000
kbps as donwload speed and between 128 and 1000 kbps upload speed.]]))
s.addremove = false
local en = s:option(ListValue, "enabled", translate("Prioritization"))
en:value("1", "Enable Quality of Service")
en:value("0", "Disable")
local dl = s:option(Value, "download", translate("Maximum Download Speed"), "kbps")
dl:depends("enabled", "1")
local ul = s:option(Value, "upload", translate("Maximum Upload Speed"), "kbps")
ul:depends("enabled", "1")
s = m:section(TypedSection, "classify", translate("Finetuning"), translate([[
The QoS application provides different useful default prioritization rules not
listed here that cover many common use-cases. You however can add custom rules
to finetune the prioritization process.]]))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
n = s:option(Value, "_name", translate("Name"), translate("optional"))
srch = s:option(Value, "srchost", translate("Local IP-Address"))
srch.rmempty = true
srch:value("", translate("all"))
for i, dataset in ipairs(sys.net.arptable()) do
srch:value(dataset["IP address"])
end
p = s:option(ListValue, "proto", translate("Protocol"))
p:value("", translate("all"))
p:value("tcp", "TCP")
p:value("udp", "UDP")
p.rmempty = true
ports = s:option(Value, "ports", translate("Ports"))
ports.rmempty = true
ports:value("", translate("any"))
if fs.access("/etc/l7-protocols") then
l7 = s:option(ListValue, "layer7", translate("Service"))
l7.rmempty = true
l7:value("", translate("all"))
for f in fs.glob("/etc/l7-protocols/*.pat") do
l7:value(f:sub(19, #f-4))
end
end
s:option(Value, "connbytes", translate("Bytes sent"), translate("from[-to]"))
t = s:option(ListValue, "target", translate("Priority"))
t:value("Priority", translate("Highest"))
t:value("Express", translate("High"))
t:value("Normal", translate("Normal"))
t:value("Bulk", translate("Low"))
t.default = "Normal"
return m
| apache-2.0 |
RebootRevival/FFXI_Test | scripts/globals/items/slice_of_cockatrice_meat.lua | 12 | 1357 | -----------------------------------------
-- ID: 4435
-- Item: slice_of_cockatrice_meat
-- Food Effect: 5Min, Galka only
-----------------------------------------
-- Strength 4
-- Intelligence -6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 8) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4435);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 4);
target:addMod(MOD_INT, -6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 4);
target:delMod(MOD_INT, -6);
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Temenos/npcs/Matter_Diffusion_Module.lua | 3 | 6347 | -----------------------------------
-- Area: temenos
-- NPC: Matter diffusion module
-- !pos
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/globals/keyitems");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
local InstanceTrade=0;
if (player:hasKeyItem(COSMOCLEANSE) and player:hasKeyItem(WHITE_CARD) ) then
if (count==1 and trade:hasItemQty(2127,1)) then -- Central Temenos - Basement 1
InstanceTrade=128;
elseif (count==1 and trade:hasItemQty(1906,1)) then -- Central Temenos - 1st Floor
InstanceTrade=64;
elseif (count==1 and trade:hasItemQty(1905,1)) then -- Central Temenos - 2st Floor
InstanceTrade=32;
elseif (count==1 and trade:hasItemQty(1904,1)) then -- Central Temenos - 3st Floor
InstanceTrade=16;
elseif (count==3 and trade:hasItemQty(1986,1) and trade:hasItemQty(1908,1) and trade:hasItemQty(1907,1)) then --proto-ultima
InstanceTrade=8;
end
else
player:messageSpecial(CONDITION_FOR_LIMBUS_T);
print("error player don't have cosmo clean");
end
if (InstanceTrade~=0) then
player:setVar("Limbus_Trade_Item-T",InstanceTrade);
player:tradeComplete();
player:messageSpecial(CHIP_TRADE_T);
player:startEvent(0x7d00,0,0,0,InstanceTrade,0,0,0,0);
player:setVar("limbusbitmap",InstanceTrade);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local instancelist ={};
local limbusbitmap = 0 ;
local AllowLimbusToPlayer = true ;
local currentlimbus= TryTobackOnCurrentLimbus(player);
instancelist = TEMENOS_LIST;
printf("currentlimbus: %u",currentlimbus);
if (player:hasKeyItem(COSMOCLEANSE)) then
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
local LimbusTradeItem = player:getVar("Limbus_Trade_Item-T");
for nt = 1,#instancelist,2 do
-- printf("list d'instance: %u",instancelist[nt]);
if (instancelist[nt+1][1]==true and player:hasKeyItem(WHITE_CARD)) then
-- print("player_have_white_card");
limbusbitmap = limbusbitmap + instancelist[nt+1][4];
-- printf("bitmapadd: %u",instancelist[nt+1][4]);
end
if (instancelist[nt+1][2]==true and player:hasKeyItem(RED_CARD)) then
-- print("player_have_red_card");
limbusbitmap = limbusbitmap + instancelist[nt+1][4];
-- printf("bitmapadd: %u",instancelist[nt+1][4]);
end
if (instancelist[nt+1][3]==true and player:hasKeyItem(BLACK_CARD)) then
-- print("player_have_black_card");
limbusbitmap = limbusbitmap + instancelist[nt+1][4];
-- printf("bitmapadd: %u",instancelist[nt+1][4]);
end
end
limbusbitmap= limbusbitmap + LimbusTradeItem;
----- /////////////////////////////////////////////on doit ajouter le mipmap pour l'item trade ici
else
local status = player:getStatusEffect(EFFECT_BATTLEFIELD);
local playerbcnmid = status:getPower();
-- check if the player has the key item for the current battlefield
for nt = 1,#instancelist,2 do
-- printf("list d'instance: %u",instancelist[nt]);
if (instancelist[nt] == playerbcnmid) then
if (instancelist[nt+1][1]== true and player:hasKeyItem(WHITE_CARD) == false) then
AllowLimbusToPlayer = false;
end
if (instancelist[nt+1][2]== true and player:hasKeyItem(RED_CARD) == false ) then
AllowLimbusToPlayer = false;
end
if (instancelist[nt+1][3]== true and player:hasKeyItem(BLACK_CARD) == false ) then
AllowLimbusToPlayer = false;
end
if (AllowLimbusToPlayer == true) then --player have the correct key item for the current battflield
limbusbitmap = instancelist[nt+1][4];
end
end
end
end
if (limbusbitmap~= 0 ) then
player:startEvent(0x7d00,0,0,0,limbusbitmap,0,0,0,0);
player:setVar("limbusbitmap",limbusbitmap);
else
player:messageSpecial(CONDITION_FOR_LIMBUS_T);
print("player need a card for basic limbus");
end
elseif (currentlimbus~=0) then
for nt = 1,#instancelist,2 do
-- printf("list d'instance: %u",instancelist[nt]);
if (instancelist[nt] == currentlimbus) then
limbusbitmap = instancelist[nt+1][4];
end
end
player:startEvent(0x7d00,0,0,0,limbusbitmap,0,0,0,0);
player:setVar("limbusbitmap",limbusbitmap);
else
player:messageSpecial(CONDITION_FOR_LIMBUS_T);
print("error player don't have cosmo clean");
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if (csid == 0x7d00) then
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
ResetPlayerLimbusVariable(player);
player:setVar("characterLimbusKey",0);
else
local status = player:getStatusEffect(EFFECT_BATTLEFIELD);
player:setVar("LimbusID",status:getPower());
player:setVar("characterLimbusKey",GetLimbusKeyFromInstance(status:getPower()));
end
player:updateEvent(2,player:getVar("limbusbitmap"),0,1,1,0);
player:setVar("limbusbitmap",0);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x7d00) then
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/abilities/pets/eraser.lua | 1 | 1759 | ---------------------------------------------
-- Eraser
---------------------------------------------
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(RECAST_ABILITY, skill:getID(), 30)
local maneuvers = master:countEffect(EFFECT_LIGHT_MANEUVER)
skill:setMsg(msgBasic.USES)
local function removeStatus()
if target:delStatusEffect(EFFECT_PETRIFICATION) then return true end
if target:delStatusEffect(EFFECT_SILENCE) then return true end
if target:delStatusEffect(EFFECT_BANE) then return true end
if target:delStatusEffect(EFFECT_CURSE_II) then return true end
if target:delStatusEffect(EFFECT_CURSE) then return true end
if target:delStatusEffect(EFFECT_PARALYSIS) then return true end
if target:delStatusEffect(EFFECT_PLAGUE) then return true end
if target:delStatusEffect(EFFECT_POISON) then return true end
if target:delStatusEffect(EFFECT_DISEASE) then return true end
if target:delStatusEffect(EFFECT_BLINDNESS) then return true end
if target:eraseStatusEffect() ~= 255 then return true end
return false
end
local toremove = maneuvers
local removed = 0
repeat
if not removeStatus() then break end
toremove = toremove - 1
removed = removed + 1
until (toremove <= 0)
for i = 1, maneuvers do
master:delStatusEffectSilent(EFFECT_LIGHT_MANEUVER)
end
return removed
end
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/spells/sleepga.lua | 1 | 1635 | -----------------------------------------
-- Spell: Sleep I
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local duration = 60;
local pINT = caster:getStat(MOD_INT);
local mINT = target:getStat(MOD_INT);
local dINT = (pINT - mINT);
local params = {};
params.diff = nil;
params.attribute = MOD_INT;
params.skillType = ENFEEBLING_MAGIC_SKILL;
params.bonus = 0;
params.effect = EFFECT_SLEEP_I;
resm = applyResistanceEffect(caster, target, spell, params);
if (caster:isMob()) then
if (caster:getPool() == 5310) then -- Amnaf (Flayer)
caster:resetEnmity(target);
end
-- Todo: get rid of this whole block by handling it in the mob script
-- this requires a multi target enmity without specifying a target (have to get hate list from mob)
-- OR by altering onSpellPrecast to have a target param..
-- onMonsterMagicPrepare is not a realistic option.
-- You'd have to script the use of every individual spell in Amnaf's list..
end
if (resm < 0.5) then
spell:setMsg(85); -- Resist
return EFFECT_SLEEP_I;
end
duration = duration * resm;
if (target:addStatusEffect(EFFECT_SLEEP_I,1,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75); -- No effect
end
return EFFECT_SLEEP_I;
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Tahrongi_Canyon/npcs/qm2.lua | 3 | 2577 | -----------------------------------
-- Area: Tahrongi Canyon
-- NPC: qm2 (???)
-- Note: Used to spawn Yara Ma Yha Who
-- !pos 271 0.001 -334 117
-----------------------------------
package.loaded["scripts/zones/Tahrongi_Canyon/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/settings");
require("scripts/zones/Tahrongi_Canyon/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Distilled water to Spawn Yara Ma Yha Who
if (GetMobAction(17256900) == 0 and trade:hasItemQty(4509,1) and trade:getItemCount() == 1) then -- Checks to make sure trade has not been made in past 50 minutes
if (GetServerVariable("[POP]Yara-Ma-Yha-Who-Timer") < os.time()) then
player:tradeComplete();
local timesTraded = GetServerVariable("[POP]Yara-Ma-Yha-Who-Trades");
if (timesTraded == 3) then -- Takes a minimum of 3 trades before NM can be spawned
if (math.random(0,2) == 2) then
SpawnMob(17256900):updateClaim(player); -- Spawn Yara Ma Yha Who
player:messageSpecial(REPULSIVE_CREATURE_EMERGES);
else
player:messageSpecial(SPROUT_LOOKING_BETTER);
end
else
SetServerVariable("[POP]Yara-Ma-Yha-Who-Trades",timesTraded + 1)
player:messageSpecial(SPROUT_LOOKING_BETTER);
end
else
player:messageSpecial(SPROUT_DOES_NOT_NEED_WATER)
end
SetServerVariable("[POP]Yara-Ma-Yha-Who-Timer",os.time() + 3000); -- 50 minutes wait time before you can trade again
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if (GetServerVariable("[POP]Yara-Ma-Yha-Who-Timer") < os.time()) then -- Checks to make sure trade has not been made in past 50 minutes
player:messageSpecial(SPROUT_LOOKS_WITHERED);
else
player:messageSpecial(SPROUT_LOOKING_BETTER);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
TheRikyHUN/fooniks | resources/phoenix_Base/base-client.lua | 2 | 6286 | loginWindow = nil;
loginBtn = nil;
usrName = nil;
passWord = nil;
remember = nil;
userRight = false;
passRight = false;
nameVal = "";
passVal = "";
isChecked = false;
wantRemember = false;
sx, sy = guiGetScreenSize( );
local sVersion = "0.0";
local sRev = "0";
local txtColor = tocolor( 255, 255, 255, 200 );
--local formatstr = "Phoenix %s.%s";
local formatstr = "Phoenix - WIP Demo";
local theStr = string.format( formatstr, sVersion, sRev );
function showLogin( )
if( not loginWindow) then
checkForRemember( );
loginWindow = guiCreateWindow( (sx-512)/2, (sy-410)/2, 512, 410, "Tere Tulemast", false );
local tempLabel;
tempLabel = guiCreateLabel( 0.15, 0.11, 0.7, 0.38, "See on F88niks, uus ajastu Eesti rollim2ngus.\nPalun logige sisse, et alustada m2ngimist.\nKui\n\n * Sa unustasid parooli\n * Sul ei ole kasutajat\n\nSiis mine aadressile:\n\thttp://estrp.com\n", true, loginWindow );
guiSetFont( tempLabel, "clear-normal");
tempLabel = guiCreateLabel( 0.15, 0.51, 0.2, 0.10, "Kasutajanimi:", true, loginWindow );
guiSetFont( tempLabel, "clear-normal");
tempLabel = guiCreateLabel( 0.15, 0.61, 0.2, 0.10, "Parool:", true, loginWindow );
guiSetFont( tempLabel, "clear-normal");
tempLabel = guiCreateLabel( 0.15, 0.71, 0.2, 0.10, "J2ta meelde:", true, loginWindow );
guiSetFont( tempLabel, "clear-normal");
usrName = guiCreateEdit( 0.55, 0.50, 0.3, 0.05, nameVal, true, loginWindow );
passWord = guiCreateEdit( 0.55, 0.60, 0.3, 0.05, passVal, true, loginWindow );
guiEditSetMasked( passWord, true );
remember = guiCreateCheckBox( 0.55, 0.70, 0.2, 0.05, "jah", isChecked, true, loginWindow );
loginBtn = guiCreateButton( 0.4, 0.85, 0.2, 0.05, "Logi Sisse", true, loginWindow );
guiSetEnabled( loginBtn, ( userRight and passRight ) );
guiSetVisible( loginWindow, true );
showCursor( true );
guiSetInputEnabled( true );
end
end
addEvent( "OnPlayerRequestLogin", true );
addEventHandler( "OnPlayerRequestLogin", getRootElement( ), showLogin );
addEvent( "OnPlayerLogin", true );
addEventHandler( "OnPlayerLogin", getRootElement( ),
function ( ret, other )
if( ret == 0 ) then
outputChatBox( other, 255, 0, 0 );
else
if( wantRemember ) then
saveForRemember( guiGetText( usrName ), guiGetText( passWord ) );
else
local xml = xmlLoadFile ( "rememberMe.xml" );
if ( xml ~= false ) then
xmlDestroyNode ( xml );
end
end
guiSetVisible( loginWindow, false );
showCursor( false );
guiSetInputEnabled( false );
triggerServerEvent( "onCharactersRequest", getLocalPlayer( ) );
end
end
);
function editChange( element )
local str = guiGetText(element);
local len = string.len(str);
if(len < 1) then
if(element == usrName) then userRight = false; end
if(element == passWord) then passRight = false; end
else
if(element == usrName) then userRight = true; end
if(element == passWord) then passRight = true; end
end
guiSetEnabled( loginBtn, ( userRight and passRight ) );
end
function resourceHandler( )
showLogin( );
addEventHandler("onClientGUIClick", loginBtn,
function ( )
guiSetEnabled( loginBtn, false );
wantRemember = guiCheckBoxGetSelected( remember );
triggerServerEvent( "OnAuthPlayer", getLocalPlayer( ), guiGetText(usrName), guiGetText(passWord) );
end
, false);
addEventHandler( "onClientGUIChanged", usrName, editChange );
addEventHandler( "onClientGUIChanged", passWord, editChange );
local realtime = getRealTime( );
setTime( realtime.hour, realtime.minute )
setMinuteDuration( 60000 );
end
addEventHandler( "onClientResourceStart", getResourceRootElement( getThisResource( ) ), resourceHandler );
function saveForRemember( rememberUser, rememberPass )
local xml = xmlCreateFile( "rememberMe.xml", "remember" );
if ( xml ~= false ) then
local child = xmlCreateChild (xml, "user" );
if( child ~= false ) then xmlNodeSetAttribute( child, "rem", rememberUser ); end
child = xmlCreateChild (xml, "pass" );
if( child ~= false ) then xmlNodeSetAttribute( child, "rem", rememberPass ); end
xmlSaveFile ( xml );
xmlUnloadFile ( xml );
end
end
function checkForRemember( )
local xml = xmlLoadFile ( "rememberMe.xml" );
if ( xml ~= false ) then
local child = xmlFindChild (xml, "user", 0 );
if( child ~= false ) then
nameVal = xmlNodeGetAttribute( child, "rem" );
userRight = true;
end
child = xmlFindChild( xml, "pass", 0 );
if( child ~= false ) then
passVal = xmlNodeGetAttribute( child, "rem" );
passRight = true;
isChecked = true;
end
xmlUnloadFile ( xml );
end
end
addEvent( "onScriptInfoRequest", true );
addEventHandler( "onScriptInfoRequest", getRootElement( ),
function ( ver, rev )
sVersion = ver;
sRev = rev;
theStr = string.format( formatstr, sVersion, sRev );
end
);
local hidden = false;
function drawVersion( )
dxDrawText( theStr, sx-150, sy-40, sx-3, sy-10, txtColor, 1, "default", "right", "bottom" );
end
addEventHandler( "onClientResourceStart", getResourceRootElement( getThisResource( ) ),
function ()
triggerServerEvent( "onScriptInfoRequestS", getLocalPlayer( ) );
addEventHandler("onClientRender", getRootElement( ), drawVersion);
hidden = false;
end
);
addCommandHandler( "hideversion", function ( ) if( not hidden ) then removeEventHandler( "onClientRender", getRootElement( ), drawVersion ); hidden = true; else hidden = false; addEventHandler("onClientRender", getRootElement( ), drawVersion); end end );
addCommandHandler( "save",
function ( strCmd, wantXml )
local posX, posY, posZ = getElementPosition( getLocalPlayer( ) );
local rotZ = getPedRotation( getLocalPlayer( ) );
local formatStr = "%.3f, %.3f, %.3f, %.3f";
if( wantXml ) then
formatStr = "posX=\"%.3f\" posY=\"%.3f\" posX=\"%.3f\" rotZ=\"%.3f\"";
end
outputConsole( string.format( formatStr, posX, posY, posZ, rotZ ) );
end
); | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Lower_Jeuno/npcs/Gurdern.lua | 17 | 1379 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Gurdern
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Lower_Jeuno/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,14) == false) then
player:startEvent(10052);
else
player:startEvent(0x0070);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 10052) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",14,true);
end
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Western_Adoulin/npcs/Preterig.lua | 3 | 1183 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Preterig
-- Type: Shop NPC
-- @zone 256
-- !pos 6 0 -53 256
-----------------------------------
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Western_Adoulin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Standard shop
player:showText(npc, PRETERIG_SHOP_TEXT);
local stock =
{
0x1147, 300, -- Apple Juice
0x1738, 125, -- Frontier Soda
0x1145, 1560, -- Melon Pie
0x1146, 200, -- Orange Juice
}
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
tommo/mock | mock/tools/TMXTool.lua | 2 | 4632 | local function trynumber(v)
return tonumber(v) or v
end
local function copyNode(s,x)
local attr=x.attributes
if attr then
for k,v in pairs(attr) do
s[k]=trynumber(v)
end
end
end
local function parseTileSet(node)
local set={}
copyNode(set,node)
local image=node.children['image'][1]
assert(image, 'not support tsx')
set.source=image.attributes['source']
--todo:property
return set
end
local function parseProperties(node)
local l={}
for i,n in ipairs(node.children['property']) do
local attr=n.attributes
l[n['name']]=trynumber(n['value'])
end
return l
end
local function parseObject(node)
local obj={}
copyNode(obj,node)
if obj.children and obj.children['properties'] then
obj.properties=parseProperties(obj.children['properties'][1])
end
return obj
end
local function parseObjectGroup(node)
local group={}
copyNode(group, node)
for i,n in ipairs(node.children['object']) do
group[i]=parseObject(n)
end
return group
end
local function parseTileLayer(node)
local layer={}
copyNode(layer,node)
local data=node.children['data'][1]
local encoding=data.attributes['encoding']
if encoding=='csv' then
layer.tiles=loadstring('return {'..data.value..'}')()
elseif encoding=='base64' then
--reference: TMXMapLoader from Hanappe
local decoded=MOAIDataBuffer.base64Decode(data.value)
if data.attributes['compression'] then
decoded=MOAIDataBuffer.inflate(decoded,47)
end
local tileCount=#decoded/4
local t={}
for i=1, tileCount do
local start=(i-1)*4 + 1
local a0,a1,a2,a3 = string.byte(decoded, start, start+3)
t[i] = a0 + a1 * 2^8 + a2 * 2^16 + a3 * 2^32
end
layer.tiles=t
else
error('unknown encoding')
end
return layer
end
local function parseMap(node)
assert(node.type=='map')
local map={}
copyNode(map,node)
local tileSets={}
local objectGroups={}
local tileLayers={}
if node.children['tileset'] then
for i, n in ipairs(node.children['tileset']) do
tileSets[i]=parseTileSet(n)
end
end
if node.children['objectgroup'] then
for i, n in ipairs(node.children['objectgroup']) do
objectGroups[i]=parseObjectGroup(n)
end
end
if node.children['layer'] then
for i, n in ipairs(node.children['layer']) do
tileLayers[i]=parseTileLayer(n)
end
end
map.tileSets=tileSets
map.tileLayers=tileLayers
map.objectGroups=objectGroups
return map
end
local function tmx2lua(file)
local xml=MOAIXmlParser.parseFile(file)
return parseMap(xml)
end
CLASS: TMXTool ()
function TMXTool:load(tmxfile)
local data=tmx2lua(tmxfile)
self.data=data or false
end
function TMXTool:getObjectLayers()
return self.data.objectGroups
end
function TMXTool:getTileLayers()
return self.data.tileLayers
end
function TMXTool:findObject(layerId, objId)
local layer=self:findObjectLayer(layerId)
if not layer then return nil end
for i, obj in ipairs(layer) do
if obj.name==objId then
return obj
end
end
return nil
end
function TMXTool:getObjectLayerCount()
assert(self.data,'not loaded')
if not self.data then return 0 end
return #self.data.objectGroups
end
function TMXTool:getTileLayerCount()
assert(self.data,'not loaded')
if not self.data then return 0 end
return #self.data.tileLayers
end
function TMXTool:findTileLayer(id)
if type(id)=='number' then
return self.data.tileLayers[id]
elseif type(id)=='string' then
for i,l in ipairs(self.data.tileLayers) do
if l.name==id then return l end
end
return nil
else
error('layer id unknown')
end
end
function TMXTool:findObjectLayer(id)
if type(id)=='number' then
return self.data.objectGroups[id]
elseif type(id)=='string' then
for i,l in ipairs(self.data.objectGroups) do
if l.name==id then return l end
end
return nil
else
error('layer id unknown')
end
end
function TMXTool:buildGrid(tileLayerId)
assert(self.data,'not loaded')
local layer=assert(self:findTileLayer(tileLayerId), 'layer not found')
local tiles=layer.tiles
if not tiles then return nil end
local grid=MOAIGrid.new()
local w,h=self.data.width, self.data.height
grid:setSize(w,h, self.data.tilewidth,self.data.tileheight)
local ptr=1
for y=h,1 ,-1 do
for x=1,w do
grid:setTile(x,y,tiles[ptr]) --TODO: multiple tileset support ?
ptr=ptr+1
end
end
return grid
end
function TMXTool:getMapSize()
assert(self.data,'not loaded')
return self.data.width, self.data.height
end
function TMXTool:getMapPixelSize()
assert(self.data,'not loaded')
return self.data.width*self.data.tilewidth, self.data.height*self.data.tileheight
end
function TMXTool:getTileSize()
assert(self.data,'not loaded')
return self.data.tilewidth, self.data.tileheight
end
| mit |
RebootRevival/FFXI_Test | scripts/globals/items/wedge_of_chalaimbille.lua | 12 | 1214 | -----------------------------------------
-- ID: 5684
-- Item: wedge_of_chalaimbille
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health % 6 (cap 40)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5684);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 6);
target:addMod(MOD_FOOD_HP_CAP, 40);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 6);
target:delMod(MOD_FOOD_HP_CAP, 40);
end;
| gpl-3.0 |
jthomasbarry/aafmt | archive/book_chapters_LaTeX_original/pgf_3.0.1.tds/tex/generic/pgf/graphdrawing/lua/pgf/gd/bindings/BindingToPGF.lua | 2 | 7474 | -- Copyright 2012 by Till Tantau
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/bindings/BindingToPGF.lua,v 1.11 2015/06/08 21:58:24 tantau Exp $
-- Imports
local Storage = require "pgf.gd.lib.Storage"
---
-- This class, which is a subclass of |Binding|, binds the graph
-- drawing system to the \pgfname\ display system by overriding (that
-- is, implementing) the methods of the |Binding| class. As a typical
-- example, consider the implementation of the function |renderVertex|:
--
--\begin{codeexample}[code only, tikz syntax=false]
--function BindingToPGF:renderVertex(v)
-- local info = assert(self.infos[v], "thou shalt not modify the syntactic digraph")
-- tex.print(
-- string.format(
-- "\\pgfgdcallbackrendernode{%s}{%fpt}{%fpt}{%fpt}{%fpt}{%fpt}{%fpt}{%s}",
-- 'not yet positionedPGFINTERNAL' .. v.name,
-- info.x_min,
-- info.x_max,
-- info.y_min,
-- info.y_max,
-- v.pos.x,
-- v.pos.y,
-- info.box_count))
--end
--\end{codeexample}
--
-- As can be seen, the main job of this function is to call a function
-- on the \TeX\ layer that is called |\pgfgdcallbackrendernode|, which gets
-- several parameters like the name of the to-be-rendered node or the
-- (new) position for the node. For almost all methods of the
-- |Binding| class there is a corresponding ``callback'' macro on the
-- \TeX\ layer, all of which are implemented in the \pgfname\ library
-- |graphdrawing|. For details on these callbacks,
-- please consult the code of that file and of the class
-- |BindingToPGF| (they are not documented here since they are local
-- to the binding and should not be called by anyone other than the
-- binding class).
local BindingToPGF = {
storage = Storage.newTableStorage () -- overwrite default storage
}
BindingToPGF.__index = BindingToPGF
setmetatable(BindingToPGF, require "pgf.gd.bindings.Binding") -- subclass of Binding
-- Namespace
require("pgf.gd.bindings").BindingToPGF = BindingToPGF
-- Imports
local lib = require "pgf.gd.lib"
-- The implementation
-- Forward
local table_in_pgf_syntax
-- Scope handling
function BindingToPGF:resumeGraphDrawingCoroutine(text)
tex.print(text)
tex.print("\\pgfgdresumecoroutinetrue")
end
-- Declarations
function BindingToPGF:declareCallback(t)
tex.print("\\pgfgdcallbackdeclareparameter{" .. t.key .. "}{" .. (t.type or "nil") .. "}")
end
-- Rendering
function BindingToPGF:renderStart()
tex.print("\\pgfgdcallbackbeginshipout")
end
function BindingToPGF:renderStop()
tex.print("\\pgfgdcallbackendshipout")
end
-- Rendering collections
function BindingToPGF:renderCollection(collection)
tex.print("\\pgfgdcallbackrendercollection{".. collection.kind .. "}{"
.. table_in_pgf_syntax(collection.generated_options) .. "}")
end
function BindingToPGF:renderCollectionStartKind(kind, layer)
tex.print("\\pgfgdcallbackrendercollectionkindstart{" .. kind .. "}{" .. tostring(layer) .. "}")
end
function BindingToPGF:renderCollectionStopKind(kind, layer)
tex.print("\\pgfgdcallbackrendercollectionkindstop{" .. kind .. "}{" .. tostring(layer) .. "}")
end
-- Printing points
local function to_pt(x)
return string.format("%.12fpt", x)
end
-- Managing vertices (pgf nodes)
local boxes = {}
local box_count = 0
function BindingToPGF:everyVertexCreation(v)
local info = self.storage[v]
-- Save the box!
box_count = box_count + 1
boxes[box_count] = node.copy_list(tex.box[info.tex_box_number])
-- Special tex stuff, should not be considered by gd algorithm
info.box_count = box_count
end
function BindingToPGF:renderVertex(v)
local info = assert(self.storage[v], "thou shalt not modify the syntactic digraph")
tex.print(
string.format(
"\\pgfgdcallbackrendernode{%s}{%.12fpt}{%.12fpt}{%.12fpt}{%.12fpt}{%.12fpt}{%.12fpt}{%s}",
'not yet positionedPGFINTERNAL' .. v.name,
info.x_min,
info.x_max,
info.y_min,
info.y_max,
v.pos.x,
v.pos.y,
info.box_count))
end
function BindingToPGF:retrieveBox(index, box_num)
tex.box[box_num] = assert(boxes[index], "no box stored at given index")
boxes[index] = nil -- remove from memory
end
function BindingToPGF:renderVerticesStart()
tex.print("\\pgfgdcallbackbeginnodeshipout")
end
function BindingToPGF:renderVerticesStop()
tex.print("\\pgfgdcallbackendnodeshipout")
end
local function rigid(x)
if type(x) == "function" then
return x()
else
return x
end
end
-- Managing edges
function BindingToPGF:renderEdge(e)
local info = assert(self.storage[e], "thou shalt not modify the syntactic digraph")
local function get_anchor(e, anchor)
local a = e.options[anchor]
if a and a ~= "" then
return "." .. a
else
return ""
end
end
local callback = {
'\\pgfgdcallbackedge',
'{', e.tail.name .. get_anchor(e, "tail anchor"), '}',
'{', e.head.name .. get_anchor(e, "head anchor"), '}',
'{', e.direction, '}',
'{', info.pgf_options or "", '}',
'{', info.pgf_edge_nodes or "", '}',
'{', table_in_pgf_syntax(e.generated_options), '}',
'{'
}
local i = 1
while i <= #e.path do
local c = e.path[i]
assert (type(c) == "string", "illegal path operand")
if c == "lineto" then
i = i + 1
local d = rigid(e.path[i])
callback [#callback + 1] = '--(' .. to_pt(d.x) .. ',' .. to_pt(d.y) .. ')'
i = i + 1
elseif c == "moveto" then
i = i + 1
local d = rigid(e.path[i])
callback [#callback + 1] = '(' .. to_pt(d.x) .. ',' .. to_pt(d.y) .. ')'
i = i + 1
elseif c == "closepath" then
callback [#callback + 1] = '--cycle'
i = i + 1
elseif c == "curveto" then
local d1, d2, d3 = rigid(e.path[i+1]), rigid(e.path[i+2]), rigid(e.path[i+3])
i = i + 3
callback [#callback + 1] = '..controls(' .. to_pt(d1.x) .. ',' .. to_pt(d1.y) .. ')and('
.. to_pt(d2.x) .. ',' .. to_pt(d2.y) .. ')..'
callback [#callback + 1] = '(' .. to_pt(d3.x) .. ',' .. to_pt(d3.y) .. ')'
i = i + 1
else
error("illegal operation in edge path")
end
end
callback [#callback + 1] = '}'
-- hand TikZ code over to TeX
tex.print(table.concat(callback))
end
function BindingToPGF:renderEdgesStart()
tex.print("\\pgfgdcallbackbeginedgeshipout")
end
function BindingToPGF:renderEdgesStop()
tex.print("\\pgfgdcallbackendedgeshipout")
end
-- Vertex creation
function BindingToPGF:createVertex(init)
-- Now, go back to TeX...
coroutine.yield(
table.concat({
"\\pgfgdcallbackcreatevertex{", init.name, "}",
"{", init.shape, "}",
"{", table_in_pgf_syntax(init.generated_options), ",", init.pgf_options or "", "}",
"{", (init.text or ""), "}"
}))
-- ... and come back with a new node!
end
-- Local helpers
function table_in_pgf_syntax (t)
local prefix = "/graph drawing/"
local suffix = "/.try"
return table.concat( lib.imap( t, function(table)
if table.value then
return prefix .. table.key .. suffix .. "={" .. tostring(table.value) .. "}"
else
return prefix .. table.key .. suffix
end
end), ",")
end
return BindingToPGF | gpl-2.0 |
ashang/koreader | frontend/ui/downloadmgr.lua | 5 | 1146 | local PathChooser = require("ui/widget/pathchooser")
local UIManager = require("ui/uimanager")
local Screen = require("device").screen
local util = require("ffi/util")
local _ = require("gettext")
local DownloadMgr = {
title = _("Long press to choose download directory"),
onConfirm = function() end,
}
function DownloadMgr:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function DownloadMgr:chooseDir()
local lastdir = G_reader_settings:readSetting("lastdir")
local download_dir = G_reader_settings:readSetting("download_dir")
local path_chooser = PathChooser:new{
title = self.title,
height = Screen:getHeight(),
path = download_dir and (download_dir .. "/..") or lastdir,
show_hidden = G_reader_settings:readSetting("show_hidden"),
onConfirm = function(path)
-- hack to remove additional parent
if path:sub(-3, -1) == "/.." then
path = path:sub(1, -4)
end
self.onConfirm(util.realpath(path))
end
}
UIManager:show(path_chooser)
end
return DownloadMgr
| agpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Hall_of_Transference/npcs/_0e8.lua | 3 | 1703 | -----------------------------------
-- Area: Hall of Transference
-- NPC: Large Apparatus (Right) - Mea
-- !pos 290.253 -81.849 -42.381 14
-----------------------------------
package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Hall_of_Transference/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("MeaChipRegistration") == 0 and player:getVar("skyShortcut") == 1 and trade:hasItemQty(478,1) and trade:getItemCount() == 1) then
player:tradeComplete();
player:startEvent(0x00A4);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("MeaChipRegistration") == 1) then
player:messageSpecial(NO_RESPONSE_OFFSET+6); -- Device seems to be functioning correctly.
else
player:startEvent(0x00A3); -- Hexagonal Cones
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00A4) then
player:messageSpecial(NO_RESPONSE_OFFSET+4,478); -- You fit..
player:messageSpecial(NO_RESPONSE_OFFSET+5); -- Device has been repaired
player:setVar("MeaChipRegistration",1);
end
end;
| gpl-3.0 |
patrikrm13/patriks | plugins/all.lua | 88 | 4791 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(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.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
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 settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
jthomasbarry/aafmt | archive/book_chapters_LaTeX_original/pgf_3.0.1.tds/tex/generic/pgf/graphdrawing/lua/pgf/gd/doc/ogdf/energybased/FastMultipoleEmbedder.lua | 3 | 2038 | -- Copyright 2013 by Till Tantau
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/doc/ogdf/energybased/FastMultipoleEmbedder.lua,v 1.1 2013/03/15 15:04:41 tantau Exp $
local key = require 'pgf.gd.doc'.key
local documentation = require 'pgf.gd.doc'.documentation
local summary = require 'pgf.gd.doc'.summary
local example = require 'pgf.gd.doc'.example
--------------------------------------------------------------------------------
key "FastMultipoleEmbedder"
summary "Implementation of a fast multipole embedder by Martin Gronemann."
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
key "FastMultipoleEmbedder.numIterations"
summary "sets the maximum number of iterations"
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
key "FastMultipoleEmbedder.multipolePrec"
summary "sets the number of coefficients for the expansions. default = 4"
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
key "FastMultipoleEmbedder.defaultEdgeLength"
summary ""
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
key "FastMultipoleEmbedder.defaultNodeSize"
summary ""
--------------------------------------------------------------------------------
-- Local Variables:
-- mode:latex
-- End:
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Upper_Jeuno/npcs/Collet.lua | 3 | 2370 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Collet
-- Involved in Quests: A Clock Most Delicate, Save the Clock Tower
-- @zone 244
-- !pos -44 0 107
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then
a = player:getVar("saveTheClockTowerNPCz1"); -- NPC zone1
if (a == 0 or (a ~= 2 and a ~= 3 and a ~= 6 and a ~= 10 and a ~= 18 and a ~= 7 and a ~= 26 and a ~= 11 and
a ~= 22 and a ~= 14 and a ~= 19 and a ~= 15 and a ~= 23 and a ~= 27 and a ~= 30 and a ~= 31)) then
player:startEvent(0x0073,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getFameLevel(JEUNO) >= 5 and aClockMostdelicate == QUEST_AVAILABLE and player:getVar("aClockMostdelicateVar") == 0) then
player:startEvent(0x0070);
elseif (player:getVar("saveTheClockTowerVar") >= 1) then
player:startEvent(0x00a4);
elseif (player:getQuestStatus(JEUNO,THE_CLOCKMASTER) == QUEST_COMPLETED) then
player:startEvent(0x00a3);
else
player:startEvent(0x0072);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0070) then
player:setVar("aClockMostdelicateVar", 1);
elseif (csid == 0x0073) then
player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1);
player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 2);
end
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/The_Eldieme_Necropolis/npcs/Treasure_Chest.lua | 17 | 3277 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Treasure Chest
-- @zone 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/treasure");
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1039,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1039,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 1) then
player:addKeyItem(GUIDING_BELL);
player:messageSpecial(KEYITEM_OBTAINED,GUIDING_BELL); -- Guiding Bell (KI)
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]);
player:messageSpecial(GIL_OBTAINED,loot[2]);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1039);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
tabacof/adversarial | lbfgsb/lbfgsb.lua | 1 | 2671 | local lbfgsb = {}
local ffi = require 'ffi'
function lbfgsb.init(n_param, m_hist, bounds, lb, ub, print_level)
lbfgsb.lib = ffi.load("./lbfgsb/liblbfgsb.so")
ffi.cdef [[
void setulb_(int *n, int *m,double *x,double *l,double *u,int *nbd, double *f,
double *g,double *factr,double *pgtol,double *wa,int *iwa,
char *task, int *len_task, int *iprint, int *lsave,int *isave,double *dsave);
size_t strlen ( const char * str );
char * strncpy ( char * destination, const char * source, size_t num );
int strncmp ( const char * str1, const char * str2, size_t num );
]]
local int_p = ffi.typeof("int[1]")
local double_p = ffi.typeof("double[1]")
lbfgsb.len_task, lbfgsb.n, lbfgsb.m, lbfgsb.iprint = int_p(), int_p(), int_p(), int_p()
lbfgsb.f, lbfgsb.factr, lbfgsb.pgtol = double_p(), double_p(), double_p()
lbfgsb.task = ffi.new("char[61]")
lbfgsb.lsave, lbfgsb.nbd, lbfgsb.iwa, lbfgsb.isave = ffi.new("int[4]"), ffi.new("int[" .. n_param .. "]"), ffi.new("int[" .. 3*n_param .. "]"), ffi.new("int[44]")
lbfgsb.x, lbfgsb.l, lbfgsb.u = ffi.new("double[" .. n_param .. "]"), ffi.new("double[" .. n_param .. "]"), ffi.new("double[" .. n_param .. "]")
lbfgsb.g, lbfgsb.dsave = ffi.new("double[" .. n_param .. "]"), ffi.new("double[29]")
lbfgsb.wa = ffi.new("double[" .. 2*m_hist*n_param + 5*n_param + 11*m_hist*m_hist + 8*m_hist .. "]")
lbfgsb.n[0] = n_param
lbfgsb.m[0] = m_hist
lbfgsb.iprint[0] = print_level;
lbfgsb.factr[0]=1.0e+7;
lbfgsb.pgtol[0]=1.0e-5;
for i = 0, n_param - 1 do
lbfgsb.l[i] = lb[i + 1]
lbfgsb.u[i] = ub[i + 1]
lbfgsb.nbd[i] = bounds[i+1]
end
end
function lbfgsb.eval(feval, w, max_iter)
local lua_task = "START "
ffi.C.strncpy(lbfgsb.task, lua_task, 61);
lbfgsb.len_task[0] = ffi.C.strlen(lbfgsb.task)
local count = 0
for i = 0, lbfgsb.n[0] - 1 do
lbfgsb.x[i] = w[i + 1]
end
repeat
if lua_task:sub(1,2) == "FG" or lua_task:sub(1,5) == "START" then
for i= 0, lbfgsb.n[0] - 1 do
w[i + 1] = lbfgsb.x[i]
end
lbfgsb.f[0], lua_g = feval(w)
count = count + 1
for i= 0, lbfgsb.n[0] - 1 do
lbfgsb.g[i] = lua_g[i + 1]
end
end
lbfgsb.lib.setulb_(lbfgsb.n,lbfgsb.m,lbfgsb.x,lbfgsb.l,lbfgsb.u,lbfgsb.nbd,lbfgsb.f,lbfgsb.g,lbfgsb.factr,lbfgsb.pgtol,
lbfgsb.wa,lbfgsb.iwa,lbfgsb.task,lbfgsb.len_task,lbfgsb.iprint,lbfgsb.lsave,lbfgsb.isave,lbfgsb.dsave);
lua_task = ffi.string(lbfgsb.task)
until lua_task:sub(1,2) ~= "FG" and lua_task:sub(1,5) ~= "NEW_X" or count == max_iter
if count == max_iter then
print("LBFGSB: too many iterations, reached max of " .. max_iter)
end
end
return lbfgsb
| gpl-3.0 |
Afforess/Factorio-Stdlib | stdlib/utils/iter.lua | 1 | 2193 | --- Iterator library.
-- @module Utils.Iter
local Iter = {}
local pairs = pairs
local ipairs = ipairs
Iter.pairs = pairs
Iter.ipairs = ipairs
function Iter.spairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do
keys[#keys + 1] = k
end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
table.sort(
keys,
function(a, b)
return order(t, a, b)
end
)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
function Iter.top(t, stop)
local start = #t
stop = stop or 1
return function()
if start >= stop and t[start] ~= nil then
local cur = start
start = start - 1
return cur, t[cur]
end
return nil
end
end
function Iter.wrap(t, start, reverse)
--[[
-- Returns an iterator that iterates over integer keys in table `t` from the specified start position, wrapping
-- around and ending when it reaches `start` again.
--
-- `dir` specifies the direction to iterate (negative values for reverse, otherwise forward)
-- `start` specifies the start location. If `nil`, the first returned item will be at the at the start of the table
-- (or the end of the table, if `dir` is negative)
--
-- Behavior if the table changes size during iteration is undefined.
]]
local dir = (reverse and -1) or 1
local len = #t
local i = start
start = start or (reverse and len) or 1
return function()
if i == nil then
i = start
return i, t[i]
end
i = i + dir
if i < 1 then
i = i + len
elseif i > len then
i = i - len
end
if i == start then
return nil
end
return i, t[i]
end
end
function Iter.tpairs(...)
return ipairs(type(...) == 'table' and ... or { ... })
end
return Iter
| isc |
abbasgh12345/extreme11 | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
AmirPGA/pgahide | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
m13790115/ssss | plugins/meme.lua | 637 | 5791 | local helpers = require "OAuth.helpers"
local _file_memes = './data/memes.lua'
local _cache = {}
local function post_petition(url, arguments)
local response_body = {}
local request_constructor = {
url = url,
method = "POST",
sink = ltn12.sink.table(response_body),
headers = {},
redirect = false
}
local source = arguments
if type(arguments) == "table" then
local source = helpers.url_encode_arguments(arguments)
end
request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded"
request_constructor.headers["Content-Length"] = tostring(#source)
request_constructor.source = ltn12.source.string(source)
local ok, response_code, response_headers, response_status_line = http.request(request_constructor)
if not ok then
return nil
end
response_body = json:decode(table.concat(response_body))
return response_body
end
local function upload_memes(memes)
local base = "http://hastebin.com/"
local pet = post_petition(base .. "documents", memes)
if pet == nil then
return '', ''
end
local key = pet.key
return base .. key, base .. 'raw/' .. key
end
local function analyze_meme_list()
local function get_m(res, n)
local r = "<option.*>(.*)</option>.*"
local start = string.find(res, "<option.*>", n)
if start == nil then
return nil, nil
end
local final = string.find(res, "</option>", n) + #"</option>"
local sub = string.sub(res, start, final)
local f = string.match(sub, r)
return f, final
end
local res, code = http.request('http://apimeme.com/')
local r = "<option.*>(.*)</option>.*"
local n = 0
local f, n = get_m(res, n)
local ult = {}
while f ~= nil do
print(f)
table.insert(ult, f)
f, n = get_m(res, n)
end
return ult
end
local function get_memes()
local memes = analyze_meme_list()
return {
last_time = os.time(),
memes = memes
}
end
local function load_data()
local data = load_from_file(_file_memes)
if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then
data = get_memes()
-- Upload only if changed?
link, rawlink = upload_memes(table.concat(data.memes, '\n'))
data.link = link
data.rawlink = rawlink
serialize_to_file(data, _file_memes)
end
return data
end
local function match_n_word(list1, list2)
local n = 0
for k,v in pairs(list1) do
for k2, v2 in pairs(list2) do
if v2:find(v) then
n = n + 1
end
end
end
return n
end
local function match_meme(name)
local _memes = load_data()
local name = name:lower():split(' ')
local max = 0
local id = nil
for k,v in pairs(_memes.memes) do
local n = match_n_word(name, v:lower():split(' '))
if n > 0 and n > max then
max = n
id = v
end
end
return id
end
local function generate_meme(id, textup, textdown)
local base = "http://apimeme.com/meme"
local arguments = {
meme=id,
top=textup,
bottom=textdown
}
return base .. "?" .. helpers.url_encode_arguments(arguments)
end
local function get_all_memes_names()
local _memes = load_data()
local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n'
for k, v in pairs(_memes.memes) do
text = text .. '- ' .. v .. '\n'
end
text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/'
return text
end
local function callback_send(cb_extra, success, data)
if success == 0 then
send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == 'list' then
local _memes = load_data()
return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link
elseif matches[1] == 'listall' then
if not is_sudo(msg) then
return "You can't list this way, use \"!meme list\""
else
return get_all_memes_names()
end
elseif matches[1] == "search" then
local meme_id = match_meme(matches[2])
if meme_id == nil then
return "I can't match that search with any meme."
end
return "With that search your meme is " .. meme_id
end
local searchterm = string.gsub(matches[1]:lower(), ' ', '')
local meme_id = _cache[searchterm] or match_meme(matches[1])
if not meme_id then
return 'I don\'t understand the meme name "' .. matches[1] .. '"'
end
_cache[searchterm] = meme_id
print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3])
local url_gen = generate_meme(meme_id, matches[2], matches[3])
send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen})
return nil
end
return {
description = "Generate a meme image with up and bottom texts.",
usage = {
"!meme search (name): Return the name of the meme that match.",
"!meme list: Return the link where you can see the memes.",
"!meme listall: Return the list of all memes. Only admin can call it.",
'!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.',
'!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.',
},
patterns = {
"^!meme (search) (.+)$",
'^!meme (list)$',
'^!meme (listall)$',
'^!meme (.+) "(.*)" "(.*)"$',
'^!meme "(.+)" "(.*)" "(.*)"$',
"^!meme (.+) %- (.*) %- (.*)$"
},
run = run
}
| gpl-2.0 |
shiprabehera/kong | spec/03-plugins/27-request-termination/02-access_spec.lua | 2 | 5174 | local helpers = require "spec.helpers"
local cjson = require "cjson"
describe("Plugin: request-termination (access)", function()
local client, admin_client
setup(function()
helpers.run_migrations()
local api1 = assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "api1.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api1.id,
config = {
}
})
local api2 = assert(helpers.dao.apis:insert {
name = "api-2",
hosts = { "api2.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api2.id,
config = {
status_code=404
}
})
local api3 = assert(helpers.dao.apis:insert {
name = "api-3",
hosts = { "api3.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api3.id,
config = {
status_code=406,
message="Invalid"
}
})
local api4 = assert(helpers.dao.apis:insert {
name = "api-4",
hosts = { "api4.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api4.id,
config = {
body="<html><body><h1>Service is down for maintenance</h1></body></html>"
}
})
local api5 = assert(helpers.dao.apis:insert {
name = "api-5",
hosts = { "api5.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api5.id,
config = {
status_code=451,
content_type="text/html",
body="<html><body><h1>Service is down due to content infringement</h1></body></html>"
}
})
local api6 = assert(helpers.dao.apis:insert {
name = "api-6",
hosts = { "api6.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api6.id,
config = {
status_code=503,
body='{"code": 1, "message": "Service unavailable"}'
}
})
assert(helpers.start_kong())
client = helpers.proxy_client()
admin_client = helpers.admin_client()
end)
teardown(function()
if client and admin_client then
client:close()
admin_client:close()
end
helpers.stop_kong()
end)
describe("status code and message", function()
it("default status code and message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api1.request-termination.com"
}
})
local body = assert.res_status(503, res)
local json = cjson.decode(body)
assert.same({ message = "Service unavailable" }, json)
end)
it("status code with default message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api2.request-termination.com"
}
})
local body = assert.res_status(404, res)
local json = cjson.decode(body)
assert.same({ message = "Not found" }, json)
end)
it("status code with custom message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api3.request-termination.com"
}
})
local body = assert.res_status(406, res)
local json = cjson.decode(body)
assert.same({ message = "Invalid" }, json)
end)
end)
describe("status code and body", function()
it("default status code and body", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api4.request-termination.com"
}
})
local body = assert.res_status(503, res)
assert.equal([[<html><body><h1>Service is down for maintenance</h1></body></html>]], body)
end)
it("status code with default message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api5.request-termination.com"
}
})
local body = assert.res_status(451, res)
assert.equal([[<html><body><h1>Service is down due to content infringement</h1></body></html>]], body)
end)
it("status code with custom message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api6.request-termination.com"
}
})
local body = assert.res_status(503, res)
local json = cjson.decode(body)
assert.same({ code = 1, message = "Service unavailable" }, json)
end)
end)
end)
| apache-2.0 |
shiprabehera/kong | kong/plugins/response-transformer/migrations/postgres.lua | 5 | 1582 | return {
{
name = "2016-05-04-160000_resp_trans_schema_changes",
up = function(_, _, factory)
local plugins, err = factory.plugins:find_all {name = "response-transformer"}
if err then
return err
end
for _, plugin in ipairs(plugins) do
for _, action in ipairs {"remove", "add", "append", "replace"} do
plugin.config[action] = plugin.config[action] or {}
for _, location in ipairs {"json", "headers"} do
plugin.config[action][location] = plugin.config[action][location] or {}
end
end
local _, err = factory.plugins:update(plugin, plugin, {full = true})
if err then
return err
end
end
end,
down = function(_, _, factory)
local plugins, err = factory.plugins:find_all {name = "response-transformer"}
if err then
return err
end
for _, plugin in ipairs(plugins) do
plugin.config.replace = nil
plugin.config.append = nil
for _, action in ipairs {"remove", "add"} do
for _, location in ipairs {"json", "headers"} do
if plugin.config[action] ~= nil and next(plugin.config[action][location]) == nil then
plugin.config[action][location] = nil
end
end
if next(plugin.config[action]) == nil then
plugin.config[action] = nil
end
end
local _, err = factory.plugins:update(plugin, plugin, {full = true})
if err then
return err
end
end
end
}
}
| apache-2.0 |
TechAtNYU/wiki | extensions/Scribunto/engines/LuaCommon/lualib/luabit/hex.lua | 10 | 1830 | --[[---------------
Hex v0.4
-------------------
Hex conversion lib for lua.
How to use:
hex.to_hex(n) -- convert a number to a hex string
hex.to_dec(hex) -- convert a hex string(prefix with '0x' or '0X') to number
Part of LuaBit(http://luaforge.net/projects/bit/).
Under the MIT license.
copyright(c) 2006~2007 hanzhao (abrash_han@hotmail.com)
2013-02-20: Brad Jorsch: Fix to not try messing with globals, doesn't work in Scribunto
--]]---------------
local bit = require 'bit'
do
local function to_hex(n)
if(type(n) ~= "number") then
error("non-number type passed in.")
end
-- checking not float
if(n - math.floor(n) > 0) then
error("trying to apply bitwise operation on non-integer!")
end
if(n < 0) then
-- negative
n = bit.tobits(bit.bnot(math.abs(n)) + 1)
n = bit.tonumb(n)
end
hex_tbl = {'A', 'B', 'C', 'D', 'E', 'F'}
hex_str = ""
while(n ~= 0) do
last = math.mod(n, 16)
if(last < 10) then
hex_str = tostring(last) .. hex_str
else
hex_str = hex_tbl[last-10+1] .. hex_str
end
n = math.floor(n/16)
end
if(hex_str == "") then
hex_str = "0"
end
return "0x" .. hex_str
end
local function to_dec(hex)
if(type(hex) ~= "string") then
error("non-string type passed in.")
end
head = string.sub(hex, 1, 2)
if( head ~= "0x" and head ~= "0X") then
error("wrong hex format, should lead by 0x or 0X.")
end
v = tonumber(string.sub(hex, 3), 16)
return v;
end
--------------------
-- hex lib interface
local hex = {
to_dec = to_dec,
to_hex = to_hex,
}
return hex
end
--[[
-- test
d = 4341688
h = to_hex(d)
print(h)
print(to_dec(h))
for i = 1, 100000 do
h = hex.to_hex(i)
d = hex.to_dec(h)
if(d ~= i) then
error("failed " .. i .. ", " .. h)
end
end
--]]
| gpl-2.0 |
johannes-mueller/ardour | scripts/bounce_replace.lua | 1 | 2985 | ardour { ["type"] = "EditorAction", name = "Bounce+Replace Regions",
license = "MIT",
author = "Ardour Team",
description = [[Bounce selected regions with processing and replace region]]
}
function factory (params) return function ()
-- there is currently no direct way to find the track
-- corresponding to a [selected] region
function find_track_for_region (region_id)
for route in Session:get_tracks():iter() do
local track = route:to_track();
local pl = track:playlist ()
if not pl:region_by_id (region_id):isnil () then
return track
end
end
assert (0); -- can't happen, region must be in a playlist
end
-- get selection
-- http://manual.ardour.org/lua-scripting/class_reference/#ArdourUI:Selection
local sel = Editor:get_selection ()
-- prepare undo operation
Session:begin_reversible_command ("Bounce+Replace Regions")
local add_undo = false -- keep track if something has changed
-- Iterate over Regions part of the selection
-- http://manual.ardour.org/lua-scripting/class_reference/#ArdourUI:RegionSelection
for r in sel.regions:regionlist ():iter () do
-- each of the items 'r' is a
-- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:Region
local track = find_track_for_region (r:to_stateful():id())
local playlist = track:playlist ()
-- clear existing changes, prepare "diff" of state for undo
playlist:to_stateful ():clear_changes ()
-- bounce the region with processing
local region = track:bounce_range (r:position (), r:position() + r:length (), ARDOUR.InterThreadInfo (), track:main_outs (), false);
-- remove old region..
playlist:remove_region (r);
-- ..and add the newly bounced one
playlist:add_region (region, r:position (), 1, false, 0, false)
-- create a diff of the performed work, add it to the session's undo stack
-- and check if it is not empty
if not Session:add_stateful_diff_command (playlist:to_statefuldestructible ()):empty () then
add_undo = true
end
end
-- all done, commit the combined Undo Operation
if add_undo then
-- the 'nil' Command here mean to use the collected diffs added above
Session:commit_reversible_command (nil)
else
Session:abort_reversible_command ()
end
end end
function icon (params) return function (ctx, width, height, fg)
local wh = math.min (width, height) * .5
local ar = wh * .2
ctx:set_line_width (1)
function stroke_outline (c)
ctx:set_source_rgba (0, 0, 0, 1)
ctx:stroke_preserve ()
ctx:set_source_rgba (c, c, c, 1)
ctx:fill ()
end
ctx:rectangle (wh - wh * .6, wh - .7 * wh, wh * 1.2, .5 * wh)
stroke_outline (.7)
ctx:rectangle (wh - wh * .6, wh + .1 * wh, wh * 1.2, .5 * wh)
stroke_outline (.9)
-- arrow
ctx:set_source_rgba (0, 1, 0, 1)
ctx:set_line_width (ar * .7)
ctx:move_to (wh, wh - .5 * wh)
ctx:rel_line_to (0, wh)
ctx:stroke ()
ctx:move_to (wh, wh + .5 * wh)
ctx:rel_line_to (-ar, -ar)
ctx:rel_line_to (2 * ar, 0)
ctx:close_path ()
ctx:stroke ()
end end
| gpl-2.0 |
liruqi/bigfoot | Interface/AddOns/Bagnon/common/core/settings.lua | 1 | 3673 | --[[
settings.lua
Methods for initializing and sharing settings between characters
--]]
local ADDON, Addon = ...
local SETS = ADDON .. '_Sets'
local CURRENT_VERSION = GetAddOnMetadata(ADDON, 'Version')
local L = LibStub('AceLocale-3.0'):GetLocale(ADDON)
local function SetDefaults(target, defaults)
defaults.__index = nil
for k, v in pairs(defaults) do
if type(v) == 'table' then
target[k] = SetDefaults(target[k] or {}, v)
end
end
defaults.__index = defaults
return setmetatable(target, defaults)
end
local FrameDefaults = {
enabled = true,
money = true, broker = true,
bagFrame = true, sort = true, search = true, options = true,
strata = 'HIGH',
scale = 1, alpha = 1,
color = {0, 0, 0, 0.5},
width = 512, height = 512,
x = 0, y = 0,
itemScale = 1, spacing = 2,
brokerObject = 'BagnonLauncher',
hiddenBags = {},
}
local ProfileDefaults = {
inventory = SetDefaults({
borderColor = {1, 1, 1, 1},
leftSideFilter = true,
point = 'BOTTOMRIGHT',
x = -50, y = 100,
columns = 8,
width = 384,
}, FrameDefaults),
bank = SetDefaults({
borderColor = {1, 1, 0, 1},
point = 'LEFT',
columns = 12,
x = 95
}, FrameDefaults),
vault = SetDefaults({
borderColor = {1, 0, 0.98, 1},
point = 'LEFT',
columns = 8,
x = 95
}, FrameDefaults),
guild = SetDefaults({
borderColor = {0, 1, 0, 1},
point = 'CENTER',
columns = 7,
}, FrameDefaults)
}
--[[ Settings ]]--
function Addon:StartupSettings()
_G[SETS] = SetDefaults(_G[SETS] or {}, {
version = CURRENT_VERSION,
global = SetDefaults({}, ProfileDefaults),
players = {},
resetPlayer = true,
displayBank = true, closeBank = true, displayAuction = true, displayGuild = true, displayMail = true, displayTrade = true, displayCraft = true,
flashFind = true, tipCount = true, fading = true,
glowAlpha = 0.5,
glowQuality = true, glowNew = true, glowQuest = true, glowSets = true, glowUnusable = true,
emptySlots = true, colorSlots = true,
leatherColor = {1, .6, .45},
enchantColor = {0.64, 0.83, 1},
inscribeColor = {.64, 1, .82},
engineerColor = {.68, .63, .25},
tackleColor = {0.42, 0.59, 1},
refrigeColor = {1, .5, .5},
gemColor = {1, .65, .98},
mineColor = {1, .81, .38},
herbColor = {.5, 1, .5},
reagentColor = {1, .87, .68},
normalColor = {1, 1, 1},
})
self.sets = _G[SETS]
self:UpdateSettings()
for _, player in self.Cache:IteratePlayers() do
self:StartupProfile(player)
end
self.profile = self:GetProfile()
end
function Addon:UpdateSettings()
local expansion, patch, release = strsplit('.', self.sets.version)
local version = tonumber(expansion) * 10000 + tonumber(patch or 0) * 100 + tonumber(release or 0)
if self.sets.frames then
for frame, sets in pairs(self.sets.frames) do
self.sets.global[frame] = SetDefaults(sets, self.sets.global[frame])
end
self.sets.frames = nil
end
if self.sets.version ~= CURRENT_VERSION then
self.sets.version = CURRENT_VERSION
self:Print(format(L.Updated, self.sets.version))
end
end
--[[ Profiles ]]--
function Addon:StartupProfile(player)
local realm, name = self.Cache:GetPlayerAddress(player)
self.sets.players[realm] = self.sets.players[realm] or {}
self:SetProfile(self.sets.players[realm][name], player)
end
function Addon:SetProfile(profile, player)
local realm, name = self.Cache:GetPlayerAddress(player)
self.sets.players[realm][name] = profile and SetDefaults(profile, ProfileDefaults)
end
function Addon:GetProfile(player)
return self:GetSpecificProfile(player) or self.sets.global
end
function Addon:GetSpecificProfile(player)
local realm, name = self.Cache:GetPlayerAddress(player)
return self.sets.players[realm][name]
end | mit |
RockySeven3161/MonsterBot | plugins/owners.lua | 284 | 12473 |
local function lock_group_namemod(msg, data, target)
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)
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)
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)
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)
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)
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)
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 show_group_settingsmod(msg, data, target)
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 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
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
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 set_description(target, about)
local data = load_data(_config.moderation.data)
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 run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) 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 to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
gastrodia/awesome | spec/wibox/layout/align_spec.lua | 1 | 8040 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2014 Uli Schlachter
---------------------------------------------------------------------------
local align = require("wibox.layout.align")
local utils = require("wibox.test_utils")
describe("wibox.layout.flex", function()
before_each(utils.stub_draw_widget)
after_each(utils.revert_draw_widget)
describe("expand=none", function()
local layout
before_each(function()
layout = align.vertical()
layout:set_expand("none")
end)
it("empty layout fit", function()
assert.widget_fit(layout, { 10, 10 }, { 0, 0 })
end)
it("empty layout draw", function()
layout:draw(nil, nil, 0, 0)
utils.check_widgets_drawn({})
end)
describe("with widgets", function()
local first, second, third
before_each(function()
first = utils.widget_stub(10, 10)
second = utils.widget_stub(15, 15)
third = utils.widget_stub(10, 10)
layout:set_first(first)
layout:set_second(second)
layout:set_third(third)
end)
describe("with enough space", function()
it("fit", function()
assert.widget_fit(layout, { 100, 100 }, { 15, 35 })
end)
it("draw", function()
layout:draw("wibox", "cr", 100, 100)
utils.check_widgets_drawn({
{ first, 0, 0, 100, 10 },
{ third, 0, 90, 100, 10 },
{ second, 0, 42, 100, 15 },
})
end)
end)
describe("without enough height", function()
it("fit", function()
assert.widget_fit(layout, { 5, 100 }, { 5, 35 })
end)
it("draw", function()
layout:draw("wibox", "cr", 5, 100)
utils.check_widgets_drawn({
{ first, 0, 0, 5, 10 },
{ third, 0, 90, 5, 10 },
{ second, 0, 42, 5, 15 },
})
end)
end)
describe("without enough width", function()
it("fit", function()
assert.widget_fit(layout, { 100, 20 }, { 15, 20 })
end)
it("draw", function()
layout:draw("wibox", "cr", 100, 20)
utils.check_widgets_drawn({
{ first, 0, 0, 100, 2 },
{ third, 0, 18, 100, 2 },
{ second, 0, 2, 100, 15 },
})
end)
end)
end)
end)
describe("expand=outside", function()
local layout
before_each(function()
layout = align.vertical()
layout:set_expand("outside")
end)
it("empty layout fit", function()
assert.widget_fit(layout, { 10, 10 }, { 0, 0 })
end)
it("empty layout draw", function()
layout:draw(nil, nil, 0, 0)
utils.check_widgets_drawn({})
end)
describe("with widgets", function()
local first, second, third
before_each(function()
first = utils.widget_stub(10, 10)
second = utils.widget_stub(15, 15)
third = utils.widget_stub(10, 10)
layout:set_first(first)
layout:set_second(second)
layout:set_third(third)
end)
describe("with enough space", function()
it("fit", function()
assert.widget_fit(layout, { 100, 100 }, { 15, 35 })
end)
it("draw", function()
layout:draw("wibox", "cr", 100, 100)
utils.check_widgets_drawn({
{ first, 0, 0, 100, 42 },
{ third, 0, 58, 100, 42 },
{ second, 0, 42, 100, 15 },
})
end)
end)
describe("without enough height", function()
it("fit", function()
assert.widget_fit(layout, { 5, 100 }, { 5, 35 })
end)
it("draw", function()
layout:draw("wibox", "cr", 5, 100)
utils.check_widgets_drawn({
{ first, 0, 0, 5, 42 },
{ third, 0, 58, 5, 42 },
{ second, 0, 42, 5, 15 },
})
end)
end)
describe("without enough width", function()
it("fit", function()
assert.widget_fit(layout, { 100, 20 }, { 15, 20 })
end)
it("draw", function()
layout:draw("wibox", "cr", 100, 20)
utils.check_widgets_drawn({
{ first, 0, 0, 100, 2 },
{ third, 0, 18, 100, 2 },
{ second, 0, 2, 100, 15 },
})
end)
end)
end)
end)
describe("expand=inside", function()
local layout
before_each(function()
layout = align.vertical()
layout:set_expand("inside")
end)
it("empty layout fit", function()
assert.widget_fit(layout, { 10, 10 }, { 0, 0 })
end)
it("empty layout draw", function()
layout:draw(nil, nil, 0, 0)
utils.check_widgets_drawn({})
end)
describe("with widgets", function()
local first, second, third
before_each(function()
first = utils.widget_stub(10, 10)
second = utils.widget_stub(15, 15)
third = utils.widget_stub(10, 10)
layout:set_first(first)
layout:set_second(second)
layout:set_third(third)
end)
describe("with enough space", function()
it("fit", function()
assert.widget_fit(layout, { 100, 100 }, { 15, 35 })
end)
it("draw", function()
layout:draw("wibox", "cr", 100, 100)
utils.check_widgets_drawn({
{ first, 0, 0, 100, 10 },
{ third, 0, 90, 100, 10 },
{ second, 0, 10, 100, 80 },
})
end)
end)
describe("without enough height", function()
it("fit", function()
assert.widget_fit(layout, { 5, 100 }, { 5, 35 })
end)
it("draw", function()
layout:draw("wibox", "cr", 5, 100)
utils.check_widgets_drawn({
{ first, 0, 0, 5, 10 },
{ third, 0, 90, 5, 10 },
{ second, 0, 10, 5, 80 },
})
end)
end)
describe("without enough width", function()
it("fit", function()
assert.widget_fit(layout, { 100, 20 }, { 15, 20 })
end)
it("draw", function()
layout:draw("wibox", "cr", 100, 20)
--- XXX: Shouldn't this also draw part of the second widget?
utils.check_widgets_drawn({
{ first, 0, 0, 100, 10 },
{ third, 0, 10, 100, 10 },
})
end)
end)
end)
end)
end)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Ali-2h/ali | plugins/add_bot.lua | 189 | 1492 | --[[
Bot can join into a group by replying a message contain an invite link or by
typing !add [invite link].
URL.parse cannot parsing complicated message. So, this plugin only works for
single [invite link] in a post.
[invite link] may be preceeded but must not followed by another characters.
--]]
do
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
i = 0
for k,segment in pairs(parsed_path) do
i = i + 1
if segment == 'joinchat' then
invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '')
break
end
end
return invite_link
end
local function action_by_reply(extra, success, result)
local hash = parsed_url(result.text)
join = import_chat_link(hash, ok_cb, false)
end
function run(msg, matches)
if is_sudo(msg) then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
elseif matches[1] then
local hash = parsed_url(matches[1])
join = import_chat_link(hash, ok_cb, false)
end
end
end
return {
description = 'Invite the bot into a group chat via its invite link.',
usage = {
'!AddBot : Join a group by replying a message containing invite link.',
'!AddBot [invite_link] : Join into a group by providing their [invite_link].'
},
patterns = {
'^[/!](addBot)$',
'^[/!](ddBot) (.*)$'
},
run = run
}
end
| gpl-2.0 |
liruqi/bigfoot | Interface/AddOns/premade-filter/localization/itIT.lua | 1 | 3561 | local _, L = ...;
if GetLocale() ~= "itIT" then return end
--Translation missing
-- L["Actions"] = ""
--Translation missing
-- L["Alive"] = ""
--Translation missing
-- L["Any"] = ""
--Translation missing
-- L["Are you sure you want to delete filter set?"] = ""
--Translation missing
-- L["At least one word"] = ""
--Translation missing
-- L["Attention! Update interval shorter than 15 seconds may cause the game to run slow and impact your gaming experience!!!"] = ""
--Translation missing
-- L["Boss status colors"] = ""
--Translation missing
-- L["By hiding the window you can activate background search so you can do anything else in the game."] = ""
--Translation missing
-- L["Click [+] to open window within extended features."] = ""
--Translation missing
-- L["Defeated"] = ""
--Translation missing
-- L["Define minimum and/or maximum number of players of any role."] = ""
--Translation missing
-- L["Enable sound notifications"] = ""
--Translation missing
-- L["Enter filter set name"] = ""
--Translation missing
-- L["Enter the words you want to be present or absent in group title and comment."] = ""
--Translation missing
-- L["Exclude words"] = ""
--Translation missing
-- L["EXPERIMENTAL"] = ""
--Translation missing
-- L["Filter set"] = ""
--Translation missing
-- L["For example if you are a tank you can set maximum number of tanks to 1 and you get the groups you are guaranteed to have a spot."] = ""
--Translation missing
-- L["found new group"] = ""
--Translation missing
-- L["found new player"] = ""
--Translation missing
-- L["If a group is not created by the addon this option is ignored."] = ""
--Translation missing
-- L["If you want to join a group of highly equipped characters you can setup minimum item level defined for its members."] = ""
--Translation missing
-- L["Include words"] = ""
--Translation missing
-- L["Monitor new groups in background?"] = ""
--Translation missing
-- L["Monitoring"] = ""
--Translation missing
-- L["More"] = ""
--Translation missing
-- L["More options"] = ""
--Translation missing
-- L["New filter set"] = ""
--Translation missing
-- L["New version available"] = ""
--Translation missing
-- L["Notifications"] = ""
--Translation missing
-- L["Notify in chat on new group"] = ""
--Translation missing
-- L["Notify in chat on new player"] = ""
--Translation missing
-- L["Select group activity: quest, dungeon, raid, difficulty"] = ""
--Translation missing
-- L["Select the roles you can fulfill."] = ""
--Translation missing
-- L["The addon notifies you if it finds a group that matches your requirements."] = ""
--Translation missing
-- L["The filters take effect when you click this button. The changes don't take effect until you do that."] = ""
--Translation missing
-- L["The words you don't want"] = ""
--Translation missing
-- L["The words you want"] = ""
--Translation missing
-- L["Update interval (sec.)"] = ""
--Translation missing
-- L["Want to find a mythic raid? Choose your realm only."] = ""
--Translation missing
-- L["Works only on premades created with Premade Filter addon"] = ""
--Translation missing
-- L["You can find a group that uses specific voice chat software or a group tha doesn't use voice chat at all."] = ""
--Translation missing
-- L["You can mark the bosses you want to be still alive with [v] and the bosses you want to be already defeated by [-]."] = ""
--Translation missing
-- L["You can save the filters to use them in future."] = ""
--Translation missing
-- L["You want at least one of these words"] = ""
| mit |
liruqi/bigfoot | Interface/AddOns/DBM-SiegeOfOrgrimmarV2/localization.tw.lua | 1 | 17051 | if GetLocale() ~= "zhTW" then return end
local L
---------------
-- Immerseus --
---------------
L= DBM:GetModLocalization(852)
L:SetWarningLocalization({
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
SoundPZD = "語音警告:當$spell:143579疊加超過三層時提示注意停手",
InfoFrame = "資訊框:顯示擊殺和淨化的軟泥怪數量",
dr = "減傷提示[警報會在第一個軟泥怪撞擊到本體時提示]",
dr1 = "$spell:143469 1",
dr2 = "$spell:143469 2",
dr3 = "$spell:143469 3",
dr4 = "$spell:143469 4",
dr5 = "$spell:143469 5",
dr6 = "$spell:143469 6",
dr7 = "$spell:143469 7",
dr8 = "$spell:143469 8",
})
L:SetMiscLocalization({
kill = "擊殺",
clean = "淨化",
Victory = "啊,你成功了!水又再次純淨了。"
})
---------------------------
-- The Fallen Protectors --
---------------------------
L= DBM:GetModLocalization(849)
L:SetWarningLocalization({
})
L:SetTimerLocalization({
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
InfoFrame = "資訊框:首領血量監視",
SoundBD = "語音警告:驅散$spell:143434",
dr1 = "減傷提示:$spell:143491 1/4",
dr2 = "減傷提示:$spell:143491 2/4",
dr3 = "減傷提示:$spell:143491 3/4",
dr4 = "減傷提示:$spell:143491 4/4",
BaneGridCount = "特殊:爲$spell:143434啟用GRID編號支持(提示位置等更多相關選項請在GRID中設置。擴散出現的状态不會顯示編號)",
optOC = "當苦痛印記疊加多少層時提示傳遞",
imm = "立刻提示",
five = "5層",
ten = "10層",
fift = "15層",
twty = "20層",
none = "從不提示",
optDD = "武僧分身打斷提示",
alldd = "總是提示(如果你選他為目標或焦點)",
DD1 = "打斷1",
DD2 = "打斷2",
DD3 = "打斷3",
nodd = "不提示",
SetIconOnStrike = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(143962),
RangeFrame = DBM_CORE_AUTO_RANGE_OPTION_TEXT:format(5, 143423)--For heroic. Need to chage smart range frame?
})
L:SetMiscLocalization({
DBM_GridBaneCount = "DBM編號-暗言術:蠱",
BaneRaidFrameCount = "編號順序使用暴雪團隊框架的排序",
optBaneGridCount = "閃動顯示編號:",
})
---------------------------
-- Norushen --
---------------------------
L= DBM:GetModLocalization(866)
L:SetWarningLocalization({
specWarnTestIn = "隊友入場:%s",
specWarnTestOut = "隊友出場:%s"
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
InfoFrame = "資訊框:$journal:8252",
InfoFrame2 = "資訊框:$spell:144452中的隊友",
specWarnTestIn = "特別警告:你監視的隊友入場",
specWarnTestOut = "特別警告:你監視的隊友出場",
prevplayer = "輸入一個隊友名,在他入場和離場時都會通知你"
})
L:SetMiscLocalization({
nameset = "諾努衫內場監視",
wasteOfTime = "很好,我會創造一個力場隔離你們的腐化。"
})
------------------
-- Sha of Pride --
------------------
L= DBM:GetModLocalization(867)
L:SetWarningLocalization({
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
SoundQS = "額外驅散提示:當你帶有$spell:144359時技能一旦冷卻即提示驅散",
HudMAPBP = "高級定位監視(HUD):$spell:144911",
HudMAPCP = "高級定位監視(HUD):$spell:144574",
HudMAPAoP = "高級定位監視(HUD):$spell:146817",
RangeFrame = DBM_CORE_AUTO_RANGE_OPTION_TEXT:format(5, 146817),
SetIconOnMark = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(144351),
InfoFrame = "資訊框:$journal:8255",
dr1 = "減傷提示:$spell:144400 1/3",
dr2 = "減傷提示:$spell:144400 2/3",
dr3 = "減傷提示:$spell:144400 3/3",
})
L:SetMiscLocalization({
})
--------------
-- Galakras --
--------------
L= DBM:GetModLocalization(868)
L:SetTimerLocalization({
timerAddsCD = "下一波小兵",
timerTowerCD = "下一個塔樓攻破"
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
SoundZQ = "語音警告:$spell:147328",
SoundTT = "語音警告:$spell:146753",
timerAddsCD = "計時器:下一波小怪",
timerTowerCD = "計時器:下一個塔樓攻破",
FixateIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(147068),
InfoFrame = "資訊框:下一波$journal:8427",
flamecount = "減傷提示:第二階段時第幾個火球提示減傷"
})
L:SetMiscLocalization({
nameset = "葛拉卡斯",
Pull = "龍喉氏族,奪回碼頭,把他們推進海裡!以地獄吼及正統部落之名!",
newForces1 = "他們來了!",
newForces1H = "趕快把她弄下來,讓我用手掐死她。",
newForces2 = "龍喉氏族,前進!",
newForces3 = "為了地獄吼!",
newForces4 = "下一隊,前進!",
tower = "的門已經遭到破壞!"
})
--------------------
--Iron Juggernaut --
--------------------
L= DBM:GetModLocalization(864)
L:SetWarningLocalization({
})
L:SetTimerLocalization({
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
timerAssaultModeCD = DBM_CORE_AUTO_TIMER_OPTIONS.next:format("ej8177"),
timerSiegeModeCD = DBM_CORE_AUTO_TIMER_OPTIONS.next:format("ej8178"),
RangeFrame = DBM_CORE_AUTO_RANGE_OPTION_TEXT:format(6, 144154),
dr = "減傷提示:$spell:144485 [此順序每次攻城階段都會重置]",
dr1 = "$spell:144485 1",
dr2 = "$spell:144485 2",
dr3 = "$spell:144485 3",
dr4 = "$spell:144485 4",
dr5 = "$spell:144485 5",
dr6 = "$spell:144485 6"
})
L:SetMiscLocalization({
})
--------------------------
-- Kor'kron Dark Shaman --
--------------------------
L= DBM:GetModLocalization(856)
L:SetWarningLocalization({
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
SoundTL = "語音警告:$spell:144330的十秒預警(即使不是你的$spell:144330也會報警,這是一個為治療者製作的提示)",
dr = "減傷提示[警報會在撞擊前4秒提示]",
dr1 = "$spell:143973 1/6",
dr2 = "$spell:143973 2/6",
dr3 = "$spell:143973 3/6",
dr4 = "$spell:143973 4/6",
dr5 = "$spell:143973 5/6",
dr6 = "$spell:143973 6/6",
SoundEle = "特殊:啟用[元素薩滿]技能提示",
SoundEnh = "特殊:啟用[增強薩滿]技能提示",
SetIconOnToxicMists = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(144089),
RangeFrame = DBM_CORE_AUTO_RANGE_OPTION_TEXT:format(4, 143990)
})
L:SetMiscLocalization({
PrisonYell = "%s 的囚牢即將結束 (%d)"
})
---------------------
-- General Nazgrim --
---------------------
L= DBM:GetModLocalization(850)
L:SetWarningLocalization({
warnDefensiveStanceSoon = "%d秒後 防禦姿態"
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
SoundDS = "語音警告:驅散$spell:143475",
SoundIFS = "語音警告:打斷$journal:7923",
SoundISM = "語音警告:打斷$journal:7925",
InfoFrame = "資訊框:怒氣監視器",
SetIconOnAdds = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format("ej7920"),
warnDefensiveStanceSoon = "預先警告:$spell:143593 (5秒前)"
})
L:SetMiscLocalization({
newForces1 = "戰士們,快點過來!",
newForces2 = "守住大門!",
newForces3 = "重整部隊!",
newForces4 = "柯爾克隆,來我身邊!",
newForces5 = "下一隊,來前線!",
allForces = "所有科爾克隆...聽我號令...殺死他們!",
Handslipped1 = "不好意思,手滑打了下BOSS",
Handslipped2 = "哎呀,手又滑了",
Handslipped3 = "難道我這隻手是肥皂做的?",
Handslipped4 = "請斬斷我這隻罪惡之手吧!我居然完全忘了要停手!"
})
-----------------
-- Malkorok -----
-----------------
L= DBM:GetModLocalization(846)
L:SetWarningLocalization({
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
Malhelper = "===特殊:開啟亞煞極之息輔助圖示 (/mal)===",
MalhelperSend = "===輔助圖示:啟用手動修正模式===",
LTshow = "長效特別警告:顯示護盾吸收量",
dr = "減傷提示:$spell:142986 (爆炸前提示)",
dr1 = "$spell:142986 1",
dr2 = "$spell:142986 2",
dr3 = "$spell:142986 3",
dr4 = "$spell:142986 4",
dr5 = "$spell:142986 5",
dr6 = "$spell:142986 6",
dr7 = "$spell:142986 7",
dr8 = "$spell:142986 8",
dr9 = "$spell:142986 9",
dr10 = "$spell:142986 10",
dr11 = "$spell:142986 11",
dr12 = "$spell:142986 12",
HudMAP = "高級定位監視(HUD):$spell:142913",
SetIconOnDisplacedEnergy= DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(142913),
RangeFrame = DBM_CORE_AUTO_RANGE_OPTION_TEXT_SHORT:format("8/5")
})
MHExRTL.panelbossmodsmalkorokdanger ="! 危險 !"
MHExRTL.sendnote ="開啟手動修改圖示,左鍵選擇,右鍵取消,你的修改會被同步給全團,請謹慎使用!!!"
------------------------
-- Spoils of Pandaria --
------------------------
L= DBM:GetModLocalization(870)
L:SetWarningLocalization({
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
LTZD = "長效特別警告:你中了$spell:145987",
RangeFrame = DBM_CORE_AUTO_RANGE_OPTION_TEXT:format(10, 145987),
Filterarea = "其他:使用更嚴格的方式判定所在區域"
})
L:SetMiscLocalization({
wasteOfTime = "我們在錄音嗎?有嗎?好。哥布林-泰坦控制模組開始運作,請後退。",
Module1 = "模組一號已準備好系統重置。",
Victory = "模組二號已準備好系統重置。"
})
---------------------------
-- Thok the Bloodthirsty --
---------------------------
L= DBM:GetModLocalization(851)
L:SetWarningLocalization({
specWarnDevotion = "%s 開啓了虔誠光環"
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
SoundPX = "倒计时:$spell:143343",
LTRange = "長效特別警告:P1$spell:143343層數/P2首領距離",
optDD = "毒血驅散鏈",
DD1 = "驅散1",
DD2 = "驅散2",
DD3 = "驅散3",
nodd = "我不驅散",
dr = "減傷提示:$spell:143343 (此順序每次轉階段都會重置)",
dr1 = "$spell:143343 1",
dr2 = "$spell:143343 2",
dr3 = "$spell:143343 3",
dr4 = "$spell:143343 4",
dr5 = "$spell:143343 5",
dr6 = "$spell:143343 6",
dr7 = "$spell:143343 7",
dr8 = "$spell:143343 8",
dr9 = "$spell:143343 9",
dr10 = "$spell:143343 10",
dr11 = "$spell:143343 11",
dr12 = "$spell:143343 12",
dr13 = "$spell:143343 13",
dr14 = "$spell:143343 14",
dr15 = "$spell:143343 15",
dr16 = "$spell:143343 16",
dr17 = "$spell:143343 17",
dr18 = "$spell:143343 18",
dr19 = "$spell:143343 19",
dr20 = "$spell:143343 20",
dr21 = "$spell:143343 21",
dr22 = "$spell:143343 22",
dr23 = "$spell:143343 23",
dr24 = "$spell:143343 24",
dr25 = "$spell:143343 25",
dr26 = "$spell:143343 26",
dr27 = "$spell:143343 27",
dr28 = "$spell:143343 28",
dr29 = "$spell:143343 29",
dr30 = "$spell:143343 30",
specWarnDevotion = "特別警告:$spell:31821",
RangeFrame = "距離監視(10碼):動態",
FixateIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(143445)
})
L:SetMiscLocalization({
})
----------------------------
-- Siegecrafter Blackfuse --
----------------------------
L= DBM:GetModLocalization(865)
L:SetWarningLocalization({
warnCC = "%s的[%s]打破了%s的%s(首次破控)。"
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
SoundFMD = "語音警告:$spell:144208前提示伐木機快打",
SoundDL = "語音警告:地雷清理提示",
LTFD = "長效特別警告:顯示$spell:143266和$spell:143828震動圖標提示",
LTHX = "長效特別警告:顯示火線變換計時",
HudMAP = "高級定位監視(HUD):$spell:143828",
SoundCZ = "語音警告:伐木機$spell:145444AOE預警(1-3次)",
SoundCZ4 = "減傷提示:伐木機第四次$spell:145444 (3層buff)",
SoundCZ5 = "減傷提示:伐木機第五次$spell:145444 (4層buff)",
SoundCS1 = "語音警告:傳送帶一組提前10秒預警",
SoundCS2 = "語音警告:傳送帶二組提前10秒預警",
ShowDps = "顯示你當前組別擊殺傳送帶武器的輸出數據",
warnCC = "警告:地雷破控信息(只顯示每輪第一個破控)",
InfoFrame = "資訊框:$journal:8202",
optCS = "傳送帶啟動提示",
CSA = "傳送帶一組",
CSB = "傳送帶二組",
CSALL = "總是提示",
none = "我不去",
optCSKILL1 = "擊殺提示:第1輪",
optCSKILL2 = "第2輪",
optCSKILL3 = "第3輪",
optCSKILL4 = "第4輪",
optCSKILL5 = "第5輪",
optCSKILL6 = "第6輪",
optCSKILL7 = "第7輪",
optCSKILL8 = "第8輪",
optCSKILL9 = "第9輪",
optCSKILL10 = "第10輪",
optCSKILL11 = "第11輪",
optCSKILL12 = "第12輪",
optCSKILL13 = "第13輪",
optCSKILL14 = "第14輪",
optCSKILL15 = "第15輪",
killdl = "地雷",
killfd = "飛彈",
killjg = "激光",
killdc = "電磁鐵",
killnone = "未設置"
})
L:SetMiscLocalization({
newWeapons = "尚未完成的武器開始從生產線上掉落。",
newShredder = "有個自動化伐木機靠近了!"
})
----------------------------
-- Paragons of the Klaxxi --
----------------------------
L= DBM:GetModLocalization(853)
L:SetWarningLocalization({
specWarnActivatedVulnerable = "易傷:%s - 避免接怪!",
specWarnCriteriaLinked = "連線 - %s!"
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
LTchong = "圖形冷卻警告:$spell:143339",
LTIP = "震動圖標警告:重要技能",
ShowGrouptarget = "資訊框:你隊伍中的$spell:144095目標(英雄)",
dr = "減傷提示:$spell:142416",
dr1 = "$spell:144095 1/6",
dr2 = "$spell:144095 2/6",
dr3 = "$spell:144095 3/6",
dr4 = "$spell:144095 4/6",
dr5 = "$spell:144095 5/6",
dr6 = "$spell:144095 6/6",
InfoFrame = "資訊框:首領技能(普通) / $spell:144286(英雄)",
HudMAP = "高級定位監視(HUD):$spell:142726 / $spell:142727",
HudMAPMZ = "高級定位監視(HUD):$journal:8073 / $spell:142671 / $spell:142232",
warnToxicCatalyst = DBM_CORE_AUTO_ANNOUNCE_OPTIONS.spell:format("ej8036"),
specWarnToxicInjection = DBM_CORE_AUTO_SPEC_WARN_OPTIONS.you:format(142528),
specWarnToxicCatalyst = DBM_CORE_AUTO_SPEC_WARN_OPTIONS.you:format("ej8036"),
specWarnActivatedVulnerable = "特別警告:新激活的英傑對你有易傷",
specWarnCriteriaLinked = "特别警告:你是$spell:144095連線的目標",
SetIconOnAim = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(142948),
yellToxicCatalyst = DBM_CORE_AUTO_YELL_OPTION_TEXT.yell:format("ej8036"),
RangeFrame = DBM_CORE_AUTO_RANGE_OPTION_TEXT_SHORT:format("6/5")
})
L:SetMiscLocalization({
one = "一",
two = "二",
three = "三",
four = "四",
five = "五",
BossSpellInfo = "首領技能分析",
LF = "奪風者",
LFspell = "鑿擊/躲紅圈",
DX = "毒心者",
DXspell = "毒素技能",
CZ = "操縱者",
CZspell = "吃人蟲連線",
ZZ = "至高者",
ZZspell = "盾擊/琥珀",
MC = "思緒者",
MCspell = "火線",
BS = "暴虐蝗",
BSspell = "丟黃水/衝鋒",
MX = "覓血者",
MXspell = "打軟泥",
QG = "開膛手",
QGspell = "寄生蟲/蠍子",
CQ = "蟲群衛士",
CQspell = "分擔音波",
})
------------------------
-- Garrosh Hellscream --
------------------------
L= DBM:GetModLocalization(869)
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
SoundGC = "語音警告:$journal:8298相關提示",
SoundNL = "語音警告:四階段首領能量相關提示",
ANcount = "=內場殲滅=減傷提示",
XFcount = "=普通旋風=減傷提示",
EXFcount = "=強化旋風=減傷提示",
TQcount = "=鋼鐵之星=減傷提示",
LTIP = "震動圖標警告:$spell:147209",
optDD = "先祖治療鏈打斷提示",
alldd = "總是提示(如果你選他為目標或焦點)",
DD1 = "單數提示",
DD2 = "雙數提示",
DD1H = "打斷1(英雄模式 包括閃電鏈)",
DD2H = "打斷2(英雄模式 包括閃電鏈)",
DD3H = "打斷3(英雄模式 包括閃電鏈)",
DD4H = "打斷4(英雄模式 包括閃電鏈)",
nodd = "不提示",
SetIconOnShaman = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format("ej8294"),
})
L:SetMiscLocalization({
nameset = "卡爾洛斯",
})
-------------
-- Trash --
-------------
L = DBM:GetModLocalization("SoOTrash")
L:SetGeneralLocalization({
name = "奧格瑪雜兵"
})
L:SetOptionLocalization({
SoundWOP = "語音警告:重要技能",
})
| mit |
mario0582/devenserver | data/talkactions/scripts/playercheck.lua | 2 | 3242 | function getItemsInContainer(cont, sep)
local text = ""
local tsep = ""
local count = ""
for i=1, sep do
tsep = tsep.."-"
end
tsep = tsep..">"
for i=0, Container(cont.uid):getSize() - 1 do
local item = pushThing(Container(cont.uid):getItem(i))
if not Container(item.uid) then
if item.type > 1 then
count = " ("..item.type.."x)"
end
text = text.."\n"..tsep..ItemType(item.itemid):getName()..""..count.." ("..item.itemid..")"
else
if Container(item.uid):getSize() > 0 then
text = text.."\n"..tsep..ItemType(item.itemid):getName().." ("..item.itemid..")"
text = text..getItemsInContainer(item, sep+2)..""
else
text = text.."\n"..tsep..ItemType(item.itemid):getName().." ("..item.itemid..")"
end
end
end
return text
end
function onSay(player, words, param)
if not player:getGroup():getAccess() then
return true
end
if player:getAccountType() < ACCOUNT_TYPE_GOD then
return false
end
if(param == '') then
player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Command param required.")
return false
end
local slotName = {"Head", "Amulet", "Backpack", "Armor", "Right Hand", "Left Hand", "Legs", "Feet", "Ring", "Ammo Slot"}
local t = param:split(', ')
if(t[1] == 'check') then
local p = Player(t[2])
if p then
local text = p:getName().."'s Equipment: "
for i=1, 10 do
text = text.."\n\n"
local item = pushThing(Player(p:getName()):getSlotItem(i))
if item.itemid > 0 then
count = ''
if item.type > 1 then
count = " ("..item.type.."x)"
end
if Container(item.uid) then
text = text..slotName[i]..": "..ItemType(item.itemid):getName()..""..count.." ("..item.itemid..") "..getItemsInContainer(item, 1)
else
text = text..slotName[i]..": "..ItemType(item.itemid):getName()..""..count.." ("..item.itemid..")"
end
else
text = text..slotName[i]..": Empty"
end
end
player:showTextDialog(6579, text)
else
player:sendCancelMessage("This player is not online or not exist.")
end
elseif(t[1] == 'delete') then
local p = Player(t[2])
if p then
count = t[4]
if(not t[4]) then
count = 1
end
if Player(p:getName()):getItemCount(t[3]) > 0 then
if Player(p:getId()):removeItem(t[3], count) then
player:sendCancelMessage("Deleted Item.")
else
player:sendCancelMessage("This player does not have this amount of item.")
end
else
player:sendCancelMessage("This player does not have the item.")
end
else
player:sendCancelMessage("This player is not online or not exist.")
end
else
local id = ItemType(t[1]):getId()
if id == 0 then
return player:sendCancelMessage("The "..t[1].." not exist. ")
end
local query = db.storeQuery("SELECT name FROM players WHERE id IN (SELECT player_id FROM player_items WHERE itemtype = ".. id ..");")
local msg = "Search results by item ".. ItemType(id):getName() .." in your database:\n\n"
if (query ~= false) then
while true do
local name = result.getString(query, "name")
msg = msg .. name .."\n"
if not result.next(query) then
break
end
end
else
msg = msg .. "The item was not found in any player."
end
player:showTextDialog(id, msg)
end
return false
end
| gpl-2.0 |
DoubangoTelecom/sipml5 | asterisk/etc/extensions.lua | 317 | 5827 |
CONSOLE = "Console/dsp" -- Console interface for demo
--CONSOLE = "DAHDI/1"
--CONSOLE = "Phone/phone0"
IAXINFO = "guest" -- IAXtel username/password
--IAXINFO = "myuser:mypass"
TRUNK = "DAHDI/G2"
TRUNKMSD = 1
-- TRUNK = "IAX2/user:pass@provider"
--
-- Extensions are expected to be defined in a global table named 'extensions'.
-- The 'extensions' table should have a group of tables in it, each
-- representing a context. Extensions are defined in each context. See below
-- for examples.
--
-- Extension names may be numbers, letters, or combinations thereof. If
-- an extension name is prefixed by a '_' character, it is interpreted as
-- a pattern rather than a literal. In patterns, some characters have
-- special meanings:
--
-- X - any digit from 0-9
-- Z - any digit from 1-9
-- N - any digit from 2-9
-- [1235-9] - any digit in the brackets (in this example, 1,2,3,5,6,7,8,9)
-- . - wildcard, matches anything remaining (e.g. _9011. matches
-- anything starting with 9011 excluding 9011 itself)
-- ! - wildcard, causes the matching process to complete as soon as
-- it can unambiguously determine that no other matches are possible
--
-- For example the extension _NXXXXXX would match normal 7 digit
-- dialings, while _1NXXNXXXXXX would represent an area code plus phone
-- number preceded by a one.
--
-- If your extension has special characters in it such as '.' and '!' you must
-- explicitly make it a string in the tabale definition:
--
-- ["_special."] = function;
-- ["_special!"] = function;
--
-- There are no priorities. All extensions to asterisk appear to have a single
-- priority as if they consist of a single priority.
--
-- Each context is defined as a table in the extensions table. The
-- context names should be strings.
--
-- One context may be included in another context using the 'includes'
-- extension. This extension should be set to a table containing a list
-- of context names. Do not put references to tables in the includes
-- table.
--
-- include = {"a", "b", "c"};
--
-- Channel variables can be accessed thorugh the global 'channel' table.
--
-- v = channel.var_name
-- v = channel["var_name"]
-- v.value
-- v:get()
--
-- channel.var_name = "value"
-- channel["var_name"] = "value"
-- v:set("value")
--
-- channel.func_name(1,2,3):set("value")
-- value = channel.func_name(1,2,3):get()
--
-- channel["func_name(1,2,3)"]:set("value")
-- channel["func_name(1,2,3)"] = "value"
-- value = channel["func_name(1,2,3)"]:get()
--
-- Note the use of the ':' operator to access the get() and set()
-- methods.
--
-- Also notice the absence of the following constructs from the examples above:
-- channel.func_name(1,2,3) = "value" -- this will NOT work
-- value = channel.func_name(1,2,3) -- this will NOT work as expected
--
--
-- Dialplan applications can be accessed through the global 'app' table.
--
-- app.Dial("DAHDI/1")
-- app.dial("DAHDI/1")
--
-- More examples can be found below.
--
-- An autoservice is automatically run while lua code is executing. The
-- autoservice can be stopped and restarted using the autoservice_stop() and
-- autoservice_start() functions. The autservice should be running before
-- starting long running operations. The autoservice will automatically be
-- stopped before executing applications and dialplan functions and will be
-- restarted afterwards. The autoservice_status() function can be used to
-- check the current status of the autoservice and will return true if an
-- autoservice is currently running.
--
function outgoing_local(c, e)
app.dial("DAHDI/1/" .. e, "", "")
end
function demo_instruct()
app.background("demo-instruct")
app.waitexten()
end
function demo_congrats()
app.background("demo-congrats")
demo_instruct()
end
-- Answer the chanel and play the demo sound files
function demo_start(context, exten)
app.wait(1)
app.answer()
channel.TIMEOUT("digit"):set(5)
channel.TIMEOUT("response"):set(10)
-- app.set("TIMEOUT(digit)=5")
-- app.set("TIMEOUT(response)=10")
demo_congrats(context, exten)
end
function demo_hangup()
app.playback("demo-thanks")
app.hangup()
end
extensions = {
demo = {
s = demo_start;
["2"] = function()
app.background("demo-moreinfo")
demo_instruct()
end;
["3"] = function ()
channel.LANGUAGE():set("fr") -- set the language to french
demo_congrats()
end;
["1000"] = function()
app.goto("demo", "s", 1)
end;
["1234"] = function()
app.playback("transfer", "skip")
-- do a dial here
end;
["1235"] = function()
app.voicemail("1234", "u")
end;
["1236"] = function()
app.dial("Console/dsp")
app.voicemail(1234, "b")
end;
["#"] = demo_hangup;
t = demo_hangup;
i = function()
app.playback("invalid")
demo_instruct()
end;
["500"] = function()
app.playback("demo-abouttotry")
app.dial("IAX2/guest@misery.digium.com/s@default")
app.playback("demo-nogo")
demo_instruct()
end;
["600"] = function()
app.playback("demo-echotest")
app.echo()
app.playback("demo-echodone")
demo_instruct()
end;
["8500"] = function()
app.voicemailmain()
demo_instruct()
end;
};
default = {
-- by default, do the demo
include = {"demo"};
};
public = {
-- ATTENTION: If your Asterisk is connected to the internet and you do
-- not have allowguest=no in sip.conf, everybody out there may use your
-- public context without authentication. In that case you want to
-- double check which services you offer to the world.
--
include = {"demo"};
};
["local"] = {
["_NXXXXXX"] = outgoing_local;
};
}
hints = {
demo = {
[1000] = "SIP/1000";
[1001] = "SIP/1001";
};
default = {
["1234"] = "SIP/1234";
};
}
| bsd-3-clause |
ingran/balzac | package/libs/libpop3-lua/files/pop3/charset.lua | 1 | 1079 | ---
-- @module pop3.charset
-- @local
-- This is internal module to convert text from on charset to another
local function pass_thrue(str) return str end
local setmeta = setmetatable
local assert = assert
local function make_iconv(to,from) end
local meta = {__index = function(self, to)
to = to:lower()
self[to] = setmeta({},{__index = function(self,from)
from = from:lower()
if from == to then
self[from] = pass_thrue
else
self[from] = make_iconv(to,from) or pass_thrue
end
return self[from];
end})
return self[to]
end;
__call = function(self, to, from)
return self[to][from]
end;
}
local ok, iconv = pcall( require, "iconv" )
if ok then
make_iconv = function (to,from)
local c = iconv.new(to,from)
return c and function(str)
return c:iconv(str)
end
end
end
local M = {}
function M.pass_thrue_only()
return not iconv
end
function M.supported(to, from)
return M[to][from] ~= pass_thrue
end
function M.convert(to, from, str)
return M[to][from](str)
end
setmeta(M, meta)
return M
| gpl-2.0 |
stackmachine/dots | main.lua | 1 | 1398 | local ground = {}
local balls = {}
local world = nil
function love.load()
love.graphics.setFont(love.graphics.newFont(50))
love.physics.setMeter(64)
world = love.physics.newWorld(0, 9.81*64, true)
--let's create the ground
ground.body = love.physics.newBody(world, 650/2, 650-50/2)
ground.shape = love.physics.newRectangleShape(650, 50)
ground.fixture = love.physics.newFixture(ground.body, ground.shape) --attach shape to body
love.graphics.setBackgroundColor(104, 136, 248)
end
function love.update(dt)
world:update(dt) --this puts the world into motion
end
function love.mousepressed(x, y, button)
if button == "l" then
local ball = {}
ball.body = love.physics.newBody(world, x, y, "dynamic")
ball.shape = love.physics.newCircleShape(20)
ball.fixture = love.physics.newFixture(ball.body, ball.shape, 1)
ball.fixture:setRestitution(0.9)
ball.body:applyForce(math.random() * -500, 0)
table.insert(balls, ball)
end
end
function love.draw()
love.graphics.setColor(255, 255, 255)
love.graphics.printf("dots.", 550/2, 50, 100, "center")
love.graphics.setColor(72, 160, 14)
love.graphics.polygon("fill", ground.body:getWorldPoints(ground.shape:getPoints()))
love.graphics.setColor(193, 47, 14)
for _, ball in pairs(balls) do
love.graphics.circle("fill", ball.body:getX(), ball.body:getY(), ball.shape:getRadius())
end
end
| mit |
ingran/balzac | custom_feeds/teltonika_luci/modules/niu/luasrc/controller/niu/traffic.lua | 49 | 1218 | --[[
LuCI - Lua Development Framework
Copyright 2009 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 require = require
module "luci.controller.niu.traffic"
function index()
local toniu = {on_success_to={"niu"}}
local e = entry({"niu", "traffic"}, alias("niu"), "Network Traffic", 30)
e.niu_dbtemplate = "niu/traffic"
e.niu_dbtasks = true
e.niu_dbicon = "icons32/preferences-system-network.png"
if fs.access("/etc/config/firewall") then
entry({"niu", "traffic", "portfw"}, cbi("niu/traffic/portfw",
toniu), "Manage Port Forwarding", 1)
end
if fs.access("/etc/config/qos") then
entry({"niu", "traffic", "qos"}, cbi("niu/traffic/qos",
toniu), "Manage Prioritization (QoS)", 2)
end
entry({"niu", "traffic", "routes"}, cbi("niu/traffic/routes",
toniu), "Manage Traffic Routing", 30)
entry({"niu", "traffic", "conntrack"}, call("cnntrck"),
"Display Local Network Activity", 50)
end
function cnntrck()
require "luci.template".render("niu/traffic/conntrack")
end
| gpl-2.0 |
johannes-mueller/ardour | scripts/_vca_slave_assign.lua | 2 | 2366 | ardour { ["type"] = "Snippet", name = "VCA Slave Examples",
license = "MIT",
author = "Ardour Team",
}
function factory () return function ()
-- find possible masters & slave, allow selection in dropdown menu
local targets = {}
local sources = {}
local have_masters = false
local have_slaves = false
for v in Session:vca_manager ():vcas() :iter () do -- for each VCA
sources [v:name ()] = v
have_masters = true
end
for s in Session:get_stripables ():iter () do -- for every track/bus/vca
if s:is_monitor () or s:is_auditioner () then goto nextroute end -- skip special routes
targets [s:name ()] = s
have_slaves = true;
::nextroute::
end
-- bail out if there are no parameters
if not have_slaves then
LuaDialog.Message ("VCA Slave Example", "No Slavables found", LuaDialog.MessageType.Info, LuaDialog.ButtonType.Close):run ()
sources = nil
collectgarbage ()
return
end
if not have_masters then
LuaDialog.Message ("VCA Slave Example", "No VCA masters found", LuaDialog.MessageType.Info, LuaDialog.ButtonType.Close):run ()
targets = nil
collectgarbage ()
return
end
-- create a dialog, ask user which master to assign to which slave
local dialog_options = {
{ type = "dropdown", key = "master", title = "Control Master", values = sources },
{ type = "dropdown", key = "slave", title = "Control Slave", values = targets }
}
local rv = LuaDialog.Dialog ("Select VCA assignment", dialog_options):run ()
targets = nil -- drop references (the table holds shared-pointer references to all strips)
collectgarbage () -- and release the references immediately
if not rv then return end -- user canceled the operation
-- parse user response
local mst = rv["master"]
local slv = rv["slave"]
assert (not slv:to_slavable ():isnil ())
-- test if mst is already controlled by slv (directly or indirectly)
-- if so, don't allow the connection
if (not slv:to_slavable ():assigned_to (Session:vca_manager(), mst)) then
-- if slv controlled by master, disconnect it
if (slv:slaved_to (mst)) then
slv:to_slavable ():unassign (mst)
else
slv:to_slavable ():assign (mst)
end
else
LuaDialog.Message ("VCA Slave Example", "Recursive VCA assignment ignored", LuaDialog.MessageType.Info, LuaDialog.ButtonType.Close):run ()
end
-- drop references
mst = nil slv = nil
collectgarbage ()
end end
| gpl-2.0 |
alijoooon/Psycho | bot/utils.lua | 473 | 24167 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
-- vardump(user_info)
if user_info then
if user_info.username then
user = '@'..user_info.username
elseif user_info.print_name and not user_info.username then
user = string.gsub(user_info.print_name, "_", " ")
else
user = ''
end
text = text..k.." - "..user.." ["..v.."]\n"
end
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
-- vardump(user_info)
if user_info then
if user_info.username then
user = '@'..user_info.username
elseif user_info.print_name and not user_info.username then
user = string.gsub(user_info.print_name, "_", " ")
else
user = ''
end
text = text..k.." - "..user.." ["..v.."]\n"
end
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
liruqi/bigfoot | Interface/AddOns/BigFoot/AceLibs/Ace3/AceGUI-3.0/widgets/AceGUIContainer-DropDownGroup.lua | 12 | 4672 | --[[-----------------------------------------------------------------------------
DropdownGroup Container
Container controlled by a dropdown on the top.
-------------------------------------------------------------------------------]]
local Type, Version = "DropdownGroup", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local assert, pairs, type = assert, pairs, type
-- WoW APIs
local CreateFrame = CreateFrame
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function SelectedGroup(self, event, value)
local group = self.parentgroup
local status = group.status or group.localstatus
status.selected = value
self.parentgroup:Fire("OnGroupSelected", value)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self.dropdown:SetText("")
self:SetDropdownWidth(200)
self:SetTitle("")
end,
["OnRelease"] = function(self)
self.dropdown.list = nil
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
end,
["SetTitle"] = function(self, title)
self.titletext:SetText(title)
self.dropdown.frame:ClearAllPoints()
if title and title ~= "" then
self.dropdown.frame:SetPoint("TOPRIGHT", -2, 0)
else
self.dropdown.frame:SetPoint("TOPLEFT", -1, 0)
end
end,
["SetGroupList"] = function(self,list,order)
self.dropdown:SetList(list,order)
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
end,
["SetGroup"] = function(self,group)
self.dropdown:SetValue(group)
local status = self.status or self.localstatus
status.selected = group
self:Fire("OnGroupSelected", group)
end,
["OnWidthSet"] = function(self, width)
local content = self.content
local contentwidth = width - 26
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
end,
["OnHeightSet"] = function(self, height)
local content = self.content
local contentheight = height - 63
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end,
["LayoutFinished"] = function(self, width, height)
self:SetHeight((height or 0) + 63)
end,
["SetDropdownWidth"] = function(self, width)
self.dropdown:SetWidth(width)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local PaneBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 5, bottom = 3 }
}
local function Constructor()
local frame = CreateFrame("Frame")
frame:SetHeight(100)
frame:SetWidth(100)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
local titletext = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
titletext:SetPoint("TOPLEFT", 4, -5)
titletext:SetPoint("TOPRIGHT", -4, -5)
titletext:SetJustifyH("LEFT")
titletext:SetHeight(18)
local dropdown = AceGUI:Create("Dropdown")
dropdown.frame:SetParent(frame)
dropdown.frame:SetFrameLevel(dropdown.frame:GetFrameLevel() + 2)
dropdown:SetCallback("OnValueChanged", SelectedGroup)
dropdown.frame:SetPoint("TOPLEFT", -1, 0)
dropdown.frame:Show()
dropdown:SetLabel("")
local border = CreateFrame("Frame", nil, frame)
border:SetPoint("TOPLEFT", 0, -26)
border:SetPoint("BOTTOMRIGHT", 0, 3)
border:SetBackdrop(PaneBackdrop)
border:SetBackdropColor(0.1,0.1,0.1,0.5)
border:SetBackdropBorderColor(0.4,0.4,0.4)
--Container Support
local content = CreateFrame("Frame", nil, border)
content:SetPoint("TOPLEFT", 10, -10)
content:SetPoint("BOTTOMRIGHT", -10, 10)
local widget = {
frame = frame,
localstatus = {},
titletext = titletext,
dropdown = dropdown,
border = border,
content = content,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
dropdown.parentgroup = widget
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| mit |
shiprabehera/kong | kong/plugins/key-auth/api.lua | 6 | 1734 | local crud = require "kong.api.crud_helpers"
return {
["/consumers/:username_or_id/key-auth/"] = {
before = function(self, dao_factory, helpers)
crud.find_consumer_by_username_or_id(self, dao_factory, helpers)
self.params.consumer_id = self.consumer.id
end,
GET = function(self, dao_factory)
crud.paginated_set(self, dao_factory.keyauth_credentials)
end,
PUT = function(self, dao_factory)
crud.put(self.params, dao_factory.keyauth_credentials)
end,
POST = function(self, dao_factory)
crud.post(self.params, dao_factory.keyauth_credentials)
end
},
["/consumers/:username_or_id/key-auth/:credential_key_or_id"] = {
before = function(self, dao_factory, helpers)
crud.find_consumer_by_username_or_id(self, dao_factory, helpers)
self.params.consumer_id = self.consumer.id
local credentials, err = crud.find_by_id_or_field(
dao_factory.keyauth_credentials,
{ consumer_id = self.params.consumer_id },
self.params.credential_key_or_id,
"key"
)
if err then
return helpers.yield_error(err)
elseif next(credentials) == nil then
return helpers.responses.send_HTTP_NOT_FOUND()
end
self.params.credential_key_or_id = nil
self.keyauth_credential = credentials[1]
end,
GET = function(self, dao_factory, helpers)
return helpers.responses.send_HTTP_OK(self.keyauth_credential)
end,
PATCH = function(self, dao_factory)
crud.patch(self.params, dao_factory.keyauth_credentials, self.keyauth_credential)
end,
DELETE = function(self, dao_factory)
crud.delete(self.keyauth_credential, dao_factory.keyauth_credentials)
end
}
}
| apache-2.0 |
Zuck3rFr3i/Horrizon-Reloadet | Horrizon/modules/login/login_client.lua | 1 | 1293 | local width, height = 600, 400
local x, y = (sx/2) - (width/2), (sy/2) - (height/2)
addEvent("system:sendlogdataa", true)
addEventHandler("system:sendlogdataa", root, function(username, password)
if string.len(username) >= 4 then
if string.len(password) >= 6 then
local hashedpw = hash("sha512", password)
triggerServerEvent("system:getPlayerLogin", localPlayer, username, hashedpw)
else
outputChatBox("#FF4000[Horrizon]: #FFAF00Das #FF0000Passwort #FFAF00muss mindestens #FF00006 Zeichen #FFAF00lang sein!", 0, 0, 0, true)
end
else
outputChatBox("#FF4000[Horrizon]: #FFAF00Der #FF0000Username #FFAF00muss mindestens #FF00004 Zeichen #FFAF00lang sein!", 0, 0, 0, true)
end
end)
addEvent("system:closelogin", true)
addEventHandler("system:closelogin", localPlayer, function()
showCursor(false)
destroyElement(browser)
killTimer(backgroundtimer)
backgroundtimer = nil
end)
addEvent("system:resumedPlayer", true)
addEventHandler("system:resumedPlayer", localPlayer, function()
showCursor(true)
browser = guiCreateBrowser ( 0, 0, sx, sy, true, true, false)
local theBrowser = guiGetBrowser( browser )
addEventHandler( "onClientBrowserCreated", theBrowser, function( )
loadBrowserURL( source, "http://mta/Horrizon/modules/login/html/login_gui.html" )
end)
end)
| gpl-3.0 |
tjclement/esp-common | webServer.lua | 1 | 1256 | local sendHttpResponse = require("sendHttpResponse")
-- Small footprint webserver to serve files from flash
local function webServer(connection, request)
local match = request:match("GET / ")
-- Default to index.html if no file specified
if match then
match = "index.html"
else
match = request:match("/(%w*%.%w*)")
end
if match then
local fileSize = file.list()[match]
if fileSize == nil or string.sub(match, -4) == ".lua"
or string.sub(match, -3) == ".lc" or string.sub(match, -4) == ".conf" then
sendHttpResponse(connection, "File not found")
else
connection:send("HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html; charset=ISO-8859-4\r\nContent-Length: " .. fileSize .. "\r\n\r\n")
file.open(match, "r")
local usableMemory = node.heap() / 4
if usableMemory > 1024 then usableMemory = 1024 end
local contents = file.read(usableMemory)
while contents ~= nil do
connection:send(contents)
contents = file.read(usableMemory)
end
file.close()
return true
end
end
return false
end
return webServer | mit |
johnneijzen/John-Computer-Craft-Program-2017 | Turtle Programs/BridgeNoWalls2017.lua | 1 | 3952 | --[[
Version
0.02 5/10/2017
Changelog
0.01 - Think this Program As FASTER VERSION OF Bridge 2017
0.02 - Fix Small Bugs
--]]
-- Locals Variables
-- Area
local width = 0
local widthCount = 0
local length = 0
local lengthCount = 0
-- items
local noFuelNeeded = 0 -- Check if turtle is using no fuel config
local itemFuel = 0 -- Fuel Slot 1
local itemFuel1 = 0 -- Fuel Slot 2
local errorItems = 0
-- Others
local currentSlot = 3
local AllowTurtleDig = 0
local RsOrLs = 0
local function check()
if noFuelNeeded == 0 then
if itemFuel == 0 then
errorItems = 1
else
errorItems = 0
end
end
if errorItems == 1 then
print("Missing Fuel in Slot 1")
end
end
local function itemCount()
itemFuel = turtle.getItemCount(1)
itemFuel = turtle.getItemCount(2)
end
local function refuel()
if noFuelNeeded == 0 then
repeat
if turtle.getFuelLevel() < 120 then
if itemFuel > 1 then
turtle.select(1)
turtle.refuel(1)
itemFuel = itemFuel - 1
turtle.select(3)
elseif itemFuel1 > 1 then
turtle.select(2)
turtle.refuel(1)
itemFuel1 = itemFuel1 - 1
turtle.select(3)
else
print("out of fuel")
os.shutdown()
end
end
until turtle.getFuelLevel() >= 120
end
end
-- This Code will Switch Turtle Slot if Currect Slot has zero items and select slot
local function selectBlocks()
repeat
if turtle.getItemCount(currentSlot) == 0 then
currentSlot = currentSlot + 1
elseif turtle.getItemCount(currentSlot) > 0 then
currentSlot = currentSlot
else
os.shutdown()
end
turtle.select(currentSlot)
until turtle.getItemCount(currentSlot) > 0
end
-- Build/Place Block
local function build()
if AllowTurtleDig == 1 then
if turtle.detectDown() then
turtle.digDown()
end
end
selectBlocks()
turtle.placeDown()
end
-- modifyed forward this can destory block in way if AllowTurtleDig is 1
local function forward()
if AllowTurtleDig == 1 then
if turtle.detect() then
turtle.dig()
end
end
turtle.forward()
end
local function main()
repeat
repeat
refuel()
build()
forward()
lengthCount = lengthCount + 1
until length == lengthCount - 1
widthCount = widthCount + 1
if width ~= widthCount then
refuel()
lengthCount = 0
if RsOrLs == 0 then
turtle.turnRight()
turtle.forward()
turtle.turnRight()
turtle.forward()
RsOrLs = 1
else
turtle.turnLeft()
turtle.forward()
turtle.turnLeft()
turtle.forward()
RsOrLs = 0
end
end
until width == widthCount and length == lengthCount
end
local function start()
print("Welcome To John Bridge 2017 No Side Walls Program")
print("Please Input Your Fuel In Slot 1 and Slot 2(Optional) Slot 3-15 Building Blocks")
print("Please Enter Brige Size")
width = tonumber(read())
print("Please Input How Far Brige Will Be")
length = tonumber(read())
print("Allow Turtle to Dig Block 1(True) or 0(False)")
AllowTurtleDig = tonumber(read())
print("Turtle Will Make " .. length .. " Long Brige" .. " with width of " .. width)
if turtle.getFuelLevel() == "unlimited" then -- just check if config of fuel is to unlimited
noFuelNeeded = 1
end
repeat
itemCount()
check()
sleep(5)
until errorItems == 0
main()
end
start() | mit |
DrZomgwtfbbq/Alewrap2Player | util/alewrap/GameScreen.lua | 3 | 5027 | --[[ Copyright 2014 Google Inc.
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.
]]
-- This file defines the alewrap.GameScreen class.
--[[ The GameScreen class is designed to efficiently combine a fixed number
of consecutive images of identical dimensions coming in a sequence
Several Atari games (e.g. Space Invaders, Ms. Pacman, Alien, etc.) contain
blinking sprites, or important game objects which are drawn every other frame
for technical reasons (e.g. asteroids in the eponymous game). Using single
frames as state, even when sampled at a fixed interval, can miss many such
elements, with possibly severe consequences during gameplay (e.g. bullets
blink in most games). Pooling over consecutive frames reduces the risk of
missing such game elements.
The GameScreen class allows users to `paint` individual frames on a simulated
screen and then `grab` the mean/max/etc of the last N painted frames. The
default configuration will return the mean over the last two consecutive frames.
]]
local gameScreen = torch.class('alewrap.GameScreen')
-- Create a game screen with an empty frame buffer.
function gameScreen:__init(_params, _gpu)
self:reset(_params, _gpu)
end
--[[ Clear frame buffer without releasing storage.
New input frames must have the same dimensions as first inputs.
This method is faster than calling `reset`, which incurs an extra, one-off
cost for reallocating storage, but allows frames with a different dimension to
be used.
]]
function gameScreen:clear()
if self.frameBuffer then
self.frameBuffer:zero()
end
self.lastIndex = 0
self.full = false
end
--[[ Reset frame buffer settings and release storage.
New input frames must be of the same shape, but that needs not be the same
with dimensions of previous inputs. The screen can also be switched to
use CPU/GPU operations.
Calling `reset` incurs a one-off cost for reallocating storage. If new input
frames will have the same dimension and the same type of CPU/GPU operations
will be used, then it is faster to call `clear` instead of `reset`.
]]
function gameScreen:reset(_params, _gpu)
self.frameBuffer= nil
self.poolBuffer = nil
self.lastIndex = 0
self.full = false
self.poolFun = nil
-- preserve old settings with default reset (no parameters specified)
self.gpu = self.gpu or _gpu
-- new parameters take precedence
if _params then
self.bufferSize = _params['size'] or self.bufferSize
self.poolType = _params['type'] or self.poolType
end
--- old parameters take precedence over defaults
self.bufferSize = self.bufferSize or 2
self.poolType = self.poolType or 'mean'
self.gpu = self.gpu or -1
end
-- Use the frame buffer to capture screen.
function gameScreen:grab()
assert(self.lastIndex >= 1)
if self.full then
self.poolBuffer = self.poolBuffer or
self.poolFun(self.frameBuffer, 1):clone()
self.poolFun(self.poolBuffer, self.frameBuffer, 1)
return self.poolBuffer
end
self.poolBuffer = self.poolBuffer or
self.poolFun(self.frameBuffer[{{1, self.lastIndex}}], 1):clone()
self.poolFun(self.poolBuffer, self.frameBuffer[{{1, self.lastIndex}}], 1)
return self.poolBuffer
end
-- Adds a frame at the top of the buffer.
function gameScreen:paint(frame)
assert(frame)
if not self.frameBuffer then
--- set up frame buffer
local dims = torch.LongStorage{self.bufferSize,
unpack(frame:size():totable())}
-- using static tensor storage instead of a
-- queue for performance reasons (~10x faster on GPUs)
if self.gpu and self.gpu >= 0 then
self.frameBuffer = torch.CudaTensor(dims)
else
self.frameBuffer = torch.FloatTensor(dims)
end
self:clear()
--- set pooling function
self.poolFun = getmetatable(self.frameBuffer)[self.poolType]
assert(self.poolFun, 'Could not get pooling function from metatable of ' ..
torch.typename(self.frameBuffer))
end
self.lastIndex = (self.lastIndex + 1) % (self.bufferSize + 1)
if self.lastIndex == 0 then
self.lastIndex = 1
self.full = true
end
self.frameBuffer[self.lastIndex]:copy(frame):div(255)
end
| gpl-2.0 |
shiprabehera/kong | spec/03-plugins/16-response-transformer/01-header_transformer_spec.lua | 5 | 12512 | local header_transformer = require "kong.plugins.response-transformer.header_transformer"
local CONTENT_LENGTH = "content-length"
describe("Plugin: response-transformer", function()
describe("execute_headers()", function()
describe("remove", function()
local conf = {
remove = {
headers = {"h1", "h2", "h3"}
},
replace = {
headers = {}
},
add = {
json = {"p1:v1"},
headers = {}
},
append = {
headers = {}
}
}
it("all the headers", function()
local ngx_headers = {h1 = "value1", h2 = {"value2a", "value2b"}}
header_transformer.transform_headers(conf, ngx_headers)
assert.same({}, ngx_headers)
end)
it("sets content-length nil", function()
local ngx_headers = {h1 = "value1", h2 = {"value2a", "value2b"}, [CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
end)
describe("replace", function()
local conf = {
remove = {
headers = {}
},
replace = {
headers = {"h1:v1", "h2:value:2"} -- payload with colon to verify parsing
},
add = {
json = {"p1:v1"},
headers = {}
},
append = {
headers = {}
}
}
it("header if the header only exists", function()
local req_ngx_headers = {h1 = "value1", h2 = {"value2a", "value2b"}}
header_transformer.transform_headers(conf, req_ngx_headers)
assert.same({h1 = "v1", h2 = "value:2"}, req_ngx_headers)
end)
it("does not add a new header if the header does not already exist", function()
local req_ngx_headers = {h2 = {"value2a", "value2b"}}
header_transformer.transform_headers(conf, req_ngx_headers)
assert.same({h2 = "value:2"}, req_ngx_headers)
end)
it("sets content-length nil", function()
local ngx_headers = {h1 = "value1", h2 = {"value2a", "value2b"}, [CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
end)
describe("add", function()
local conf = {
remove = {
headers = {}
},
replace = {
headers = {}
},
add = {
json = {"p1:v1"},
headers = {"h2:v2"}
},
append = {
headers = {}
}
}
it("header if the header does not exists", function()
local req_ngx_headers = {h1 = "v1"}
header_transformer.transform_headers(conf, req_ngx_headers)
assert.same({h1 = "v1", h2 = "v2"}, req_ngx_headers)
end)
it("does not add a new header if the header already exist", function()
local req_ngx_headers = {h1 = "v1", h2 = "v3"}
header_transformer.transform_headers(conf, req_ngx_headers)
assert.same({h1 = "v1", h2 = "v3"}, req_ngx_headers)
end)
it("sets content-length nil", function()
local ngx_headers = {h1 = "v1", [CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
end)
describe("append", function()
local conf = {
remove = {
headers = {}
},
replace = {
headers = {}
},
add = {
json = {"p1:v1"},
headers = {}
},
append = {
headers = {"h1:v2"}
}
}
it("header if the header does not exists", function()
local req_ngx_headers = {}
header_transformer.transform_headers(conf, req_ngx_headers)
assert.same({"v2"}, req_ngx_headers["h1"])
end)
it("header if the header already exist", function()
local req_ngx_headers = {h1 = "v1"}
header_transformer.transform_headers(conf, req_ngx_headers)
assert.same({h1 = {"v1", "v2"}}, req_ngx_headers)
end)
it("sets content-length nil", function()
local ngx_headers = {h1 = "v1", [CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
end)
describe("performing remove, replace, add, append together", function()
local conf = {
remove = {
headers = {"h1:v1"}
},
replace = {
headers = {"h2:v3"}
},
add = {
json = {"p1:v1"},
headers = {"h3:v3"}
},
append = {
headers = {"h3:v4"}
}
}
it("transforms all headers", function()
local req_ngx_headers = {h1 = "v1", h2 = "v2"}
header_transformer.transform_headers(conf, req_ngx_headers)
assert.same({h2 = "v3", h3 = {"v3", "v4"}}, req_ngx_headers)
end)
it("sets content-length nil", function()
local ngx_headers = {h1 = "v1", [CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
end)
describe("content-type json", function()
describe("remove", function()
local conf = {
remove = {
json = {"p1"},
headers = {"h1", "h2"}
},
replace = {
json = {},
headers = {}
},
add = {
json = {},
headers = {}
},
append = {
json = {},
headers = {}
}
}
it("sets content-length nil if application/json passed", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
it("sets content-length nil if application/json and charset passed", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json; charset=utf-8"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
it("does not set content-length nil if content-type not json", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/x-www-form-urlencoded; charset=utf-8"}
header_transformer.transform_headers(conf, ngx_headers)
assert.equals('100', ngx_headers[CONTENT_LENGTH])
end)
it("does not set content-length nil if any of json not set", function()
conf.remove.json = {}
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.equals('100', ngx_headers[CONTENT_LENGTH])
end)
end)
describe("replace", function()
local conf = {
remove = {
json = {},
headers = {}
},
replace = {
json = {"p1:v1", "p2:v1"},
headers = {"h1:v1", "h2:v2"}
},
add = {
json = {},
headers = {}
},
append = {
json = {},
headers = {}
}
}
it("sets content-length nil if application/json passed", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
it("sets content-length nil if application/json and charset passed", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json; charset=utf-8"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
it("does not set content-length nil if content-type not json", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/x-www-form-urlencoded; charset=utf-8"}
header_transformer.transform_headers(conf, ngx_headers)
assert.equals('100', ngx_headers[CONTENT_LENGTH])
end)
it("does not set content-length nil if any of json not set", function()
conf.replace.json = {}
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.equals('100', ngx_headers[CONTENT_LENGTH])
end)
end)
describe("add", function()
local conf = {
remove = {
json = {},
headers = {}
},
replace = {
json = {},
headers = {}
},
add = {
json = {"p1:v1", "p2:v1"},
headers = {"h1:v1", "h2:v2"}
},
append = {
json = {},
headers = {}
}
}
it("set content-length nil if application/json passed", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
it("set content-length nil if application/json and charset passed", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json; charset=utf-8"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
it("does not set content-length nil if content-type not json", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/x-www-form-urlencoded; charset=utf-8"}
header_transformer.transform_headers(conf, ngx_headers)
assert.equals('100', ngx_headers[CONTENT_LENGTH])
end)
it("does not set content-length nil if any of json not set", function()
conf.add.json = {}
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.equals('100', ngx_headers[CONTENT_LENGTH])
end)
end)
describe("append", function()
local conf = {
remove = {
json = {},
headers = {}
},
replace = {
json = {},
headers = {}
},
add = {
json = {},
headers = {}
},
append = {
json = {"p1:v1", "p2:v1"},
headers = {"h1:v1", "h2:v2"}
}
}
it("set content-length nil if application/json passed", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
it("set content-length nil if application/json and charset passed", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json; charset=utf-8"}
header_transformer.transform_headers(conf, ngx_headers)
assert.is_nil(ngx_headers[CONTENT_LENGTH])
end)
it("does not set content-length nil if content-type not json", function()
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/x-www-form-urlencoded; charset=utf-8"}
header_transformer.transform_headers(conf, ngx_headers)
assert.equals('100', ngx_headers[CONTENT_LENGTH])
end)
it("does not set content-length nil if any of json not set", function()
conf.append.json = {}
local ngx_headers = {[CONTENT_LENGTH] = "100", ["content-type"] = "application/json"}
header_transformer.transform_headers(conf, ngx_headers)
assert.equals('100', ngx_headers[CONTENT_LENGTH])
end)
end)
end)
end)
end)
| apache-2.0 |
telegold/telespam | plugins/ingroup.lua | 202 | 31524 | 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] == 'link' 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.."]")
return "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 = {
"^[!/](add)$",
"^[!/](rem)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](demote) (.*)$",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
LORDMEHDI/TeleTard | plugins/ingroup.lua | 202 | 31524 | 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] == 'link' 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.."]")
return "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 = {
"^[!/](add)$",
"^[!/](rem)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](demote) (.*)$",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
mario0582/devenserver | data/npc/scripts/tapete izac.lua | 2 | 2378 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local travelNode = keywordHandler:addKeyword({'infernium'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You want fly to Infernium for 120 gold coins?'})
travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 2, cost = 120, destination = {x=237, y=259, z=8} })
travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'I wouldn\'t go there either.'})
local travelNode = keywordHandler:addKeyword({'flam'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You want fly to flam for 115 gold coins?'})
travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 2, cost = 115, destination = {x=393, y=76, z=5} })
travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'I wouldn\'t go there either.'})
local travelNode = keywordHandler:addKeyword({'saari'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You want fly to saari for 90 gold coins?'})
travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 2, cost = 90, destination = {x=259, y=112, z=5} })
travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'I wouldn\'t go there either.'})
local travelNode = keywordHandler:addKeyword({'mirand theraan'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You want fly to mirand theraan for 80 gold coins?'})
travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 2, cost = 80, destination = {x=297, y=177, z=6} })
travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'I wouldn\'t go there either.'})
npcHandler:addModule(FocusModule:new()) | gpl-2.0 |
liruqi/bigfoot | Interface/AddOns/BigFoot/AceLibs/LibDBIcon-1.0/LibDBIcon-1.0.lua | 1 | 11064 |
-----------------------------------------------------------------------
-- LibDBIcon-1.0
--
-- Allows addons to easily create a lightweight minimap icon as an alternative to heavier LDB displays.
--
local DBICON10 = "LibDBIcon-1.0"
local DBICON10_MINOR = 36 -- Bump on changes
if not LibStub then error(DBICON10 .. " requires LibStub.") end
local ldb = LibStub("LibDataBroker-1.1", true)
if not ldb then error(DBICON10 .. " requires LibDataBroker-1.1.") end
local lib = LibStub:NewLibrary(DBICON10, DBICON10_MINOR)
if not lib then return end
lib.disabled = lib.disabled or nil
lib.objects = lib.objects or {}
lib.callbackRegistered = lib.callbackRegistered or nil
lib.callbacks = lib.callbacks or LibStub("CallbackHandler-1.0"):New(lib)
lib.notCreated = lib.notCreated or {}
lib.tooltip = lib.tooltip or CreateFrame("GameTooltip", "LibDBIconTooltip", UIParent, "GameTooltipTemplate")
function lib:IconCallback(event, name, key, value)
if lib.objects[name] then
if key == "icon" then
lib.objects[name].icon:SetTexture(value)
elseif key == "iconCoords" then
lib.objects[name].icon:UpdateCoord()
elseif key == "iconR" then
local _, g, b = lib.objects[name].icon:GetVertexColor()
lib.objects[name].icon:SetVertexColor(value, g, b)
elseif key == "iconG" then
local r, _, b = lib.objects[name].icon:GetVertexColor()
lib.objects[name].icon:SetVertexColor(r, value, b)
elseif key == "iconB" then
local r, g = lib.objects[name].icon:GetVertexColor()
lib.objects[name].icon:SetVertexColor(r, g, value)
end
end
end
if not lib.callbackRegistered then
ldb.RegisterCallback(lib, "LibDataBroker_AttributeChanged__icon", "IconCallback")
ldb.RegisterCallback(lib, "LibDataBroker_AttributeChanged__iconCoords", "IconCallback")
ldb.RegisterCallback(lib, "LibDataBroker_AttributeChanged__iconR", "IconCallback")
ldb.RegisterCallback(lib, "LibDataBroker_AttributeChanged__iconG", "IconCallback")
ldb.RegisterCallback(lib, "LibDataBroker_AttributeChanged__iconB", "IconCallback")
lib.callbackRegistered = true
end
local function getAnchors(frame)
local x, y = frame:GetCenter()
if not x or not y then return "CENTER" end
local hhalf = (x > UIParent:GetWidth()*2/3) and "RIGHT" or (x < UIParent:GetWidth()/3) and "LEFT" or ""
local vhalf = (y > UIParent:GetHeight()/2) and "TOP" or "BOTTOM"
return vhalf..hhalf, frame, (vhalf == "TOP" and "BOTTOM" or "TOP")..hhalf
end
local function onEnter(self)
if self.isMoving then return end
local obj = self.dataObject
if obj.OnTooltipShow then
lib.tooltip:SetOwner(self, "ANCHOR_NONE")
lib.tooltip:SetPoint(getAnchors(self))
obj.OnTooltipShow(lib.tooltip)
lib.tooltip:Show()
elseif obj.OnEnter then
obj.OnEnter(self)
end
end
local function onLeave(self)
local obj = self.dataObject
lib.tooltip:Hide()
if obj.OnLeave then obj.OnLeave(self) end
end
--------------------------------------------------------------------------------
local onClick, onMouseUp, onMouseDown, onDragStart, onDragStop, updatePosition
do
local minimapShapes = {
["ROUND"] = {true, true, true, true},
["SQUARE"] = {false, false, false, false},
["CORNER-TOPLEFT"] = {false, false, false, true},
["CORNER-TOPRIGHT"] = {false, false, true, false},
["CORNER-BOTTOMLEFT"] = {false, true, false, false},
["CORNER-BOTTOMRIGHT"] = {true, false, false, false},
["SIDE-LEFT"] = {false, true, false, true},
["SIDE-RIGHT"] = {true, false, true, false},
["SIDE-TOP"] = {false, false, true, true},
["SIDE-BOTTOM"] = {true, true, false, false},
["TRICORNER-TOPLEFT"] = {false, true, true, true},
["TRICORNER-TOPRIGHT"] = {true, false, true, true},
["TRICORNER-BOTTOMLEFT"] = {true, true, false, true},
["TRICORNER-BOTTOMRIGHT"] = {true, true, true, false},
}
function updatePosition(button)
local angle = math.rad(button.db and button.db.minimapPos or button.minimapPos or 225)
local x, y, q = math.cos(angle), math.sin(angle), 1
if x < 0 then q = q + 1 end
if y > 0 then q = q + 2 end
local minimapShape = GetMinimapShape and GetMinimapShape() or "ROUND"
local quadTable = minimapShapes[minimapShape]
if quadTable[q] then
x, y = x*80, y*80
else
local diagRadius = 103.13708498985 --math.sqrt(2*(80)^2)-10
x = math.max(-80, math.min(x*diagRadius, 80))
y = math.max(-80, math.min(y*diagRadius, 80))
end
button:SetPoint("CENTER", Minimap, "CENTER", x, y)
end
end
function onClick(self, b) if self.dataObject.OnClick then self.dataObject.OnClick(self, b) end end
function onMouseDown(self) self.isMouseDown = true; self.icon:UpdateCoord() end
function onMouseUp(self) self.isMouseDown = false; self.icon:UpdateCoord() end
do
local function onUpdate(self)
local mx, my = Minimap:GetCenter()
local px, py = GetCursorPosition()
local scale = Minimap:GetEffectiveScale()
px, py = px / scale, py / scale
if self.db then
self.db.minimapPos = math.deg(math.atan2(py - my, px - mx)) % 360
else
self.minimapPos = math.deg(math.atan2(py - my, px - mx)) % 360
end
updatePosition(self)
end
function onDragStart(self)
self:LockHighlight()
self.isMouseDown = true
self.icon:UpdateCoord()
self:SetScript("OnUpdate", onUpdate)
self.isMoving = true
lib.tooltip:Hide()
end
end
function onDragStop(self)
self:SetScript("OnUpdate", nil)
self.isMouseDown = false
self.icon:UpdateCoord()
self:UnlockHighlight()
self.isMoving = nil
end
local defaultCoords = {0, 1, 0, 1}
local function updateCoord(self)
local coords = self:GetParent().dataObject.iconCoords or defaultCoords
local deltaX, deltaY = 0, 0
if not self:GetParent().isMouseDown then
deltaX = (coords[2] - coords[1]) * 0.05
deltaY = (coords[4] - coords[3]) * 0.05
end
self:SetTexCoord(coords[1] + deltaX, coords[2] - deltaX, coords[3] + deltaY, coords[4] - deltaY)
end
local function createButton(name, object, db)
local button = CreateFrame("Button", "LibDBIcon10_"..name, Minimap)
button.dataObject = object
button.db = db
button:SetFrameStrata("MEDIUM")
button:SetSize(31, 31)
button:SetFrameLevel(8)
button:RegisterForClicks("anyUp")
button:RegisterForDrag("LeftButton")
button:SetHighlightTexture(136477) --"Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight"
local overlay = button:CreateTexture(nil, "OVERLAY")
overlay:SetSize(53, 53)
overlay:SetTexture(136430) --"Interface\\Minimap\\MiniMap-TrackingBorder"
overlay:SetPoint("TOPLEFT")
local background = button:CreateTexture(nil, "BACKGROUND")
background:SetSize(20, 20)
background:SetTexture(136467) --"Interface\\Minimap\\UI-Minimap-Background"
background:SetPoint("TOPLEFT", 7, -5)
local icon = button:CreateTexture(nil, "ARTWORK")
icon:SetSize(17, 17)
icon:SetTexture(object.icon)
icon:SetPoint("TOPLEFT", 7, -6)
button.icon = icon
button.isMouseDown = false
local r, g, b = icon:GetVertexColor()
icon:SetVertexColor(object.iconR or r, object.iconG or g, object.iconB or b)
icon.UpdateCoord = updateCoord
icon:UpdateCoord()
button:SetScript("OnEnter", onEnter)
button:SetScript("OnLeave", onLeave)
button:SetScript("OnClick", onClick)
if not db or not db.lock then
button:SetScript("OnDragStart", onDragStart)
button:SetScript("OnDragStop", onDragStop)
end
button:SetScript("OnMouseDown", onMouseDown)
button:SetScript("OnMouseUp", onMouseUp)
lib.objects[name] = button
if lib.loggedIn then
updatePosition(button)
if not db or not db.hide then button:Show()
else button:Hide() end
end
lib.callbacks:Fire("LibDBIcon_IconCreated", button, name) -- Fire 'Icon Created' callback
end
-- We could use a metatable.__index on lib.objects, but then we'd create
-- the icons when checking things like :IsRegistered, which is not necessary.
local function check(name)
if lib.notCreated[name] then
createButton(name, lib.notCreated[name][1], lib.notCreated[name][2])
lib.notCreated[name] = nil
end
end
lib.loggedIn = lib.loggedIn or false
-- Wait a bit with the initial positioning to let any GetMinimapShape addons
-- load up.
if not lib.loggedIn then
local f = CreateFrame("Frame")
f:SetScript("OnEvent", function()
for _, object in pairs(lib.objects) do
updatePosition(object)
if not lib.disabled and (not object.db or not object.db.hide) then object:Show()
else object:Hide() end
end
lib.loggedIn = true
f:SetScript("OnEvent", nil)
f = nil
end)
f:RegisterEvent("PLAYER_LOGIN")
end
local function getDatabase(name)
return lib.notCreated[name] and lib.notCreated[name][2] or lib.objects[name].db
end
function lib:Register(name, object, db)
if not object.icon then error("Can't register LDB objects without icons set!") end
if lib.objects[name] or lib.notCreated[name] then error("Already registered, nubcake.") end
if not lib.disabled and (not db or not db.hide) then
createButton(name, object, db)
else
lib.notCreated[name] = {object, db}
end
end
function lib:Lock(name)
if not lib:IsRegistered(name) then return end
if lib.objects[name] then
lib.objects[name]:SetScript("OnDragStart", nil)
lib.objects[name]:SetScript("OnDragStop", nil)
end
local db = getDatabase(name)
if db then db.lock = true end
end
function lib:Unlock(name)
if not lib:IsRegistered(name) then return end
if lib.objects[name] then
lib.objects[name]:SetScript("OnDragStart", onDragStart)
lib.objects[name]:SetScript("OnDragStop", onDragStop)
end
local db = getDatabase(name)
if db then db.lock = nil end
end
function lib:Hide(name)
if not lib.objects[name] then return end
lib.objects[name]:Hide()
end
function lib:Show(name)
if lib.disabled then return end
check(name)
lib.objects[name]:Show()
updatePosition(lib.objects[name])
end
function lib:IsRegistered(name)
return (lib.objects[name] or lib.notCreated[name]) and true or false
end
function lib:Refresh(name, db)
if lib.disabled then return end
check(name)
local button = lib.objects[name]
if db then button.db = db end
updatePosition(button)
if not button.db or not button.db.hide then
button:Show()
else
button:Hide()
end
if not button.db or not button.db.lock then
button:SetScript("OnDragStart", onDragStart)
button:SetScript("OnDragStop", onDragStop)
else
button:SetScript("OnDragStart", nil)
button:SetScript("OnDragStop", nil)
end
end
function lib:GetMinimapButton(name)
return lib.objects[name]
end
function lib:EnableLibrary()
lib.disabled = nil
for name, object in pairs(lib.objects) do
if not object.db or not object.db.hide then
object:Show()
updatePosition(object)
end
end
for name, data in pairs(lib.notCreated) do
if not data.db or not data.db.hide then
createButton(name, data[1], data[2])
lib.notCreated[name] = nil
end
end
end
function lib:DisableLibrary()
lib.disabled = true
for name, object in pairs(lib.objects) do
object:Hide()
end
end
| mit |
br-lemes/stuff | smartlan/socket/tp.lua | 146 | 3608 | -----------------------------------------------------------------------------
-- Unified SMTP/FTP subsystem
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id: tp.lua,v 1.22 2006/03/14 09:04:15 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local socket = require("socket")
local ltn12 = require("ltn12")
module("socket.tp")
-----------------------------------------------------------------------------
-- Program constants
-----------------------------------------------------------------------------
TIMEOUT = 60
-----------------------------------------------------------------------------
-- Implementation
-----------------------------------------------------------------------------
-- gets server reply (works for SMTP and FTP)
local function get_reply(c)
local code, current, sep
local line, err = c:receive()
local reply = line
if err then return nil, err end
code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
if not code then return nil, "invalid server reply" end
if sep == "-" then -- reply is multiline
repeat
line, err = c:receive()
if err then return nil, err end
current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
reply = reply .. "\n" .. line
-- reply ends with same code
until code == current and sep == " "
end
return code, reply
end
-- metatable for sock object
local metat = { __index = {} }
function metat.__index:check(ok)
local code, reply = get_reply(self.c)
if not code then return nil, reply end
if base.type(ok) ~= "function" then
if base.type(ok) == "table" then
for i, v in base.ipairs(ok) do
if string.find(code, v) then
return base.tonumber(code), reply
end
end
return nil, reply
else
if string.find(code, ok) then return base.tonumber(code), reply
else return nil, reply end
end
else return ok(base.tonumber(code), reply) end
end
function metat.__index:command(cmd, arg)
if arg then
return self.c:send(cmd .. " " .. arg.. "\r\n")
else
return self.c:send(cmd .. "\r\n")
end
end
function metat.__index:sink(snk, pat)
local chunk, err = c:receive(pat)
return snk(chunk, err)
end
function metat.__index:send(data)
return self.c:send(data)
end
function metat.__index:receive(pat)
return self.c:receive(pat)
end
function metat.__index:getfd()
return self.c:getfd()
end
function metat.__index:dirty()
return self.c:dirty()
end
function metat.__index:getcontrol()
return self.c
end
function metat.__index:source(source, step)
local sink = socket.sink("keep-open", self.c)
local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step)
return ret, err
end
-- closes the underlying c
function metat.__index:close()
self.c:close()
return 1
end
-- connect with server and return c object
function connect(host, port, timeout, create)
local c, e = (create or socket.tcp)()
if not c then return nil, e end
c:settimeout(timeout or TIMEOUT)
local r, e = c:connect(host, port)
if not r then
c:close()
return nil, e
end
return base.setmetatable({c = c}, metat)
end
| mit |
Unknown8765/SpeedBot | plugins/time.lua | 771 | 2865 | -- Implement a command !time [area] which uses
-- 2 Google APIs to get the desired result:
-- 1. Geocoding to get from area to a lat/long pair
-- 2. Timezone to get the local time in that lat/long location
-- Globals
-- If you have a google api key for the geocoding/timezone api
api_key = nil
base_api = "https://maps.googleapis.com/maps/api"
dateFormat = "%A %d %B - %H:%M:%S"
-- Need the utc time for the google api
function utctime()
return os.time(os.date("!*t"))
end
-- Use the geocoding api to get the lattitude and longitude with accuracy specifier
-- CHECKME: this seems to work without a key??
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Get the data
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
-- Use timezone api to get the time in the lat,
-- Note: this needs an API key
function get_time(lat,lng)
local api = base_api .. "/timezone/json?"
-- Get a timestamp (server time is relevant here)
local timestamp = utctime()
local parameters = "location=" ..
URL.escape(lat) .. "," ..
URL.escape(lng) ..
"×tamp="..URL.escape(timestamp)
if api_key ~=nil then
parameters = parameters .. "&key="..api_key
end
local res,code = https.request(api..parameters)
if code ~= 200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Construct what we want
-- The local time in the location is:
-- timestamp + rawOffset + dstOffset
local localTime = timestamp + data.rawOffset + data.dstOffset
return localTime, data.timeZoneId
end
return localTime
end
function getformattedLocalTime(area)
if area == nil then
return "The time in nowhere is never"
end
lat,lng,acc = get_latlong(area)
if lat == nil and lng == nil then
return 'It seems that in "'..area..'" they do not have a concept of time.'
end
local localTime, timeZoneId = get_time(lat,lng)
return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime)
end
function run(msg, matches)
return getformattedLocalTime(matches[1])
end
return {
description = "Displays the local time in an area",
usage = "!time [area]: Displays the local time in that area",
patterns = {"^!time (.*)$"},
run = run
}
| gpl-2.0 |
andreaskoepf/faster-rcnn | create-imagenet-traindata.lua | 2 | 4481 | -- specify the base path of the ILSVRC2015 dataset:
ILSVRC2015_BASE_DIR = '/data/imagenet/ILSVRC2015/'
require 'lfs'
require 'LuaXML' -- if missing use luarocks install LuaXML
require 'utilities'
require 'Rect'
local ground_truth = {}
local class_names = {}
local class_index = {}
function import_file(anno_base, data_base, fn, name_table)
local x = xml.load(fn)
local a = x:find('annotation')
local folder = a:find('folder')[1]
local filename = a:find('filename')[1]
local src = a:find('source')
local db = src:find('database')[1]
local sz = a:find('size')
local w = tonumber(sz:find('width')[1])
local h = tonumber(sz:find('height')[1])
for _,e in pairs(a) do
if e[e.TAG] == 'object' then
local obj = e
local name = obj:find('name')[1]
local bb = obj:find('bndbox')
local xmin = tonumber(bb:find('xmin')[1])
local xmax = tonumber(bb:find('xmax')[1])
local ymin = tonumber(bb:find('ymin')[1])
local ymax = tonumber(bb:find('ymax')[1])
if not class_index[name] then
class_names[#class_names + 1] = name
class_index[name] = #class_names
end
-- generate path relative to annotation dir and join with data dir
local image_path = path.join(data_base, path.relpath(fn, anno_base))
-- replace 'xml' file ending with 'JPEG'
image_path = string.sub(image_path, 1, #image_path - 3) .. 'JPEG'
table.insert(name_table, image_path)
local roi = {
rect = Rect.new(xmin, ymin, xmax, ymax),
class_index = class_index[name],
class_name = name
}
local file_entry = ground_truth[image_path]
if not file_entry then
file_entry = { image_file_name = image_path, rois = {} }
ground_truth[image_path] = file_entry
end
table.insert(file_entry.rois, roi)
end
end
end
function import_directory(anno_base, data_base, directory_path, recursive, name_table)
for fn in lfs.dir(directory_path) do
local full_fn = path.join(directory_path, fn)
local mode = lfs.attributes(full_fn, 'mode')
if recursive and mode == 'directory' and fn ~= '.' and fn ~= '..' then
import_directory(anno_base, data_base, full_fn, true, name_table)
collectgarbage()
elseif mode == 'file' and string.sub(fn, -4):lower() == '.xml' then
import_file(anno_base, data_base, full_fn, name_table)
end
if #ground_truth > 10 then
return
end
end
return l
end
-- recursively search through training and validation directories and import all xml files
function create_ground_truth_file(dataset_name, base_dir, train_annotation_dir, val_annotation_dir, train_data_dir, val_data_dir, background_dirs, output_fn)
function expand(p)
return path.join(base_dir, p)
end
local training_set = {}
local validation_set = {}
import_directory(expand(train_annotation_dir), expand(train_data_dir), expand(train_annotation_dir), true, training_set)
import_directory(expand(val_annotation_dir), expand(val_data_dir), expand(val_annotation_dir), true, validation_set)
local file_names = keys(ground_truth)
-- compile list of background images
local background_files = {}
for i,directory_path in ipairs(background_dirs) do
directory_path = expand(directory_path)
for fn in lfs.dir(directory_path) do
local full_fn = path.join(directory_path, fn)
local mode = lfs.attributes(full_fn, 'mode')
if mode == 'file' and string.sub(fn, -5):lower() == '.jpeg' then
table.insert(background_files, full_fn)
end
end
end
print(string.format('Total images: %d; classes: %d; train_set: %d; validation_set: %d; (Background: %d)',
#file_names, #class_names, #training_set, #validation_set, #background_files
))
save_obj(
output_fn,
{
dataset_name = dataset_name,
ground_truth = ground_truth,
training_set = training_set,
validation_set = validation_set,
class_names = class_names,
class_index = class_index,
background_files = background_files
}
)
print('Done.')
end
background_folders = {}
for i=0,10 do
table.insert(background_folders, 'Data/DET/train/ILSVRC2013_train_extra' .. i)
end
create_ground_truth_file(
'ILSVRC2015_DET',
ILSVRC2015_BASE_DIR,
'Annotations/DET/train',
'Annotations/DET/val',
'Data/DET/train',
'Data/DET/val',
background_folders,
'ILSVRC2015_DET.t7'
)
| mit |
MocoNinja/LinuxConfs | Archlabs/.config/awesome/vicious/contrib/rss.lua | 18 | 1741 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2009, olcc
--
-- This is now a standalone RSS reader for awesome:
-- * http://github.com/olcc/aware
---------------------------------------------------
-- {{{ Grab environment
local pairs = pairs
local io = { popen = io.popen }
local setmetatable = setmetatable
-- }}}
-- RSS: provides latest world news
-- vicious.contrib.rss
local rss = {}
-- {{{ RSS widget type
local function worker(format, input)
-- input: * feed - feed url
-- * object - entity to look for (typically: 'item')
-- * fields - fields to read (example: 'link', 'title', 'description')
-- output: * count - number of entities found
-- * one table for each field, containing wanted values
local feed = input.feed
local object = input.object
local fields = input.fields
-- Initialise tables
local out = {}
for _, v in pairs(fields) do
out[v] = {}
end
-- Initialise variables
local ob = nil
local i,j,k = 1, 1, 0
local curl = "curl -A 'Mozilla/4.0' -fsm 5 --connect-timeout 3 "
-- Get the feed
local f = io.popen(curl .. '"' .. feed .. '"')
local feed = f:read("*all")
f:close()
while true do
i, j, ob = feed.find(feed, "<" .. object .. ">(.-)</" .. object .. ">", i)
if not ob then break end
for _, v in pairs(fields) do
out[v][k] = ob:match("<" .. v .. ">(.*)</" .. v .. ">")
end
k = k+1
i = j+1
end
-- Update the entity count
out.count = k
return out
end
-- }}}
return setmetatable(rss, { __call = function(_, ...) return worker(...) end })
| gpl-3.0 |
henkboom/pax-britannica | scripts/easy_enemy_production.lua | 5 | 2312 | local SCRIPTED_ACTIONS = { { 'fighter', 'fighter', 'fighter', 'fighter', 'bomber' },
{ 'fighter', 'fighter', 'fighter', 'bomber' },
{ 'fighter', 'fighter', 'bomber' },
{ 'fighter', 'fighter', 'fighter', 'frigate' } }
local action_index = 0
local frames_to_hold = 0
local accumulated_frames = 0
local frames_to_wait = 0
local script_index = 0
self.resources.harvest_rate = self.resources.harvest_rate * 0.8
local function next_script()
script_index = math.ceil(math.random() * table.getn(SCRIPTED_ACTIONS))
--print ('player ' .. self.ship.player .. ' picked script #' .. script_index)
end
local function next_action()
accumulated_frames = 0
action_index = action_index + 1
if action_index > table.getn(SCRIPTED_ACTIONS[script_index]) then
action_index = 1
next_script()
end
-- how much time to hold the button
frames_to_hold = (self.production.UNIT_COSTS[SCRIPTED_ACTIONS[script_index][action_index]] - self.production.UNIT_COSTS['fighter']) / self.production.BUILDING_SPEED + 2 + math.random() * 60
-- how much time to wait before actually performing the scripted action?
if not self.resources then return end
local missing_resources = (self.production.UNIT_COSTS[SCRIPTED_ACTIONS[script_index][action_index]] - self.resources.amount) / self.resources.harvest_rate
frames_to_wait = math.max(missing_resources + 1, 0) + math.random() * 60
--print('producing ' .. SCRIPTED_ACTIONS[action_index] .. ' : ' .. frames_to_hold .. ' held, ' .. frames_to_wait .. ' waited')
end
-- take the first action on init
next_script()
next_action()
function update()
-- make sure we still have enemies
local found_enemy = false
for _, actor in ipairs(game.actors.get('factory')) do
if actor.ship and actor.ship.player ~= self.ship.player then found_enemy = true end
end
if not found_enemy then
self.production.button_held = false
return
end
accumulated_frames = accumulated_frames + 1
self.production.button_held = accumulated_frames > frames_to_wait and accumulated_frames < frames_to_hold + frames_to_wait
if accumulated_frames > frames_to_hold + frames_to_wait then
next_action()
end
end | mit |
Unknown8765/SpeedBot | plugins/rae.lua | 616 | 1312 | do
function getDulcinea( text )
-- Powered by https://github.com/javierhonduco/dulcinea
local api = "http://dulcinea.herokuapp.com/api/?query="
local query_url = api..text
local b, code = http.request(query_url)
if code ~= 200 then
return "Error: HTTP Connection"
end
dulcinea = json:decode(b)
if dulcinea.status == "error" then
return "Error: " .. dulcinea.message
end
while dulcinea.type == "multiple" do
text = dulcinea.response[1].id
b = http.request(api..text)
dulcinea = json:decode(b)
end
local text = ""
local responses = #dulcinea.response
if responses == 0 then
return "Error: 404 word not found"
end
if (responses > 5) then
responses = 5
end
for i = 1, responses, 1 do
text = text .. dulcinea.response[i].word .. "\n"
local meanings = #dulcinea.response[i].meanings
if (meanings > 5) then
meanings = 5
end
for j = 1, meanings, 1 do
local meaning = dulcinea.response[i].meanings[j].meaning
text = text .. meaning .. "\n\n"
end
end
return text
end
function run(msg, matches)
return getDulcinea(matches[1])
end
return {
description = "Spanish dictionary",
usage = "!rae [word]: Search that word in Spanish dictionary.",
patterns = {"^!rae (.*)$"},
run = run
}
end | gpl-2.0 |
alijoooon/Psycho | plugins/welcome.lua | 5 | 3684 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\n› توضیحات گروه :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\n› قوانین گروه :\n"..rules.."\n"
end
local sambutan = "سلام "..nama.." عزیز\nبه گروه "..string.gsub(msg.to.print_name, "_", " ").."\nخوش آمدید ، شما میتوانید به کمک\nدستور /help راهنمایی دریافت کنید.\n"
local text = sambutan..about..rules.."\n"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return '✋😐 خداحافظ \n' ..bye_name
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
nurv/lirec | scenarios/MyFriend/MyPleo/tags/version-1.05/workspace/viPleoShivaModule/Resources/Scripts/MyPleoAI_Function_updateAttachmentEstimate.lua | 2 | 1403 | --------------------------------------------------------------------------------
-- Function......... : updateAttachmentEstimate
-- Author........... : Paulo F. Gomes
-- Description...... : Updates the attachment estimate calculating a weighted
-- sum of all needs.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function MyPleoAI.updateAttachmentEstimate ( )
--------------------------------------------------------------------------------
local nAttachmentEstimate = 0
nAttachmentEstimate = nAttachmentEstimate + this.getNeedCleanliness ( ) * this.nNeedCleanlinessWeight ( )
nAttachmentEstimate = nAttachmentEstimate + this.getNeedEnergy ( ) * this.nNeedEnergyWeight ( )
nAttachmentEstimate = nAttachmentEstimate + this.getNeedPetting ( ) * this.nNeedPettingWeight ( )
nAttachmentEstimate = nAttachmentEstimate + this.getNeedSkills ( ) * this.nNeedSkillsWeight ( )
nAttachmentEstimate = nAttachmentEstimate + this.getNeedWater ( ) * this.nNeedWaterWeight ( )
application.setCurrentUserEnvironmentVariable ( "nAttachmentEstimate" , nAttachmentEstimate )
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
| gpl-3.0 |
jessemillar/the-staff-of-lewis | lib/hump/class.lua | 9 | 3066 | --[[
Copyright (c) 2010-2013 Matthias Richter
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.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
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 function include_helper(to, from, seen)
if from == nil then
return to
elseif type(from) ~= 'table' then
return from
elseif seen[from] then
return seen[from]
end
seen[from] = to
for k,v in pairs(from) do
k = include_helper({}, k, seen) -- keys might also be tables
if to[k] == nil then
to[k] = include_helper({}, v, seen)
end
end
return to
end
-- deeply copies `other' into `class'. keys in `other' that are already
-- defined in `class' are omitted
local function include(class, other)
return include_helper(class, other, {})
end
-- returns a deep copy of `other'
local function clone(other)
return setmetatable(include({}, other), getmetatable(other))
end
local function new(class)
-- mixins
class = class or {} -- class can be nil
local inc = class.__includes or {}
if getmetatable(inc) then inc = {inc} end
for _, other in ipairs(inc) do
if type(other) == "string" then
other = _G[other]
end
include(class, other)
end
-- class implementation
class.__index = class
class.init = class.init or class[1] or function() end
class.include = class.include or include
class.clone = class.clone or clone
-- constructor call
return setmetatable(class, {__call = function(c, ...)
local o = setmetatable({}, c)
o:init(...)
return o
end})
end
-- interface for cross class-system compatibility (see https://github.com/bartbes/Class-Commons).
if class_commons ~= false and not common then
common = {}
function common.class(name, prototype, parent)
return new{__includes = {prototype, parent}}
end
function common.instance(class, ...)
return class(...)
end
end
-- the module
return setmetatable({new = new, include = include, clone = clone},
{__call = function(_,...) return new(...) end})
| mit |
hanfang/scikit-ribo | tools/samtools-1.2/misc/r2plot.lua | 28 | 2877 | #!/usr/bin/env luajit
function string:split(sep, n)
local a, start = {}, 1;
sep = sep or "%s+";
repeat
local b, e = self:find(sep, start);
if b == nil then
table.insert(a, self:sub(start));
break
end
a[#a+1] = self:sub(start, b - 1);
start = e + 1;
if n and #a == n then
table.insert(a, self:sub(start));
break
end
until start > #self;
return a;
end
function io.xopen(fn, mode)
mode = mode or 'r';
if fn == nil then return io.stdin;
elseif fn == '-' then return (mode == 'r' and io.stdin) or io.stdout;
elseif fn:sub(-3) == '.gz' then return (mode == 'r' and io.popen('gzip -dc ' .. fn, 'r')) or io.popen('gzip > ' .. fn, 'w');
elseif fn:sub(-4) == '.bz2' then return (mode == 'r' and io.popen('bzip2 -dc ' .. fn, 'r')) or io.popen('bgzip2 > ' .. fn, 'w');
else return io.open(fn, mode) end
end
local eps = {};
function eps.func(fp)
fp = fp or io.stdout
fp:write("/C { dup 255 and 255 div exch dup -8 bitshift 255 and 255 div 3 1 roll -16 bitshift 255 and 255 div 3 1 roll setrgbcolor } bind def\n")
fp:write("/L { 4 2 roll moveto lineto } bind def\n")
fp:write("/LX { dup 4 -1 roll exch moveto lineto } bind def\n")
fp:write("/LY { dup 4 -1 roll moveto exch lineto } bind def\n")
fp:write("/LS { 3 1 roll moveto show } bind def\n")
fp:write("/RS { dup stringwidth pop 4 -1 roll exch sub 3 -1 roll moveto show } bind def\n")
fp:write("/B { 4 copy 3 1 roll exch 6 2 roll 8 -2 roll moveto lineto lineto lineto closepath } bind def\n")
end
function eps.font(ft, size, fp)
fp = fp or io.stdout
fp:write(string.format('/FS %d def\n', size));
fp:write('/FS4 FS 4 div def\n');
fp:write('/' .. ft .. ' findfont FS scalefont setfont\n');
end
local scale = 8;
if #arg == 0 then
print("Usage: r2plot.lua <in.txt>");
os.exit(1)
end
local fp = io.xopen(arg[1]);
local n = tonumber(fp:read());
print('%!PS-Adobe-3.0 EPSF-3.0');
print('%%' .. string.format('BoundingBox: -%d -%d %.3f %.3f\n', 10*scale, scale, (n+1)*scale, (n+1)*scale));
print(string.format('%.3f setlinewidth', scale));
print(string.format('/plot { setgray moveto 0 %d rlineto } def', scale));
print(string.format('/plothalf { setgray moveto 0 %.2f rlineto } def', scale/2));
eps.func();
eps.font('Helvetica', scale-1);
local i = 1;
for l in fp:lines() do
local t = l:split('\t');
print(string.format("%d %d FS4 add (%s) RS", (i-1)*scale-2, (i-1)*scale, t[1]));
for j = 2, #t do
if tonumber(t[j]) > 0.01 then
print(string.format('%.2f %.2f %.2f plot stroke', (i-1+.5)*scale, (j-2)*scale, 1.-t[j]));
end
end
i = i + 1;
end
for j = 1, 21 do
print(string.format('%.2f %.2f %.2f plothalf stroke', -8*scale, (j-1) * scale/2, 1.-(j-1)/20));
end
print('showpage');
| gpl-2.0 |
liruqi/bigfoot | Interface/AddOns/Bagnon/components/sortButton.lua | 1 | 2021 | --[[
sortButton.lua
Sorting options button
--]]
local ADDON, Addon = ...
local L = LibStub('AceLocale-3.0'):GetLocale(ADDON)
local SortButton = Addon:NewClass('SortButton', 'CheckButton')
local SIZE = 20
local NORMAL_TEXTURE_SIZE = 64 * (SIZE/36)
local FIRST_FLAG, LAST_FLAG = LE_BAG_FILTER_FLAG_IGNORE_CLEANUP, NUM_LE_BAG_FILTER_FLAGS
--[[ Constructor ]]--
function SortButton:New(parent)
local b = self:Bind(CreateFrame('CheckButton', nil, parent))
b:RegisterForClicks('anyUp')
b:SetSize(SIZE, SIZE)
local nt = b:CreateTexture()
nt:SetTexture([[Interface\Buttons\UI-Quickslot2]])
nt:SetSize(NORMAL_TEXTURE_SIZE, NORMAL_TEXTURE_SIZE)
nt:SetPoint('CENTER', 0, -1)
b:SetNormalTexture(nt)
local pt = b:CreateTexture()
pt:SetTexture([[Interface\Buttons\UI-Quickslot-Depress]])
pt:SetAllPoints(b)
b:SetPushedTexture(pt)
local ht = b:CreateTexture()
ht:SetTexture([[Interface\Buttons\ButtonHilight-Square]])
ht:SetAllPoints(b)
b:SetHighlightTexture(ht)
local icon = b:CreateTexture()
icon:SetTexture([[Interface\Icons\Achievement_GuildPerk_Quick and Dead]])
icon:SetAllPoints(b)
b:SetScript('OnClick', b.OnClick)
b:SetScript('OnEnter', b.OnEnter)
b:SetScript('OnLeave', b.OnLeave)
return b
end
--[[ Interaction ]]--
function SortButton:OnClick(button)
local isBank = self:GetParent().frameID == 'bank'
if button == 'RightButton' then
if isBank then
SortReagentBankBags()
SortBankBags()
end
elseif isBank then
DepositReagentBank()
else
SortBags()
end
end
function SortButton:OnEnter()
GameTooltip:SetOwner(self, self:GetRight() > (GetScreenWidth() / 2) and 'ANCHOR_LEFT' or 'ANCHOR_RIGHT')
local frameID = self:GetParent().frameID
if frameID == 'bank' then
GameTooltip:SetText(L.TipManageBank)
GameTooltip:AddLine(L.TipDepositReagents, 1,1,1)
GameTooltip:AddLine(L.TipCleanBank, 1,1,1)
else
GameTooltip:SetText(L.TipCleanBags)
end
GameTooltip:Show()
end
function SortButton:OnLeave()
if GameTooltip:IsOwned(self) then
GameTooltip:Hide()
end
end | mit |
nurv/lirec | scenarios/MyFriend/MyPleo/tags/version-1.05/workspace/viPleoShivaModule/Resources/Scripts/MyPleoAI_Game_State_WalkToTarget_onEnter.lua | 2 | 1073 | --------------------------------------------------------------------------------
-- State............ : WalkToTarget
-- Author........... : Tiago Paiva
-- Description...... : (unsure if it is being used)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function MyPleoAI_Game.WalkToTarget_onEnter ( )
--------------------------------------------------------------------------------
-- log.message ( "WALK TO TARGET" )
local hObject = this.hObject ( )
-- hud.newTemplateInstance ( )
log.message ( "DEStruIDOOOOO" )
local hProg= application.getCurrentUserEnvironmentVariable ( "hProg")
application.setCurrentUserEnvironmentVariable ( "hProg", false)
--hud.destroyTemplateInstance ( application.getCurrentUser ( ), "myHIT" )
-----------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
| gpl-3.0 |
liruqi/bigfoot | Interface/AddOns/DBM-Scenario-MoP/Landfall/Landfall.lua | 1 | 1723 | local mod = DBM:NewMod("Landfall", "DBM-Scenario-MoP")--Alliance : 590, Horde : 595
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 2 $"):sub(12, -3))
mod:SetZone()
mod:RegisterCombat("scenario", 1103, 1102)
mod:RegisterEventsInCombat(
"SPELL_CAST_START",
"UNIT_DIED"
)
mod.onlyNormal = true
local warnDivineStorm = mod:NewSpellAnnounce(135404, 4, nil, mod:IsMelee())
local warnDivineLight = mod:NewSpellAnnounce(135403, 4)
local warnAchFiveAlive = mod:NewAnnounce("WarnAchFiveAlive", 3, nil, false)
local specWarnDivineLight = mod:NewSpecialWarningInterrupt(135403)
mod:RemoveOption("HealthFrame")
--[[ Alliance 'heroes'
68581 Daggin Windbeard
68685 Admiral Taylor
68871 Amber Kearnen
68883 Sully "The Pickle" MxLeary
68870 Mishka
--]]
--[[ Horde 'heroes' -- Someone verify those please :)
68997 General Nazgrim
69002 Warlord Bloodhilt
68996 Kromthar
--]]
local heroes = {
[68581] = "Daggin Windbeard",
[68695] = "Admiral Taylor",
[68871] = "Amber Kearnen",
[68883] = "Sully \"The Pickle\" MxLeary",
[68870] = "Mishka"
}
local achievementFailed = false
function mod:OnCombatStart(delay)
achievementFailed = false
end
function mod:SPELL_CAST_START(args)
if args.spellId == 135403 then
warnDivineLight:Show()
specWarnDivineLight:Show(args.sourceName)
elseif args.spellId == 135404 then
warnDivineStorm:Show()
end
end
function mod:UNIT_DIED(args)
local cid = self:GetCIDFromGUID(args.destGUID)
if heroes[cid] then
self:SendSync("AchFailed")
end
end
function mod:OnSync(msg, str)
if not achievementFailed and msg == "AchFailed" then
achievementFailed = true
warnAchFiveAlive:Show()
end
end
| mit |
pouya-joker/Telecat | plugins/cpu.lua | 244 | 1893 | function run_sh(msg)
name = get_name(msg)
text = ''
-- if config.sh_enabled == false then
-- text = '!sh command is disabled'
-- else
-- if is_sudo(msg) then
-- bash = msg.text:sub(4,-1)
-- text = run_bash(bash)
-- else
-- text = name .. ' you have no power here!'
-- end
-- end
if is_sudo(msg) then
bash = msg.text:sub(4,-1)
text = run_bash(bash)
else
text = name .. ' you have no power here!'
end
return text
end
function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
function on_getting_dialogs(cb_extra,success,result)
if success then
local dialogs={}
for key,value in pairs(result) do
for chatkey, chat in pairs(value.peer) do
print(chatkey,chat)
if chatkey=="id" then
table.insert(dialogs,chat.."\n")
end
if chatkey=="print_name" then
table.insert(dialogs,chat..": ")
end
end
end
send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false)
end
end
function run(msg, matches)
if not is_sudo(msg) then
return "You aren't allowed!"
end
local receiver = get_receiver(msg)
if string.match(msg.text, '!sh') then
text = run_sh(msg)
send_msg(receiver, text, ok_cb, false)
return
end
if string.match(msg.text, '!$ uptime') then
text = run_bash('uname -snr') .. ' ' .. run_bash('whoami')
text = text .. '\n' .. run_bash('top -b |head -2')
send_msg(receiver, text, ok_cb, false)
return
end
if matches[1]=="Get dialogs" then
get_dialog_list(on_getting_dialogs,{get_receiver(msg)})
return
end
end
return {
description = "shows cpuinfo",
usage = "!$ uptime",
patterns = {"^!$ uptime", "^!sh","^Get dialogs$"},
run = run
}
| gpl-2.0 |
Electrovirus/Griffin | lang/english_lang.lua | 1 | 19295 | --------------------------------------------------
-- ____ ____ _____ --
-- | \| _ )_ _|___ ____ __ __ --
-- | |_ ) _ \ | |/ ·__| _ \_| \/ | --
-- |____/|____/ |_|\____/\_____|_/\/\_| --
-- --
--------------------------------------------------
-- --
-- Developers: @Josepdal & @MaSkAoS --
-- Support: @Skneos, @iicc1 & @serx666 --
-- --
--------------------------------------------------
local LANG = 'en'
local function run(msg, matches)
if permissions(msg.from.id, msg.to.id, "lang_install") then
-------------------------
-- Translation version --
-------------------------
set_text(LANG, 'version', '0.2')
set_text(LANG, 'versionExtended', 'Translation version 0.2')
-------------
-- Plugins --
-------------
-- global plugins --
set_text(LANG, 'require_sudo', 'This plugin requires sudo privileges.')
set_text(LANG, 'require_admin', 'This plugin requires admin privileges or higher.')
set_text(LANG, 'require_mod', 'This plugin requires mod privileges or higher.')
-- Spam.lua --
set_text(LANG, 'reportUser', 'USER')
set_text(LANG, 'reportReason', 'Report reason')
set_text(LANG, 'reportGroup', 'Group')
set_text(LANG, 'reportMessage', 'Message')
set_text(LANG, 'allowedSpamT', 'Spam is now allowed in this chat.')
set_text(LANG, 'allowedSpamL', 'Spam is now allowed in this supergroup.')
set_text(LANG, 'notAllowedSpamT', 'Spam is not allowed in this chat.')
set_text(LANG, 'notAllowedSpamL', 'Spam is not allowed in this supergroup.')
-- bot.lua --
set_text(LANG, 'botOn', 'I\'m back. Let\'s do this')
set_text(LANG, 'botOff', 'Nothing to do here')
-- settings.lua --
set_text(LANG, 'user', 'User')
set_text(LANG, 'isFlooding', 'is flooding')
set_text(LANG, 'noStickersT', 'Stickers are not allowed in this chat.')
set_text(LANG, 'noStickersL', 'Stickers are not allowed in this supergroup.')
set_text(LANG, 'stickersT', 'Stickers are now allowed in this chat.')
set_text(LANG, 'stickersL', 'Stickers are now allowed in this supergroup.')
set_text(LANG, 'noTgservicesT', 'Telegram services muted in this chat.')
set_text(LANG, 'noTgservicesL', 'Telegram services muted in this supergroup.')
set_text(LANG, 'tgservicesT', 'Telegram services allowed in this chat.')
set_text(LANG, 'tgservicesL', 'Telegram services allowed in this supergroup.')
set_text(LANG, 'LinksT', 'Links are now allowed in this chat.')
set_text(LANG, 'LinksL', 'Links are now allowed in this supergroup.')
set_text(LANG, 'noLinksT', 'Links are not allowed in this chat.')
set_text(LANG, 'noLinksL', 'Links are not allowed in this supergroup.')
set_text(LANG, 'gifsT', 'Gifs are now allowed in this chat.')
set_text(LANG, 'gifsL', 'Gifs are now allowed in this supergroup.')
set_text(LANG, 'noGifsT', 'Gifs are not allowed in this chat.')
set_text(LANG, 'noGifsL', 'Gifs are not allowed in this supergroup.')
set_text(LANG, 'photosT', 'Photos are now allowed in this chat.')
set_text(LANG, 'photosL', 'Photos are now allowed in this supergroup.')
set_text(LANG, 'noPhotosT', 'Photos are not allowed in this chat.')
set_text(LANG, 'noPhotosL', 'Photos are not allowed in this supergroup.')
set_text(LANG, 'botsT', 'Bots are now allowed in this chat.')
set_text(LANG, 'botsL', 'Bots are now allowed in this supergroup.')
set_text(LANG, 'noBotsT', 'Bots are not allowed in this chat.')
set_text(LANG, 'noBotsL', 'Bots are not allowed in this supergroup.')
set_text(LANG, 'arabicT', 'Arabic is now allowed in this chat.')
set_text(LANG, 'arabicL', 'Arabic is now allowed in this supergroup.')
set_text(LANG, 'noArabicT', 'Arabic is not allowed in this chat.')
set_text(LANG, 'noArabicL', 'Arabic is not allowed in this supergroup.')
set_text(LANG, 'audiosT', 'Audios are now allowed in this chat.')
set_text(LANG, 'audiosL', 'Audios are now allowed in this supergroup.')
set_text(LANG, 'noAudiosT', 'Audios are not allowed in this chat.')
set_text(LANG, 'noAudiosL', 'Audios are not allowed in this supergroup.')
set_text(LANG, 'kickmeT', 'Autokick is now allowed in this chat.')
set_text(LANG, 'kickmeL', 'Autokick is now allowed in this supergroup.')
set_text(LANG, 'noKickmeT', 'Autokick is not allowed in this chat.')
set_text(LANG, 'noKickmeL', 'Autokick is not allowed in this supergroup.')
set_text(LANG, 'floodT', 'Flood is now allowed in this chat.')
set_text(LANG, 'floodL', 'Flood is now allowed in this supergroup.')
set_text(LANG, 'noFloodT', 'Flood is not allowed in this chat.')
set_text(LANG, 'noFloodL', 'Flood is not allowed in this supergroup.')
set_text(LANG, 'floodTime', 'Flood time check has been set to ')
set_text(LANG, 'floodMax', 'Max flood messages have been set to ')
set_text(LANG, 'gSettings', 'Group settings')
set_text(LANG, 'sSettings', 'SuperGroup settings')
set_text(LANG, 'allowed', 'allowed')
set_text(LANG, 'noAllowed', 'not allowed')
set_text(LANG, 'noSet', 'not set')
set_text(LANG, 'stickers', 'Stickers')
set_text(LANG, 'tgservices', 'Tg services')
set_text(LANG, 'links', 'Links')
set_text(LANG, 'arabic', 'Arabic')
set_text(LANG, 'bots', 'Bots')
set_text(LANG, 'gifs', 'Gifs')
set_text(LANG, 'photos', 'Photos')
set_text(LANG, 'audios', 'Audios')
set_text(LANG, 'kickme', 'Kickme')
set_text(LANG, 'spam', 'Spam')
set_text(LANG, 'gName', 'Group Name')
set_text(LANG, 'flood', 'Flood')
set_text(LANG, 'language', 'Language')
set_text(LANG, 'mFlood', 'Flood max')
set_text(LANG, 'tFlood', 'Flood time')
set_text(LANG, 'setphoto', 'Set photo')
set_text(LANG, 'photoSaved', 'Photo saved!')
set_text(LANG, 'photoFailed', 'Failed, please try again!')
set_text(LANG, 'setPhotoAborted', 'Stopping setphoto process...')
set_text(LANG, 'sendPhoto', 'Please, send a photo')
set_text(LANG, 'chatSetphoto', 'Now you can setphoto in this chat.')
set_text(LANG, 'channelSetphoto', 'Now you can setphoto in this channel.')
set_text(LANG, 'notChatSetphoto', 'Now you can\'t setphoto in this chat.')
set_text(LANG, 'notChannelSetphoto', 'Now you can\'t setphoto in this channel.')
set_text(LANG, 'setPhotoError', 'Please, enable setphoto settings.')
set_text(LANG, 'linkSaved', 'New link saved.')
set_text(LANG, 'groupLink', 'Group Link')
set_text(LANG, 'sGroupLink', 'SuperGroup Link')
set_text(LANG, 'noLinkSet', 'There is not link set yet. Please add one by #setlink [Link].')
set_text(LANG, 'chatRename', 'Now you can rename the chat.')
set_text(LANG, 'channelRename', 'Now you can rename the channel.')
set_text(LANG, 'notChatRename', 'Now you can\'t rename the chat.')
set_text(LANG, 'notChannelRename', 'Now you can\'t rename the channel.')
set_text(LANG, 'lockMembersT', 'The number of members has been locked on this chat.')
set_text(LANG, 'lockMembersL', 'The number of members has been locked on this channel.')
set_text(LANG, 'notLockMembersT', 'The number of members now is not locked on this chat.')
set_text(LANG, 'notLockMembersL', 'The number of members now is not locked on this channel.')
set_text(LANG, 'langUpdated', 'Your language has been updated to: ')
set_text(LANG, 'chatUpgrade', 'Chat Upgraded Successfully.')
set_text(LANG, 'notInChann', 'You can\'t do this in a supergroup.')
set_text(LANG, 'chatUpgrade', 'Chat Upgraded Successfully.')
set_text(LANG, 'notInChann', 'You can\'t do this in a supergroup.')
set_text(LANG, 'desChanged', 'Channel description has been changed.')
set_text(LANG, 'desOnlyChannels', 'Description only can be changed in channels.')
set_text(LANG, 'muteAll', 'Everyone is muted now.')
set_text(LANG, 'unmuteAll', 'Everyone can talk now.')
set_text(LANG, 'muteAllX:1', 'This channel has been muted for')
set_text(LANG, 'muteAllX:2', 'seconds.')
set_text(LANG, 'createGroup:1', 'Group')
set_text(LANG, 'createGroup:2', 'created.')
set_text(LANG, 'newGroupWelcome', 'Welcome to your new group.')
-- export_gban.lua --
set_text(LANG, 'accountsGban', 'accounts globally banned.')
-- giverank.lua --
set_text(LANG, 'alreadyAdmin', 'This user is already admin.')
set_text(LANG, 'alreadyMod', 'This user is already mod.')
set_text(LANG, 'newAdmin', 'New admin')
set_text(LANG, 'newMod', 'New mod')
set_text(LANG, 'nowUser', 'is now an user.')
set_text(LANG, 'modList', 'Mods list')
set_text(LANG, 'adminList', 'Admins list')
set_text(LANG, 'modEmpty', 'Mod list is empty in this chat.')
set_text(LANG, 'adminEmpty', 'Admin list is empty.')
-- id.lua --
set_text(LANG, 'user', 'User')
set_text(LANG, 'supergroupName', 'SuperGroup Name')
set_text(LANG, 'chatName', 'Chat Name')
set_text(LANG, 'supergroup', 'SuperGroup')
set_text(LANG, 'chat', 'Chat')
-- moderation.lua --
set_text(LANG, 'userUnmuted:1', 'User')
set_text(LANG, 'userUnmuted:2', 'unmuted.')
set_text(LANG, 'userMuted:1', 'User')
set_text(LANG, 'userMuted:2', 'muted.')
set_text(LANG, 'kickUser:1', 'User')
set_text(LANG, 'kickUser:2', 'kicked out.')
set_text(LANG, 'banUser:1', 'User')
set_text(LANG, 'banUser:2', 'banned.')
set_text(LANG, 'unbanUser:1', 'User')
set_text(LANG, 'unbanUser:2', 'is unbanned.')
set_text(LANG, 'gbanUser:1', 'User')
set_text(LANG, 'gbanUser:2', 'globally banned.')
set_text(LANG, 'ungbanUser:1', 'User')
set_text(LANG, 'ungbanUser:2', 'unglobally banned.')
set_text(LANG, 'addUser:1', 'User')
set_text(LANG, 'addUser:2', 'added to chat.')
set_text(LANG, 'addUser:3', 'added to channel.')
set_text(LANG, 'kickmeBye', 'bye.')
-- plugins.lua --
set_text(LANG, 'plugins', 'Plugins')
set_text(LANG, 'installedPlugins', 'plugins installed.')
set_text(LANG, 'pEnabled', 'enabled.')
set_text(LANG, 'pDisabled', 'disabled.')
set_text(LANG, 'isEnabled:1', 'Plugin')
set_text(LANG, 'isEnabled:2', 'is enabled.')
set_text(LANG, 'notExist:1', 'Plugin')
set_text(LANG, 'notExist:2', 'does not exists.')
set_text(LANG, 'notEnabled:1', 'Plugin')
set_text(LANG, 'notEnabled:2', 'not enabled.')
set_text(LANG, 'pNotExists', 'Plugin doesn\'t exists.')
set_text(LANG, 'pDisChat:1', 'Plugin')
set_text(LANG, 'pDisChat:2', 'disabled on this chat.')
set_text(LANG, 'anyDisPlugin', 'There aren\'t any disabled plugins.')
set_text(LANG, 'anyDisPluginChat', 'There aren\'t any disabled plugins for this chat.')
set_text(LANG, 'notDisabled', 'This plugin is not disabled')
set_text(LANG, 'enabledAgain:1', 'Plugin')
set_text(LANG, 'enabledAgain:2', 'is enabled again')
-- commands.lua --
set_text(LANG, 'commandsT', 'Commands')
set_text(LANG, 'errorNoPlug', 'This plugin does not exists or has not usages.')
-- rules.lua --
set_text(LANG, 'setRules', 'Chat rules have been updated.')
set_text(LANG, 'remRules', 'Chat rules have been removed.')
------------
-- Usages --
------------
-- bot.lua --
set_text(LANG, 'bot:0', 2)
set_text(LANG, 'bot:1', '+bot on: enable bot in current channel.')
set_text(LANG, 'bot:2', '+bot off: disable bot in current channel.')
-- commands.lua --
set_text(LANG, 'commands:0', 2)
set_text(LANG, 'commands:1', '+commands: Show all commands for every plugin.')
set_text(LANG, 'commands:2', '+commands [plugin]: Commands for that plugin.')
-- export_gban.lua --
set_text(LANG, 'export_gban:0', 2)
set_text(LANG, 'export_gban:1', '+gbans installer: Return a lua file installer to share gbans and add those in another bot in just one command.')
set_text(LANG, 'export_gban:2', '+gbans list: Return an archive with a list of gbans.')
-- gban_installer.lua --
set_text(LANG, 'gban_installer:0', 1)
set_text(LANG, 'gban_installer:1', '+install gbans: add a list of gbans into your redis db.')
-- welcome.lua --
set_text(LANG, 'welcome:0', 6)
set_text(LANG, 'welcome:1', 'You should use + Griffin V.1👑')
-- giverank.lua --
set_text(LANG, 'giverank:0', 9)
set_text(LANG, 'giverank:1', '+rank admin (reply): add admin by reply.')
set_text(LANG, 'giverank:2', '+rank admin <user_id>/<user_name>: add admin by user ID/Username.')
set_text(LANG, 'giverank:3', '+rank mod (reply): add mod by reply.')
set_text(LANG, 'giverank:4', '+rank mod <user_id>/<user_name>: add mod by user ID/Username.')
set_text(LANG, 'giverank:5', '+rank guest (reply): remove admin by reply.')
set_text(LANG, 'giverank:6', '+rank guest <user_id>/<user_name>: remove admin by user ID/Username.')
set_text(LANG, 'giverank:7', '+admins: list of all admin members.')
set_text(LANG, 'giverank:8', '+mods: list of all mod members.')
set_text(LANG, 'giverank:9', '+members: list of all channel members.')
-- id.lua --
set_text(LANG, 'id:0', 6)
set_text(LANG, 'id:1', '+id: Return your ID and the chat id if you are in one.')
set_text(LANG, 'id:2', '+ids chat: Return the IDs of the current chat members.')
set_text(LANG, 'id:3', '+ids channel: Return the IDs of the current channel members.')
set_text(LANG, 'id:4', '+id <user_name>: Return the member username ID from the current chat.')
set_text(LANG, 'id:5', '+whois <user_id>/<user_name>: Return username.')
set_text(LANG, 'id:6', '+whois (reply): Return user id.')
-- moderation.lua --
set_text(LANG, 'moderation:0', 18)
set_text(LANG, 'moderation:1', '+add: replying to a message, the user will be added to the current group/supergroup.')
set_text(LANG, 'moderation:2', '+add <id>/<username>: adds a user by its ID/Username to the current group/supergroup.')
set_text(LANG, 'moderation:3', '+kick: replying to a message, the user will be kicked in the current group/supergroup.')
set_text(LANG, 'moderation:4', '+kick <id>/<username>: the user will be kicked by its ID/Username in the current group/supergroup.')
set_text(LANG, 'moderation:5', '+kickme: kick yourself.')
set_text(LANG, 'moderation:6', '+ban: replying to a message, the user will be kicked and banned in the current group/supergroup.')
set_text(LANG, 'moderation:7', '+ban <id>/<username>: the user will be banned by its ID/Username in the current group/supergroup and it wont be able to return.')
set_text(LANG, 'moderation:8', '+unban: replying to a message, the user will be unbanned in the current group/supergroup.')
set_text(LANG, 'moderation:9', '+unban <id>/<username>: the user will be unbanned by its ID/Username in the current group/supergroup.')
set_text(LANG, 'moderation:10', '+gban: replying to a message, the user will be kicked and banned from all groups/supergroups.')
set_text(LANG, 'moderation:11', '+gban <id>/<username>: the user will be banned by its ID/Username from all groups/supergroups and it wont be able to enter.')
set_text(LANG, 'moderation:12', '+ungban: replying to a message, the user will be unbanned from all groups/supergroups.')
set_text(LANG, 'moderation:13', '+ungban <id>/<username>: the user will be unbanned by its ID/Username from all groups/supergroups.')
set_text(LANG, 'moderation:14', '+mute: replying to a message, the user will be silenced in the current supergroup, erasing all its messages.')
set_text(LANG, 'moderation:15', '+mute <id>/<username>: the user will be silenced by its ID/Username inthe current supergroup, erasing all its messages.')
set_text(LANG, 'moderation:16', '+unmute: replying to a message, the user will be unsilenced in the current supergroup.')
set_text(LANG, 'moderation:17', '+unmute <id>/<username>: the user will be unsilenced by its ID/Username in the current supergroup.')
set_text(LANG, 'moderation:18', '+rem: replying to a message, the message will be removed.')
-- settings.lua --
set_text(LANG, 'settings:0', 20)
set_text(LANG, 'settings:1', '+settings stickers enable/disable: when disabled, all stickers will be cleared.')
set_text(LANG, 'settings:2', '+settings links enable/disable: when disabled, all links will be cleared.')
set_text(LANG, 'settings:3', '+settings arabic enable/disabl: when disabled, all messages with arabic/persian will be cleared.')
set_text(LANG, 'settings:4', '+settings bots enable/disable: when disabled, if someone adds a bot, it will be kicked.')
set_text(LANG, 'settings:5', '+settings gifs enable/disable: when disabled, all gifs will be cleared.')
set_text(LANG, 'settings:6', '+settings photos enable/disable: when disabled, all photos will be cleared.')
set_text(LANG, 'settings:7', '+settings audios enable/disable: when disabled, all audios will be cleared.')
set_text(LANG, 'settings:8', '+settings kickme enable/disable: when disabled, people can kick out itself.')
set_text(LANG, 'settings:9', '+settings spam enable/disable: when disabled, all spam links will be cleared.')
set_text(LANG, 'settings:10', '+settings setphoto enable/disable: when enabled, if a user changes the group photo, the bot will revert to the saved photo.')
set_text(LANG, 'settings:11', '+settings setname enable/disable: when enabled, if a user changes the group name, the bot will revert to the saved name.')
set_text(LANG, 'settings:12', '+settings lockmember enable/disable: when enabled, the bot will kick all people that enters to the group.')
set_text(LANG, 'settings:13', '+settings floodtime <secs>: set the time that bot uses to check flood.')
set_text(LANG, 'settings:14', '+settings maxflood <msgs>: set the maximum messages in a floodtime to be considered as flood.')
set_text(LANG, 'settings:15', '+setname <group title>: the bot will change group title.')
set_text(LANG, 'settings:16', '+setphoto <then send photo>: the bot will change group photo.')
set_text(LANG, 'settings:17', '+lang <language (en, es...)>: it changes the language of the bot.')
set_text(LANG, 'settings:18', '+setlink <link>: saves the link of the group.')
set_text(LANG, 'settings:19', '+link: to get the link of the group.')
set_text(LANG, 'settings:20', '+settings tgservices enable/disable: when disabled, new user participant message will be erased.')
-- plugins.lua --
set_text(LANG, 'plugins:0', 4)
set_text(LANG, 'plugins:1', '#plugins: shows a list of all plugins.')
set_text(LANG, 'plugins:2', '#plugins <enable>/<disable> [plugin]: enable/disable the specified plugin.')
set_text(LANG, 'plugins:3', '#plugins <enable>/<disable> [plugin] chat: enable/disable the specified plugin, only in the current group/supergroup.')
set_text(LANG, 'plugins:4', '#plugins reload: reloads all plugins.')
-- version.lua --
set_text(LANG, 'version:0', 1)
set_text(LANG, 'version:1', '+version: shows bot version.')
-- rules.lua --
set_text(LANG, 'rules:0', 1)
set_text(LANG, 'rules:1', '+rules: shows channel rules.')
if matches[1] == 'install' then
return 'ℹ️ English was successfully installed on your bot.'
elseif matches[1] == 'update' then
return 'ℹ️ English was successfully updated on your bot.'
end
else
return "🚫 This plugin requires sudo privileged user."
end
end
return {
patterns = {
'[!/#](install) (english_lang)$',
'[!/#](update) (english_lang)$'
},
run = run
}
| gpl-2.0 |
Beagle/wesnoth | data/ai/micro_ais/cas/ca_messenger_f_next_waypoint.lua | 25 | 2603 | local H = wesnoth.require "lua/helper.lua"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua"
return function(cfg)
-- Calculate next waypoint and rating for all messengers
-- Return next messenger to move and waypoint toward which it should move
-- Also return the array of all messengers (for escort move evaluation,
-- so that it only needs to be done in one place, in case the syntax is changed some more)
-- Returns nil for first 3 arguments if no messenger has moves left
-- Returns nil for all arguments if there are no messengers on the map
local filter = cfg.filter or { id = cfg.id }
local messengers = wesnoth.get_units { side = wesnoth.current.side, { "and", filter } }
if (not messengers[1]) then return end
local waypoint_x = AH.split(cfg.waypoint_x, ",")
local waypoint_y = AH.split(cfg.waypoint_y, ",")
for i,_ in ipairs(waypoint_x) do
waypoint_x[i] = tonumber(waypoint_x[i])
waypoint_y[i] = tonumber(waypoint_y[i])
end
-- Set the next waypoint for all messengers
-- Also find those with MP left and return the one to next move, together with the WP to move toward
local max_rating, best_messenger, x, y = -9e99
for _,messenger in ipairs(messengers) do
-- To avoid code duplication and ensure consistency, we store some pieces of
-- information in the messenger units, even though it could be calculated each time it is needed
local wp_i = MAIUV.get_mai_unit_variables(messenger, cfg.ai_id, "wp_i") or 1
local wp_x, wp_y = waypoint_x[wp_i], waypoint_y[wp_i]
-- If this messenger is within 3 hexes of the next waypoint, we go on to the one after that
-- except if it's the last one
local dist_wp = H.distance_between(messenger.x, messenger.y, wp_x, wp_y)
if (dist_wp <= 3) and (wp_i < #waypoint_x) then wp_i = wp_i + 1 end
-- Also store the rating for each messenger
-- For now, this is simply a "forward rating"
local rating = wp_i - dist_wp / 1000.
-- If invert_order= key is set, we want to move the rearmost messenger first.
if cfg.invert_order then rating = - rating end
MAIUV.set_mai_unit_variables(messenger, cfg.ai_id, { wp_i = wp_i, wp_x = wp_x, wp_y = wp_y, wp_rating = rating })
if (messenger.moves > 0) and (rating > max_rating) then
best_messenger, max_rating = messenger, rating
x, y = wp_x, wp_y
end
end
return best_messenger, x, y, messengers
end
| gpl-2.0 |
liruqi/bigfoot | Interface/AddOns/DBM-Core/DBM-Core.lua | 1 | 454185 | -- *********************************************************
-- ** Deadly Boss Mods - Core **
-- ** http://www.deadlybossmods.com **
-- ** https://www.patreon.com/deadlybossmods **
-- *********************************************************
--
-- This addon is written and copyrighted by:
-- * Paul Emmerich (Tandanu @ EU-Aegwynn) (DBM-Core)
-- * Martin Verges (Nitram @ EU-Azshara) (DBM-GUI)
-- * Adam Williams (Omegal @ US-Whisperwind) (Primary boss mod author & DBM maintainer)
--
-- The localizations are written by:
-- * enGB/enUS: Omegal Twitter @MysticalOS
-- * deDE: Ebmor http://www.deadlybossmods.com/forum/memberlist.php?mode=viewprofile&u=79
-- * ruRU: TOM_RUS http://www.curseforge.com/profiles/TOM_RUS/
-- * zhTW: Whyv ultrashining@gmail.com
-- * koKR: nBlueWiz everfinale@gmail.com
-- * zhCN: Mini Dragon projecteurs@gmail.com
--
--
-- Special thanks to:
-- * Arta
-- * Tennberg (a lot of fixes in the enGB/enUS localization)
-- * nBlueWiz (a lot of fixes in the koKR localization as well as boss mod work) Contact: everfinale@gmail.com
--
--
-- The code of this addon is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License. (see license.txt)
-- All included textures and sounds are copyrighted by their respective owners, license information for these media files can be found in the modules that make use of them.
--
--
-- You are free:
-- * to Share - to copy, distribute, display, and perform the work
-- * to Remix - to make derivative works
-- Under the following conditions:
-- * Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). (A link to http://www.deadlybossmods.com is sufficient)
-- * Noncommercial. You may not use this work for commercial purposes.
-- * Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.
--
-------------------------------
-- Globals/Default Options --
-------------------------------
DBM = {
Revision = tonumber(("$Revision: 17579 $"):sub(12, -3)),
DisplayVersion = "7.3.31 alpha", -- the string that is shown as version
ReleaseRevision = 17510 -- the revision of the latest stable version that is available
}
DBM.HighestRelease = DBM.ReleaseRevision --Updated if newer version is detected, used by update nags to reflect critical fixes user is missing on boss pulls
-- support for git svn which doesn't support svn keyword expansion
-- just use the latest release revision
if not DBM.Revision then
DBM.Revision = DBM.ReleaseRevision
end
local wowVersionString, _, _, wowTOC = GetBuildInfo()
local testBuild = false
if IsTestBuild() then
testBuild = true
end
-- dual profile setup
local _, playerClass = UnitClass("player")
DBM_UseDualProfile = true
if playerClass == "MAGE" or playerClass == "WARLOCK" and playerClass == "ROGUE" then
DBM_UseDualProfile = false
end
DBM_CharSavedRevision = 2
--Hard code STANDARD_TEXT_FONT since skinning mods like to taint it (or worse, set it to nil, wtf?)
local standardFont = STANDARD_TEXT_FONT
if (LOCALE_koKR) then
standardFont = "Fonts\\2002.TTF"
elseif (LOCALE_zhCN) then
standardFont = "Fonts\\ARKai_T.ttf"
elseif (LOCALE_zhTW) then
standardFont = "Fonts\\blei00d.TTF"
elseif (LOCALE_ruRU) then
standardFont = "Fonts\\FRIZQT___CYR.TTF"
else
standardFont = "Fonts\\FRIZQT__.TTF"
end
DBM.DefaultOptions = {
WarningColors = {
{r = 0.41, g = 0.80, b = 0.94}, -- Color 1 - #69CCF0 - Turqoise
{r = 0.95, g = 0.95, b = 0.00}, -- Color 2 - #F2F200 - Yellow
{r = 1.00, g = 0.50, b = 0.00}, -- Color 3 - #FF8000 - Orange
{r = 1.00, g = 0.10, b = 0.10}, -- Color 4 - #FF1A1A - Red
},
RaidWarningSound = "Sound\\Doodad\\BellTollNightElf.ogg",
SpecialWarningSound = "Sound\\Spells\\PVPFlagTaken.ogg",
SpecialWarningSound2 = "Sound\\Creature\\AlgalonTheObserver\\UR_Algalon_BHole01.ogg",
SpecialWarningSound3 = "Interface\\AddOns\\DBM-Core\\sounds\\AirHorn.ogg",
SpecialWarningSound4 = "Sound\\Creature\\HoodWolf\\HoodWolfTransformPlayer01.ogg",
SpecialWarningSound5 = "Sound\\Creature\\Loathstare\\Loa_Naxx_Aggro02.ogg",
ModelSoundValue = "Short",
CountdownVoice = "VP:Yike", --bf@178.com
CountdownVoice2 = "VP:Yike", --bf@178.com
CountdownVoice3v2 = "VP:Yike", --bf@178.com
ChosenVoicePack = "Yike", --bf@178.com
VoiceOverSpecW2 = "DefaultOnly",
AlwaysPlayVoice = false,
EventSoundVictory2 = "None",
EventSoundWipe = "None",
EventSoundEngage = "",
EventSoundMusic = "None",
EventSoundDungeonBGM = "None",
EventSoundMusicCombined = false,
EventDungMusicMythicFilter = true,
EventMusicMythicFilter = true,
Enabled = true,
ShowWarningsInChat = true,
ShowSWarningsInChat = true,
WarningIconLeft = true,
WarningIconRight = true,
WarningIconChat = true,
WarningAlphabetical = true,
StripServerName = true,
ShowAllVersions = false, --bf@178.com
ShowPizzaMessage = true,
ShowEngageMessage = true,
ShowDefeatMessage = true,
ShowGuildMessages = true,
ShowGuildMessagesPlus = false,
AutoRespond = true,
StatusEnabled = true,
WhisperStats = false,
DisableStatusWhisper = false,
DisableGuildStatus = false,
HideBossEmoteFrame2 = true,
ShowMinimapButton = true, --bf@178.com
ShowFlashFrame = true,
SWarningAlphabetical = true,
SWarnNameInNote = true,
CustomSounds = 0,
ShowBigBrotherOnCombatStart = false,
FilterTankSpec = true,
FilterInterrupt2 = "TandFandBossCooldown",
FilterInterruptNoteName = false,
FilterDispel = true,
--FilterSelfHud = true,
AutologBosses = false,
AdvancedAutologBosses = false,
LogOnlyRaidBosses = false,
UseSoundChannel = "Master",
LFDEnhance = true,
WorldBossNearAlert = false,
RLReadyCheckSound = true,
AFKHealthWarning = false,
AutoReplySound = true,
HideObjectivesFrame = true,
HideGarrisonToasts = true,
HideGuildChallengeUpdates = true,
HideQuestTooltips = true,
HideTooltips = false,
DisableSFX = false,
EnableModels = true,
RangeFrameFrames = "radar",
RangeFrameUpdates = "Average",
RangeFramePoint = "CENTER",
RangeFrameX = 50,
RangeFrameY = -50,
RangeFrameSound1 = "none",
RangeFrameSound2 = "none",
RangeFrameLocked = false,
RangeFrameRadarPoint = "CENTER",
RangeFrameRadarX = 100,
RangeFrameRadarY = -100,
InfoFramePoint = "CENTER",
InfoFrameX = 75,
InfoFrameY = -75,
InfoFrameShowSelf = false,
InfoFrameLines = 0,
WarningDuration2 = 1.5,
WarningPoint = "CENTER",
WarningX = 0,
WarningY = 260,
WarningFont = standardFont,
WarningFontSize = 20,
WarningFontStyle = "None",
WarningFontShadow = true,
SpecialWarningDuration2 = 1.5,
SpecialWarningPoint = "CENTER",
SpecialWarningX = 0,
SpecialWarningY = 75,
SpecialWarningFont = standardFont,
SpecialWarningFontSize2 = 35,
SpecialWarningFontStyle = "THICKOUTLINE",
SpecialWarningFontShadow = false,
SpecialWarningIcon = true,
SpecialWarningFontCol = {1.0, 0.7, 0.0},--Yellow, with a tint of orange
SpecialWarningFlashCol1 = {1.0, 1.0, 0.0},--Yellow
SpecialWarningFlashCol2 = {1.0, 0.5, 0.0},--Orange
SpecialWarningFlashCol3 = {1.0, 0.0, 0.0},--Red
SpecialWarningFlashCol4 = {1.0, 0.0, 1.0},--Purple
SpecialWarningFlashCol5 = {0.2, 1.0, 1.0},--Tealish
SpecialWarningFlashDura1 = 0.4,
SpecialWarningFlashDura2 = 0.4,
SpecialWarningFlashDura3 = 1,
SpecialWarningFlashDura4 = 0.7,
SpecialWarningFlashDura5 = 1,
SpecialWarningFlashAlph1 = 0.3,
SpecialWarningFlashAlph2 = 0.3,
SpecialWarningFlashAlph3 = 0.4,
SpecialWarningFlashAlph4 = 0.4,
SpecialWarningFlashAlph5 = 0.5,
SpecialWarningFlashRepeat1 = false,
SpecialWarningFlashRepeat2 = false,
SpecialWarningFlashRepeat3 = true,
SpecialWarningFlashRepeat4 = false,
SpecialWarningFlashRepeat5 = true,
SpecialWarningFlashRepeatAmount = 2,--Repeat 2 times, mean 3 flashes (first plus 2 repeat)
SWarnClassColor = true,
ArrowPosX = 0,
ArrowPosY = -150,
ArrowPoint = "TOP",
-- global boss mod settings (overrides mod-specific settings for some options)
DontShowBossAnnounces = false,
DontShowTargetAnnouncements = true,
DontShowSpecialWarnings = false,
DontShowSpecialWarningText = false,
DontShowBossTimers = false,
DontShowUserTimers = false,
DontShowFarWarnings = true,
DontSetIcons = false,
DontRestoreIcons = false,
DontShowRangeFrame = false,
DontRestoreRange = false,
DontShowInfoFrame = false,
DontShowHudMap2 = false,
DontShowNameplateIcons = false,
DontPlayCountdowns = false,
DontSendYells = false,
BlockNoteShare = false,
DontShowReminders = false,
DontShowPT2 = false,
DontShowPTCountdownText = false,
DontPlayPTCountdown = false,
DontShowPTText = false,
DontShowPTNoID = false,
PTCountThreshold = 5,
LatencyThreshold = 250,
BigBrotherAnnounceToRaid = false,
SettingsMessageShown = false,
ForumsMessageShown = false,
AlwaysShowSpeedKillTimer2 = false,
ShowRespawn = true,
ShowQueuePop = true,
HelpMessageVersion = 3,
MoviesSeen = {},
MovieFilter = "AfterFirst",
LastRevision = 0,
DebugMode = false,
DebugLevel = 1,
RoleSpecAlert = true,
CheckGear = true,
WorldBossAlert = false,
AutoAcceptFriendInvite = false,
AutoAcceptGuildInvite = false,
FakeBWVersion = false,
AITimer = true,
AutoCorrectTimer = false,
ShortTimerText = true,
ChatFrame = "DEFAULT_CHAT_FRAME",
CoreSavedRevision = 1,
}
DBM.Bars = DBT:New()
DBM.Mods = {}
DBM.ModLists = {}
DBM.Counts = {
{ text = "Moshne (Male)", value = "Mosh", path = "Interface\\AddOns\\DBM-Core\\Sounds\\Mosh\\", max = 5},
{ text = "Corsica (Female)",value = "Corsica", path = "Interface\\AddOns\\DBM-Core\\Sounds\\Corsica\\", max = 10},
{ text = "Koltrane (Male)",value = "Kolt", path = "Interface\\AddOns\\DBM-Core\\Sounds\\Kolt\\", max = 10},
{ text = "Pewsey (Male)",value = "Pewsey", path = "Interface\\AddOns\\DBM-Core\\Sounds\\Pewsey\\", max = 10},
{ text = "Bear (Male Child)",value = "Bear", path = "Interface\\AddOns\\DBM-Core\\Sounds\\Bear\\", max = 10},
{ text = "Anshlun (ptBR Male)",value = "Anshlun", path = "Interface\\AddOns\\DBM-Core\\Sounds\\Anshlun\\", max = 10},
{ text = "Neryssa (ptBR Female)",value = "Neryssa", path = "Interface\\AddOns\\DBM-Core\\Sounds\\Neryssa\\", max = 10},
}
DBM.Victory = {
{text = "None",value = "None"},
{text = "Random",value = "Random"},
{text = "Blakbyrd: FF Fanfare",value = "Interface\\AddOns\\DBM-Core\\sounds\\Victory\\bbvictory.ogg", length=4},
{text = "SMG: FF Fanfare",value = "Interface\\AddOns\\DBM-Core\\sounds\\Victory\\SmoothMcGroove_Fanfare.ogg", length=4},
}
DBM.Defeat = {
{text = "None",value = "None"},
{text = "Random",value = "Random"},
{text = "Kologarn: You Fail",value = "Sound\\Creature\\Kologarn\\UR_Kologarn_Slay02.ogg", length=4},
{text = "Alizabal: Incompetent Raiders",value = "Sound\\Creature\\ALIZABAL\\VO_BH_ALIZABAL_RESET_01.ogg", length=4},
{text = "Hodir: Tragic",value = "Sound\\Creature\\Hodir\\UR_Hodir_Slay01.ogg", length=4},
{text = "Thorim: Failures",value = "Sound\\Creature\\Thorim\\UR_Thorim_P1Wipe01.ogg", length=4},
{text = "Valithria: Failures",value = "Sound\\Creature\\ValithriaDreamwalker\\IC_Valithria_Berserk01.ogg", length=4},
}
DBM.Music = {--Contains all music media, period
{text = "None",value = "None"},
{text = "Random",value = "Random"},
{text = "Anduin Part 1 B",value = "sound\\music\\Legion\\MUS_70_AnduinPt1_B.mp3", length=140},
{text = "Anduin Part 2 B",value = "sound\\music\\Legion\\MUS_70_AnduinPt2_B.mp3", length=111},
{text = "Bronze Jam",value = "Sound\\Music\\ZoneMusic\\IcecrownRaid\\IR_BronzeJam.mp3", length=116},
{text = "Invincible",value = "Sound\\Music\\Draenor\\MUS_Invincible.mp3", length=197},
{text = "Nightsong",value = "Sound\\Music\\cataclysm\\MUS_NightElves_GU01.mp3", length=160},
{text = "Ulduar: Titan Orchestra",value = "Sound\\Music\\ZoneMusic\\UlduarRaidInt\\UR_TitanOrchestraIntro.mp3", length=102},
}
DBM.DungeonMusic = {--Filtered list of media assigned to dungeon/raid background music catagory
{text = "None",value = "None"},
{text = "Random",value = "Random"},
{text = "Anduin Part 1 B",value = "sound\\music\\Legion\\MUS_70_AnduinPt1_B.mp3", length=140},
{text = "Nightsong",value = "Sound\\Music\\cataclysm\\MUS_NightElves_GU01.mp3", length=160},
{text = "Ulduar: Titan Orchestra",value = "Sound\\Music\\ZoneMusic\\UlduarRaidInt\\UR_TitanOrchestraIntro.mp3", length=102},
}
DBM.BattleMusic = {--Filtered list of media assigned to boss/encounter background music catagory
{text = "None",value = "None"},
{text = "Random",value = "Random"},
{text = "Anduin Part 2 B",value = "sound\\music\\Legion\\MUS_70_AnduinPt2_B.mp3", length=111},
{text = "Bronze Jam",value = "Sound\\Music\\ZoneMusic\\IcecrownRaid\\IR_BronzeJam.mp3", length=116},
{text = "Invincible",value = "Sound\\Music\\Draenor\\MUS_Invincible.mp3", length=197},
}
------------------------
-- Global Identifiers --
------------------------
DBM_DISABLE_ZONE_DETECTION = newproxy(false)
DBM_OPTION_SPACER = newproxy(false)
--------------
-- Locals --
--------------
local bossModPrototype = {}
local usedProfile = "Default"
local dbmIsEnabled = true
local lastCombatStarted = GetTime()
local loadcIds = {}
local inCombat = {}
local oocBWComms = {}
local combatInfo = {}
local bossIds = {}
local updateFunctions = {}
local raid = {}
local modSyncSpam = {}
local autoRespondSpam = {}
local chatPrefix = "<Deadly Boss Mods> "
local chatPrefixShort = "<DBM> "
local ver = ("%s (r%d)"):format(DBM.DisplayVersion, DBM.Revision)
local mainFrame = CreateFrame("Frame", "DBMMainFrame")
local newerVersionPerson = {}
local newerRevisionPerson = {}
local combatInitialized = false
local healthCombatInitialized = false
local pformat
local schedulerFrame = CreateFrame("Frame", "DBMScheduler")
schedulerFrame:Hide()
local startScheduler
local schedule
local unschedule
local unscheduleAll
local scheduleCountdown
local loadOptions
local checkWipe
local checkBossHealth
local checkCustomBossHealth
local fireEvent
local playerName = UnitName("player")
local playerLevel = UnitLevel("player")
local playerRealm = GetRealmName()
local connectedServers = GetAutoCompleteRealms()
local LastInstanceMapID = -1
local LastGroupSize = 0
local LastInstanceType = nil
local queuedBattlefield = {}
local noDelay = true
local watchFrameRestore = false
local bossHealth = {}
local bossHealthuIdCache = {}
local bossuIdCache = {}
local savedDifficulty, difficultyText, difficultyIndex, difficultyModifier
local lastBossEngage = {}
local lastBossDefeat = {}
local bossuIdFound = false
local timerRequestInProgress = false
local updateNotificationDisplayed = 0
local showConstantReminder = 0
local tooltipsHidden = false
local SWFilterDisabed = 3
local currentSpecID, currentSpecName, currentSpecGroup
local cSyncSender = {}
local cSyncReceived = 0
local eeSyncSender = {}
local eeSyncReceived = 0
local canSetIcons = {}
local iconSetRevision = {}
local iconSetPerson = {}
local addsGUIDs = {}
local targetEventsRegistered = false
local targetMonitor = nil
local statusWhisperDisabled = false
local statusGuildDisabled = false
local dbmToc = 0
local UpdateChestTimer
local breakTimerStart
local AddMsg
local delayedFunction
local fakeBWVersion, fakeBWHash = 97, "10064f7"
local versionQueryString, versionResponseString = "Q^%d^%s", "V^%d^%s"
local enableIcons = true -- set to false when a raid leader or a promoted player has a newer version of DBM
local bannedMods = { -- a list of "banned" (meaning they are replaced by another mod or discontinued). These mods will not be loaded by DBM (and they wont show up in the GUI)
"DBM-Battlegrounds", --replaced by DBM-PvP
-- ZG and ZA are now part of the party mods for Cataclysm
"DBM-ZulAman",--Remove restriction in 8.0 classic wow
"DBM-ZG",--Remove restriction in 8.0 classic wow
"DBM-SiegeOfOrgrimmar",--Block legacy version. New version is "DBM-SiegeOfOrgrimmarV2"
"DBM-HighMail",
"DBM-ProvingGrounds-MoP",--Renamed to DBM-ProvingGrounds in 6.0 version since blizzard updated content for WoD
"DBM-ProvingGrounds",--Renamed to DBM-Challenges going forward to include proving grounds and any new single player challendges of similar design such as mage tower artifact quests
"DBM-VPKiwiBeta",--Renamed to DBM-VPKiwi in final version.
"DBM-Suramar",--Renamed to DBM-Nighthold
-- "DBM-PvP",--Discontinued do to inability to maintain such large scale external projects with limitted time/resources
}
-----------------
-- Libraries --
-----------------
local LL
if LibStub("LibLatency", true) then
LL = LibStub("LibLatency")
end
local LD
if LibStub("LibDurability", true) then
LD = LibStub("LibDurability")
end
--------------------------------------------------------
-- Cache frequently used global variables in locals --
--------------------------------------------------------
local DBM = DBM
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
local ipairs, pairs, next = ipairs, pairs, next
local tinsert, tremove, twipe, tsort, tconcat = table.insert, table.remove, table.wipe, table.sort, table.concat
local type, select = type, select
local GetTime = GetTime
local bband = bit.band
local floor, mhuge, mmin, mmax = math.floor, math.huge, math.min, math.max
local GetNumGroupMembers, GetRaidRosterInfo = GetNumGroupMembers, GetRaidRosterInfo
local UnitName, GetUnitName = UnitName, GetUnitName
local IsInRaid, IsInGroup, IsInInstance = IsInRaid, IsInGroup, IsInInstance
local UnitAffectingCombat, InCombatLockdown, IsFalling, IsEncounterInProgress, UnitPlayerOrPetInRaid, UnitPlayerOrPetInParty = UnitAffectingCombat, InCombatLockdown, IsFalling, IsEncounterInProgress, UnitPlayerOrPetInRaid, UnitPlayerOrPetInParty
local UnitGUID, UnitHealth, UnitHealthMax, UnitBuff, UnitDebuff = UnitGUID, UnitHealth, UnitHealthMax, UnitBuff, UnitDebuff
local UnitExists, UnitIsDead, UnitIsFriend, UnitIsUnit = UnitExists, UnitIsDead, UnitIsFriend, UnitIsUnit
local GetSpellInfo, EJ_GetSectionInfo, GetSectionIconFlags, GetSpellTexture, GetSpellCooldown = GetSpellInfo, C_EncounterJournal.GetSectionInfo, C_EncounterJournal.GetSectionIconFlags, GetSpellTexture, GetSpellCooldown
local EJ_GetEncounterInfo, EJ_GetCreatureInfo, GetDungeonInfo = EJ_GetEncounterInfo, EJ_GetCreatureInfo, GetDungeonInfo
local GetInstanceInfo = GetInstanceInfo
local GetCurrentMapDungeonLevel, SetMapToCurrentZone, GetPlayerMapAreaID = GetCurrentMapDungeonLevel, SetMapToCurrentZone, GetPlayerMapAreaID
local GetSpecialization, GetSpecializationInfo, GetSpecializationInfoByID = GetSpecialization, GetSpecializationInfo, GetSpecializationInfoByID
local UnitDetailedThreatSituation = UnitDetailedThreatSituation
local UnitIsGroupLeader, UnitIsGroupAssistant = UnitIsGroupLeader, UnitIsGroupAssistant
local PlaySoundFile, PlaySound = PlaySoundFile, PlaySound
local Ambiguate = Ambiguate
local C_TimerNewTicker, C_TimerAfter = C_Timer.NewTicker, C_Timer.After
--TODO, remove RegisterAddonMessagePrefix upvalue in 8.x, this is only a temp live/beta work around
local RegisterAddonMessagePrefix, SendAddonMessage = RegisterAddonMessagePrefix or C_ChatInfo.RegisterAddonMessagePrefix, SendAddonMessage or C_ChatInfo.SendAddonMessage
-- for Phanx' Class Colors
local RAID_CLASS_COLORS = CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS
---------------------------------
-- General (local) functions --
---------------------------------
-- checks if a given value is in an array
-- returns true if it finds the value, false otherwise
local function checkEntry(t, val)
for i, v in ipairs(t) do
if v == val then
return true
end
end
return false
end
local function findEntry(t, val)
for i, v in ipairs(t) do
if v and val and val:find(v) then
return true
end
end
return false
end
-- removes all occurrences of a value in an array
-- returns true if at least one occurrence was remove, false otherwise
local function removeEntry(t, val)
local existed = false
for i = #t, 1, -1 do
if t[i] == val then
tremove(t, i)
existed = true
end
end
return existed
end
-- automatically sends an addon message to the appropriate channel (INSTANCE_CHAT, RAID or PARTY)
local function sendSync(prefix, msg)
msg = msg or ""
if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and IsInInstance() then--For BGs, LFR and LFG (we also check IsInInstance() so if you're in queue but fighting something outside like a world boss, it'll sync in "RAID" instead)
SendAddonMessage("D4", prefix .. "\t" .. msg, "INSTANCE_CHAT")
else
if IsInRaid() then
SendAddonMessage("D4", prefix .. "\t" .. msg, "RAID")
elseif IsInGroup(LE_PARTY_CATEGORY_HOME) then
SendAddonMessage("D4", prefix .. "\t" .. msg, "PARTY")
else--for solo raid
SendAddonMessage("D4", prefix .. "\t" .. msg, "WHISPER", playerName)
end
end
end
--Custom sync function that should only be used for user generated sync messages
local function sendLoggedSync(prefix, msg)
msg = msg or ""
if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and IsInInstance() then--For BGs, LFR and LFG (we also check IsInInstance() so if you're in queue but fighting something outside like a world boss, it'll sync in "RAID" instead)
C_ChatInfo.SendAddonMessageLogged("D4", prefix .. "\t" .. msg, "INSTANCE_CHAT")
else
if IsInRaid() then
C_ChatInfo.SendAddonMessageLogged("D4", prefix .. "\t" .. msg, "RAID")
elseif IsInGroup(LE_PARTY_CATEGORY_HOME) then
C_ChatInfo.SendAddonMessageLogged("D4", prefix .. "\t" .. msg, "PARTY")
else--for solo raid
C_ChatInfo.SendAddonMessageLogged("D4", prefix .. "\t" .. msg, "WHISPER", playerName)
end
end
end
local function strFromTime(time)
if type(time) ~= "number" then time = 0 end
time = floor(time*100)/100
if time < 60 then
return DBM_CORE_TIMER_FORMAT_SECS:format(time)
elseif time % 60 == 0 then
return DBM_CORE_TIMER_FORMAT_MINS:format(time/60)
else
return DBM_CORE_TIMER_FORMAT:format(time/60, time % 60)
end
end
do
-- fail-safe format, replaces missing arguments with unknown
-- note: doesn't handle cases like %%%s correctly at the moment (should become %unknown, but becomes %%s)
-- also, the end of the format directive is not detected in all cases, but handles everything that occurs in our boss mods ;)
--> not suitable for general-purpose use, just for our warnings and timers (where an argument like a spell-target might be nil due to missing target information from unreliable detection methods)
local function replace(cap1, cap2)
return cap1 == "%" and DBM_CORE_UNKNOWN
end
function pformat(fstr, ...)
local ok, str = pcall(format, fstr, ...)
return ok and str or fstr:gsub("(%%+)([^%%%s<]+)", replace):gsub("%%%%", "%%")
end
end
-- sends a whisper to a player by his or her character name or BNet presence id
-- returns true if the message was sent, nil otherwise
local function sendWhisper(target, msg)
if type(target) == "number" then
if not BNIsSelf(target) then -- never send BNet whispers to ourselves
BNSendWhisper(target, msg)
return true
end
elseif type(target) == "string" then
-- whispering to ourselves here is okay and somewhat useful for whisper-warnings
SendChatMessage(msg, "WHISPER", nil, target)
return true
end
end
local BNSendWhisper = sendWhisper
local function stripServerName(cap)
cap = cap:sub(2, -2)
if DBM.Options.StripServerName then
cap = Ambiguate(cap, "short")
end
return cap
end
--------------
-- Events --
--------------
do
local registeredEvents = {}
local registeredSpellIds = {}
local unfilteredCLEUEvents = {}
local registeredUnitEventIds = {}
local argsMT = {__index = {}}
local args = setmetatable({}, argsMT)
function argsMT.__index:IsSpellID(a1, a2, a3, a4, a5)
local v = self.spellId
return v == a1 or v == a2 or v == a3 or v == a4 or v == a5
end
function argsMT.__index:IsPlayer()
return bband(args.destFlags, COMBATLOG_OBJECT_AFFILIATION_MINE) ~= 0 and bband(args.destFlags, COMBATLOG_OBJECT_TYPE_PLAYER) ~= 0
end
function argsMT.__index:IsPlayerSource()
return bband(args.sourceFlags, COMBATLOG_OBJECT_AFFILIATION_MINE) ~= 0 and bband(args.sourceFlags, COMBATLOG_OBJECT_TYPE_PLAYER) ~= 0
end
function argsMT.__index:IsNPC()
return bband(args.destFlags, COMBATLOG_OBJECT_TYPE_NPC) ~= 0
end
function argsMT.__index:IsPet()
return bband(args.destFlags, COMBATLOG_OBJECT_TYPE_PET) ~= 0
end
function argsMT.__index:IsPetSource()
return bband(args.sourceFlags, COMBATLOG_OBJECT_TYPE_PET) ~= 0
end
function argsMT.__index:IsSrcTypePlayer()
return bband(args.sourceFlags, COMBATLOG_OBJECT_TYPE_PLAYER) ~= 0
end
function argsMT.__index:IsDestTypePlayer()
return bband(args.destFlags, COMBATLOG_OBJECT_TYPE_PLAYER) ~= 0
end
function argsMT.__index:IsSrcTypeHostile()
return bband(args.sourceFlags, COMBATLOG_OBJECT_REACTION_HOSTILE) ~= 0
end
function argsMT.__index:IsDestTypeHostile()
return bband(args.destFlags, COMBATLOG_OBJECT_REACTION_HOSTILE) ~= 0
end
function argsMT.__index:GetSrcCreatureID()
return DBM:GetCIDFromGUID(self.sourceGUID)
end
function argsMT.__index:GetDestCreatureID()
return DBM:GetCIDFromGUID(self.destGUID)
end
local function handleEvent(self, event, ...)
local isUnitEvent = event:sub(0, 5) == "UNIT_" and event ~= "UNIT_DIED" and event ~= "UNIT_DESTROYED"
if self == mainFrame and isUnitEvent then
-- UNIT_* events that come from mainFrame are _UNFILTERED variants and need their suffix
event = event .. "_UNFILTERED"
isUnitEvent = false -- not actually a real unit id for this function...
end
if not registeredEvents[event] or not dbmIsEnabled then return end
for i, v in ipairs(registeredEvents[event]) do
local zones = v.zones
local handler = v[event]
local modEvents = v.registeredUnitEvents
if handler and (not isUnitEvent or not modEvents or modEvents[event .. ...]) and (not zones or zones[LastInstanceMapID]) and not (v.isTrashMod and #inCombat > 0) then
handler(v, ...)
end
end
end
local registerUnitEvent, unregisterUnitEvent, registerSpellId, unregisterSpellId, registerCLEUEvent, unregisterCLEUEvent
do
local frames = {} -- frames that are being used for unit events, one frame per unit id (this could be optimized, as it currently creates a new frame even for a different event, but that's not worth the effort as 90% of all calls are just boss1 anyways)
function registerUnitEvent(mod, event, ...)
mod.registeredUnitEvents = mod.registeredUnitEvents or {}
for i = 1, select("#", ...) do
local uId = select(i, ...)
if not uId then break end
local frame = frames[uId]
if not frame then
frame = CreateFrame("Frame")
if uId == "mouseover" then
-- work-around for mouse-over events (broken!)
frame:SetScript("OnEvent", function(self, event, uId, ...)
-- we registered mouseover events, so we only want mouseover events, thanks.
handleEvent(self, event, "mouseover", ...)
end)
else
frame:SetScript("OnEvent", handleEvent)
end
frames[uId] = frame
end
registeredUnitEventIds[event .. uId] = (registeredUnitEventIds[event .. uId] or 0) + 1
mod.registeredUnitEvents[event .. uId] = true
frame:RegisterUnitEvent(event, uId)
end
end
function unregisterUnitEvent(mod, event, ...)
for i = 1, select("#", ...) do
local uId = select(i, ...)
if not uId then break end
local frame = frames[uId]
local refs = (registeredUnitEventIds[event .. uId] or 1) - 1
registeredUnitEventIds[event .. uId] = refs
if refs <= 0 then
registeredUnitEventIds[event .. uId] = nil
if frame then
frame:UnregisterEvent(event)
end
end
if mod.registeredUnitEvents and mod.registeredUnitEvents[event .. uId] then
mod.registeredUnitEvents[event .. uId] = nil
end
end
for i = #registeredEvents[event], 1, -1 do
if registeredEvents[event][i] == mod then
tremove(registeredEvents[event], i)
end
end
if #registeredEvents[event] == 0 then
registeredEvents[event] = nil
end
end
function registerSpellId(event, spellId)
if type(spellId) == "string" then--Something is screwed up, like SPELL_AURA_APPLIED DOSE
DBM:AddMsg("DBM RegisterEvents Error: "..spellId.." is not a number!")
return
end
if spellId and not DBM:GetSpellInfo(spellId) then
DBM:AddMsg("DBM RegisterEvents Error: "..spellId.." spell id does not exist!")
return
end
if not registeredSpellIds[event] then
registeredSpellIds[event] = {}
end
registeredSpellIds[event][spellId] = (registeredSpellIds[event][spellId] or 0) + 1
end
function unregisterSpellId(event, spellId)
if not registeredSpellIds[event] then return end
local refs = (registeredSpellIds[event][spellId] or 1) - 1
registeredSpellIds[event][spellId] = refs
if refs <= 0 then
registeredSpellIds[event][spellId] = nil
end
end
--There are 2 tables. unfilteredCLEUEvents and registeredSpellIds table.
--unfilteredCLEUEvents saves UNFILTERED cleu event count. this is count table to prevent bad unregister.
--registeredSpellIds tables filtered table. this saves event and spell ids. works smiliar with unfilteredCLEUEvents table.
function registerCLEUEvent(mod, event)
local argTable = {strsplit(" ", event)}
-- filtered cleu event. save information in registeredSpellIds table.
if #argTable > 1 then
event = argTable[1]
for i = 2, #argTable do
registerSpellId(event, tonumber(argTable[i]))
end
-- no args. works as unfiltered. save information in unfilteredCLEUEvents table.
else
unfilteredCLEUEvents[event] = (unfilteredCLEUEvents[event] or 0) + 1
end
registeredEvents[event] = registeredEvents[event] or {}
tinsert(registeredEvents[event], mod)
end
function unregisterCLEUEvent(mod, event)
local argTable = {strsplit(" ", event)}
local eventCleared = false
-- filtered cleu event. save information in registeredSpellIds table.
if #argTable > 1 then
event = argTable[1]
for i = 2, #argTable do
unregisterSpellId(event, tonumber(argTable[i]))
end
local remainingSpellIdCount = 0
if registeredSpellIds[event] then
for i, v in pairs(registeredSpellIds[event]) do
remainingSpellIdCount = remainingSpellIdCount + 1
end
end
if remainingSpellIdCount == 0 then
registeredSpellIds[event] = nil
-- if unfilteredCLEUEvents and registeredSpellIds do not exists, clear registeredEvents.
if not unfilteredCLEUEvents[event] then
eventCleared = true
end
end
-- no args. works as unfiltered. save information in unfilteredCLEUEvents table.
else
local refs = (unfilteredCLEUEvents[event] or 1) - 1
unfilteredCLEUEvents[event] = refs
if refs <= 0 then
unfilteredCLEUEvents[event] = nil
-- if unfilteredCLEUEvents and registeredSpellIds do not exists, clear registeredEvents.
if not registeredSpellIds[event] then
eventCleared = true
end
end
end
for i = #registeredEvents[event], 1, -1 do
if registeredEvents[event][i] == mod then
registeredEvents[event][i] = {}
break
end
end
if eventCleared then
registeredEvents[event] = nil
end
end
end
-- UNIT_* events are special: they can take 'parameters' like this: "UNIT_HEALTH boss1 boss2" which only trigger the event for the given unit ids
function DBM:RegisterEvents(...)
for i = 1, select("#", ...) do
local event = select(i, ...)
-- spell events with special care.
if event:sub(0, 6) == "SPELL_" and event ~= "SPELL_NAME_UPDATE" or event:sub(0, 6) == "RANGE_" or event == "UNIT_DIED" or event == "UNIT_DESTROYED" then
registerCLEUEvent(self, event)
else
local eventWithArgs = event
-- unit events need special care
if event:sub(0, 5) == "UNIT_" then
-- unit events are limited to 8 "parameters", as there is no good reason to ever use more than 5 (it's just that the code old code supported 8 (boss1-5, target, focus))
local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8
event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 = strsplit(" ", event)
if not arg1 and event:sub(event:len() - 10) ~= "_UNFILTERED" then -- no arguments given, support for legacy mods
eventWithArgs = event .. " boss1 boss2 boss3 boss4 boss5 target focus"
event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 = strsplit(" ", eventWithArgs)
end
if event:sub(event:len() - 10) == "_UNFILTERED" then
-- we really want *all* unit ids
mainFrame:RegisterEvent(event:sub(0, -12))
else
registerUnitEvent(self, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
end
-- spell events with filter
else
-- normal events
mainFrame:RegisterEvent(event)
end
registeredEvents[eventWithArgs] = registeredEvents[eventWithArgs] or {}
tinsert(registeredEvents[eventWithArgs], self)
if event ~= eventWithArgs then
registeredEvents[event] = registeredEvents[event] or {}
tinsert(registeredEvents[event], self)
end
end
end
end
local function unregisterUEvent(mod, event)
if event:sub(0, 5) == "UNIT_" and event ~= "UNIT_DIED" and event ~= "UNIT_DESTROYED" then
local event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 = strsplit(" ", event)
if event:sub(event:len() - 10) == "_UNFILTERED" then
mainFrame:UnregisterEvent(event:sub(0, -12))
else
unregisterUnitEvent(mod, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
end
end
end
local function findRealEvent(t, val)
for i, v in ipairs(t) do
local event = strsplit(" ", v)
if event == val then
return v
end
end
end
function DBM:UnregisterInCombatEvents(srmOnly)
for event, mods in pairs(registeredEvents) do
if srmOnly then
local i = 1
while mods[i] do
if mods[i] == self and event == "SPELL_AURA_REMOVED" then
local findEvent = findRealEvent(self.inCombatOnlyEvents, "SPELL_AURA_REMOVED")
if findEvent then
unregisterCLEUEvent(self, findEvent)
break
end
end
i = i +1
end
elseif (event:sub(0, 6) == "SPELL_"and event ~= "SPELL_NAME_UPDATE" or event:sub(0, 6) == "RANGE_") then
local i = 1
while mods[i] do
if mods[i] == self and event ~= "SPELL_AURA_REMOVED" then
local findEvent = findRealEvent(self.inCombatOnlyEvents, event)
if findEvent then
unregisterCLEUEvent(self, findEvent)
break
end
end
i = i +1
end
else
local match = false
for i = #mods, 1, -1 do
if mods[i] == self and checkEntry(self.inCombatOnlyEvents, event) then
tremove(mods, i)
match = true
end
end
if #mods == 0 or (match and event:sub(0, 5) == "UNIT_" and event:sub(0, -10) ~= "_UNFILTERED" and event ~= "UNIT_DIED" and event ~= "UNIT_DESTROYED") then -- unit events have their own reference count
unregisterUEvent(self, event)
end
if #mods == 0 then
registeredEvents[event] = nil
end
end
end
end
function DBM:RegisterShortTermEvents(...)
if self.shortTermEventsRegistered then
return
end
self.shortTermRegisterEvents = {...}
for k, v in pairs(self.shortTermRegisterEvents) do
if v:sub(0, 5) == "UNIT_" and v:sub(v:len() - 10) ~= "_UNFILTERED" and not v:find(" ") and v ~= "UNIT_DIED" and v ~= "UNIT_DESTROYED" then
-- legacy event, oh noes
self.shortTermRegisterEvents[k] = v .. " boss1 boss2 boss3 boss4 boss5 target focus"
end
end
self.shortTermEventsRegistered = 1
self:RegisterEvents(unpack(self.shortTermRegisterEvents))
end
function DBM:UnregisterShortTermEvents()
if self.shortTermRegisterEvents then
for event, mods in pairs(registeredEvents) do
if event:sub(0, 6) == "SPELL_" or event:sub(0, 6) == "RANGE_" then
local i = 1
while mods[i] do
if mods[i] == self then
local findEvent = findRealEvent(self.shortTermRegisterEvents, event)
if findEvent then
unregisterCLEUEvent(self, findEvent)
break
end
end
i = i +1
end
else
local match = false
for i = #mods, 1, -1 do
if mods[i] == self and checkEntry(self.shortTermRegisterEvents, event) then
tremove(mods, i)
match = true
end
end
if #mods == 0 or (match and event:sub(0, 5) == "UNIT_" and event:sub(0, -10) ~= "_UNFILTERED" and event ~= "UNIT_DIED" and event ~= "UNIT_DESTROYED") then
unregisterUEvent(self, event)
end
if #mods == 0 then
registeredEvents[event] = nil
end
end
end
self.shortTermEventsRegistered = nil
self.shortTermRegisterEvents = nil
end
end
DBM:RegisterEvents("ADDON_LOADED")
function DBM:FilterRaidBossEmote(msg, ...)
return handleEvent(nil, "CHAT_MSG_RAID_BOSS_EMOTE_FILTERED", msg:gsub("\124c%x+(.-)\124r", "%1"), ...)
end
local noArgTableEvents = {
SWING_DAMAGE = true,
SWING_MISSED = true,
RANGE_DAMAGE = true,
RANGE_MISSED = true,
SPELL_DAMAGE = true,
SPELL_BUILDING_DAMAGE = true,
SPELL_MISSED = true,
SPELL_ABSORBED = true,
SPELL_HEAL = true,
SPELL_ENERGIZE = true,
SPELL_PERIODIC_ENERGIZE = true,
SPELL_PERIODIC_MISSED = true,
SPELL_PERIODIC_DAMAGE = true,
SPELL_PERIODIC_DRAIN = true,
SPELL_PERIODIC_LEECH = true,
SPELL_PERIODIC_ENERGIZE = true,
SPELL_DRAIN = true,
SPELL_LEECH = true,
SPELL_CAST_FAILED = true
}
function DBM:COMBAT_LOG_EVENT_UNFILTERED(timestamp, event, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, extraArg1, extraArg2, extraArg3, extraArg4, extraArg5, extraArg6, extraArg7, extraArg8, extraArg9, extraArg10, ...)
if wowTOC == 80000 then--In 8.x+, CLEU is just an event with no args, all args must be requested via CombatLogGetCurrentEventInfo
timestamp, event, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, extraArg1, extraArg2, extraArg3, extraArg4, extraArg5, extraArg6, extraArg7, extraArg8, extraArg9, extraArg10 = CombatLogGetCurrentEventInfo()
end
if not registeredEvents[event] then return end
local eventSub6 = event:sub(0, 6)
if (eventSub6 == "SPELL_" or eventSub6 == "RANGE_") and not unfilteredCLEUEvents[event] and registeredSpellIds[event] then
if not registeredSpellIds[event][extraArg1] then return end
end
-- process some high volume events without building the whole table which is somewhat faster
-- this prevents work-around with mods that used to have their own event handler to prevent this overhead
if noArgTableEvents[event] then
return handleEvent(nil, event, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, extraArg1, extraArg2, extraArg3, extraArg4, extraArg5, extraArg6, extraArg7, extraArg8, extraArg9, extraArg10, ...)
else
twipe(args)
args.timestamp = timestamp
args.event = event
args.sourceGUID = sourceGUID
args.sourceName = sourceName
args.sourceFlags = sourceFlags
args.sourceRaidFlags = sourceRaidFlags
args.destGUID = destGUID
args.destName = destName
args.destFlags = destFlags
args.destRaidFlags = destRaidFlags
if eventSub6 == "SPELL_" then
args.spellId, args.spellName = extraArg1, extraArg2
if event == "SPELL_AURA_APPLIED" or event == "SPELL_AURA_REFRESH" or event == "SPELL_AURA_REMOVED" then
if not args.sourceName then
args.sourceName = args.destName
args.sourceGUID = args.destGUID
args.sourceFlags = args.destFlags
end
elseif event == "SPELL_AURA_APPLIED_DOSE" or event == "SPELL_AURA_REMOVED_DOSE" then
args.amount = extraArg5
if not args.sourceName then
args.sourceName = args.destName
args.sourceGUID = args.destGUID
args.sourceFlags = args.destFlags
end
elseif event == "SPELL_INTERRUPT" or event == "SPELL_DISPEL" or event == "SPELL_DISPEL_FAILED" or event == "SPELL_AURA_STOLEN" then
args.extraSpellId, args.extraSpellName = extraArg4, extraArg5
end
elseif event == "UNIT_DIED" or event == "UNIT_DESTROYED" then
args.sourceName = args.destName
args.sourceGUID = args.destGUID
args.sourceFlags = args.destFlags
elseif event == "ENVIRONMENTAL_DAMAGE" then
args.environmentalType, args.amount, args.overkill, args.school, args.resisted, args.blocked, args.absorbed, args.critical, args.glancing, args.crushing = extraArg1, extraArg2, extraArg3, extraArg4, extraArg5, extraArg6, extraArg7, extraArg8, extraArg9, extraArg10
end
return handleEvent(nil, event, args)
end
end
mainFrame:SetScript("OnEvent", handleEvent)
end
--------------
-- OnLoad --
--------------
do
local isLoaded = false
local onLoadCallbacks = {}
local disabledMods = {}
local function runDelayedFunctions(self)
noDelay = false
--Check if voice pack missing
local activeVP = self.Options.ChosenVoicePack
if activeVP ~= "None" then
if not self.VoiceVersions[activeVP] or (self.VoiceVersions[activeVP] and self.VoiceVersions[activeVP] == 0) then--A voice pack is selected that does not belong
self.Options.ChosenVoicePack = "None"--Set ChosenVoicePack back to None
AddMsg(DBM, DBM_CORE_VOICE_MISSING)
end
else
if not self.Options.DontShowReminders and #self.Voices > 1 then
--At least one voice pack installed but activeVP set to "None"
AddMsg(DBM, DBM_CORE_VOICE_DISABLED)
end
end
--Check if any of countdown sounds are using missing voice pack
local voice1 = self.Options.CountdownVoice
local voice2 = self.Options.CountdownVoice2
local voice3 = self.Options.CountdownVoice3v2
if voice1 == "None" then--Migrate to new setting
self.Options.CountdownVoice = self.DefaultOptions.CountdownVoice
self.Options.DontPlayCountdowns = true
end
if voice3 == "HoTS_R" and select(4, GetAddOnInfo("DBM-CountPack-HoTS")) then
--Heroes count pack already installed, migrate user setting instead of forcing pewsey voice
self.Options.CountdownVoice3v2 = "HoTS_Ravenlord"
end
local found1, found2, found3 = false, false, false
for i = 1, #self.Counts do
local voice = self.Counts[i].value
if voice == self.Options.CountdownVoice then
found1 = true
end
if voice == self.Options.CountdownVoice2 then
found2 = true
end
if voice == self.Options.CountdownVoice3v2 then
found3 = true
end
end
if not found1 then
AddMsg(DBM, DBM_CORE_VOICE_COUNT_MISSING:format(1, self.DefaultOptions.CountdownVoice))
self.Options.CountdownVoice = self.DefaultOptions.CountdownVoice
end
if not found2 then
AddMsg(DBM, DBM_CORE_VOICE_COUNT_MISSING:format(2, self.DefaultOptions.CountdownVoice2))
self.Options.CountdownVoice2 = self.DefaultOptions.CountdownVoice2
end
if not found3 then
AddMsg(DBM, DBM_CORE_VOICE_COUNT_MISSING:format(3, self.DefaultOptions.CountdownVoice3v2))
self.Options.CountdownVoice3v2 = self.DefaultOptions.CountdownVoice3v2
end
self:BuildVoiceCountdownCache()
--Break timer recovery
--Try local settings
if self.Options.tempBreak2 then
local timer, startTime = string.split("/", self.Options.tempBreak2)
local elapsed = time() - tonumber(startTime)
local remaining = timer - elapsed
if remaining > 0 then
breakTimerStart(DBM, remaining, playerName)
else--It must have ended while we were offline, kill variable.
self.Options.tempBreak2 = nil
end
end
if IsInGuild() then
SendAddonMessage("D4", "GH", "GUILD")
end
if not savedDifficulty or not difficultyText or not difficultyIndex then--prevent error if savedDifficulty or difficultyText is nil
savedDifficulty, difficultyText, difficultyIndex, LastGroupSize, difficultyModifier = self:GetCurrentInstanceDifficulty()
end
end
-- register a callback that will be executed once the addon is fully loaded (ADDON_LOADED fired, saved vars are available)
function DBM:RegisterOnLoadCallback(cb)
if isLoaded then
cb()
else
onLoadCallbacks[#onLoadCallbacks + 1] = cb
end
end
function DBM:ADDON_LOADED(modname)
if modname == "DBM-Core" and not isLoaded then
dbmToc = tonumber(GetAddOnMetadata("DBM-Core", "X-Min-Interface"))
isLoaded = true
for i, v in ipairs(onLoadCallbacks) do
xpcall(v, geterrorhandler())
end
onLoadCallbacks = nil
loadOptions(self)
if GetAddOnEnableState(playerName, "VEM-Core") >= 1 then
self:Disable(true)
C_TimerAfter(15, function() AddMsg(self, DBM_CORE_VEM) end)
return
end
if GetAddOnEnableState(playerName, "DBM-Profiles") >= 1 then
self:Disable(true)
C_TimerAfter(15, function() AddMsg(self, DBM_CORE_3RDPROFILES) end)
return
end
if GetAddOnEnableState(playerName, "DPMCore") >= 1 then
self:Disable(true)
C_TimerAfter(15, function() AddMsg(self, DBM_CORE_DPMCORE) end)
return
end
self.Bars:LoadOptions("DBM")
self.Arrow:LoadPosition()
if not self.Options.ShowMinimapButton then self:HideMinimapButton() end
--[[local soundChannels = tonumber(GetCVar("Sound_NumChannels")) or 24--if set to 24, may return nil, Defaults usually do
--If this messes with your fps, stop raiding with a toaster. It's only fix for addon sound ducking.
if soundChannels < 64 then
SetCVar("Sound_NumChannels", 64)
end--]]
self.AddOns = {}
self.Voices = { {text = "None",value = "None"}, }--Create voice table, with default "None" value
self.VoiceVersions = {}
for i = 1, GetNumAddOns() do
local addonName = GetAddOnInfo(i)
local enabled = GetAddOnEnableState(playerName, i)
local minToc = tonumber(GetAddOnMetadata(i, "X-Min-Interface"))
if GetAddOnMetadata(i, "X-DBM-Mod") then
if enabled ~= 0 then
if checkEntry(bannedMods, addonName) then
AddMsg(self, "The mod " .. addonName .. " is deprecated and will not be available. Please remove the folder " .. addonName .. " from your Interface" .. (IsWindowsClient() and "\\" or "/") .. "AddOns folder to get rid of this message. Check for an updated version of " .. addonName .. " that is compatible with your game version.")
elseif not testBuild and minToc and minToc > wowTOC then
self:Debug(i.." not loaded because mod requires minimum toc of "..minToc)
else
local mapIdTable = {strsplit(",", GetAddOnMetadata(i, "X-DBM-Mod-MapID") or "")}
tinsert(self.AddOns, {
sort = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-Sort") or mhuge) or mhuge,
type = GetAddOnMetadata(i, "X-DBM-Mod-Type") or "OTHER",
category = GetAddOnMetadata(i, "X-DBM-Mod-Category") or "Other",
name = GetAddOnMetadata(i, "X-DBM-Mod-Name") or GetRealZoneText(tonumber(mapIdTable[1])) or DBM_CORE_UNKNOWN,
mapId = mapIdTable,
subTabs = GetAddOnMetadata(i, "X-DBM-Mod-SubCategoriesID") and {strsplit(",", GetAddOnMetadata(i, "X-DBM-Mod-SubCategoriesID"))} or GetAddOnMetadata(i, "X-DBM-Mod-SubCategories") and {strsplit(",", GetAddOnMetadata(i, "X-DBM-Mod-SubCategories"))},
oneFormat = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-Has-Single-Format") or 0) == 1,
hasLFR = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-Has-LFR") or 0) == 1,
hasChallenge = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-Has-Challenge") or 0) == 1,
noHeroic = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-No-Heroic") or 0) == 1,
noStatistics = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-No-Statistics") or 0) == 1,
hasMythic = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-Has-Mythic") or 0) == 1,
hasTimeWalker = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-Has-TimeWalker") or 0) == 1,
isWorldBoss = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-World-Boss") or 0) == 1,
minRevision = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-MinCoreRevision") or 0),
minExpansion = tonumber(GetAddOnMetadata(i, "X-DBM-Mod-MinExpansion") or 0),
modId = addonName,
})
for i = #self.AddOns[#self.AddOns].mapId, 1, -1 do
local id = tonumber(self.AddOns[#self.AddOns].mapId[i])
if id then
self.AddOns[#self.AddOns].mapId[i] = id
else
tremove(self.AddOns[#self.AddOns].mapId, i)
end
end
if self.AddOns[#self.AddOns].subTabs then
for k, v in ipairs(self.AddOns[#self.AddOns].subTabs) do
local id = tonumber(self.AddOns[#self.AddOns].subTabs[k])
if id then
self.AddOns[#self.AddOns].subTabs[k] = GetRealZoneText(id):trim() or id
else
self.AddOns[#self.AddOns].subTabs[k] = (self.AddOns[#self.AddOns].subTabs[k]):trim()
end
end
end
if GetAddOnMetadata(i, "X-DBM-Mod-LoadCID") then
local idTable = {strsplit(",", GetAddOnMetadata(i, "X-DBM-Mod-LoadCID"))}
for i = 1, #idTable do
loadcIds[tonumber(idTable[i]) or ""] = addonName
end
end
end
else
disabledMods[#disabledMods+1] = addonName
end
end
if GetAddOnMetadata(i, "X-DBM-Voice") and enabled ~= 0 then
if checkEntry(bannedMods, addonName) then
AddMsg(self, "The mod " .. addonName .. " is deprecated and will not be available. Please remove the folder " .. addonName .. " from your Interface" .. (IsWindowsClient() and "\\" or "/") .. "AddOns folder to get rid of this message. Check for an updated version of " .. addonName .. " that is compatible with your game version.")
else
local voiceValue = GetAddOnMetadata(i, "X-DBM-Voice-ShortName")
local voiceVersion = tonumber(GetAddOnMetadata(i, "X-DBM-Voice-Version") or 0)
if voiceVersion > 0 then--Do not insert voice version 0 into THIS table. 0 should be used by voice packs that insert only countdown
tinsert(self.Voices, { text = GetAddOnMetadata(i, "X-DBM-Voice-Name"), value = voiceValue })
end
self.VoiceVersions[voiceValue] = voiceVersion
self:Schedule(10, self.CheckVoicePackVersion, self, voiceValue)--Still at 1 since the count sounds won't break any mods or affect filter. V2 if support countsound path
if GetAddOnMetadata(i, "X-DBM-Voice-HasCount") then--Supports adding countdown options, insert new countdown into table
tinsert(self.Counts, { text = GetAddOnMetadata(i, "X-DBM-Voice-Name"), value = "VP:"..voiceValue, path = "Interface\\AddOns\\DBM-VP"..voiceValue.."\\count\\", max = 10})
end
end
end
if GetAddOnMetadata(i, "X-DBM-CountPack") and enabled ~= 0 then
if checkEntry(bannedMods, addonName) then
AddMsg(self, "The mod " .. addonName .. " is deprecated and will not be available. Please remove the folder " .. addonName .. " from your Interface" .. (IsWindowsClient() and "\\" or "/") .. "AddOns folder to get rid of this message. Check for an updated version of " .. addonName .. " that is compatible with your game version.")
else
local loaded = LoadAddOn(addonName)
local voiceGlobal = GetAddOnMetadata(i, "X-DBM-CountPack-GlobalName")
local insertFunction = _G[voiceGlobal]
if loaded and insertFunction then
insertFunction()
else
DBM:Debug(addonName.." failed to load at time CountPack function ran", 2)
end
end
end
if GetAddOnMetadata(i, "X-DBM-VictoryPack") and enabled ~= 0 then
if checkEntry(bannedMods, addonName) then
AddMsg(self, "The mod " .. addonName .. " is deprecated and will not be available. Please remove the folder " .. addonName .. " from your Interface" .. (IsWindowsClient() and "\\" or "/") .. "AddOns folder to get rid of this message. Check for an updated version of " .. addonName .. " that is compatible with your game version.")
else
local loaded = LoadAddOn(addonName)
local victoryGlobal = GetAddOnMetadata(i, "X-DBM-VictoryPack-GlobalName")
local insertFunction = _G[victoryGlobal]
if loaded and insertFunction then
insertFunction()
else
DBM:Debug(addonName.." failed to load at time CountPack function ran", 2)
end
end
end
if GetAddOnMetadata(i, "X-DBM-DefeatPack") and enabled ~= 0 then
if checkEntry(bannedMods, addonName) then
AddMsg(self, "The mod " .. addonName .. " is deprecated and will not be available. Please remove the folder " .. addonName .. " from your Interface" .. (IsWindowsClient() and "\\" or "/") .. "AddOns folder to get rid of this message. Check for an updated version of " .. addonName .. " that is compatible with your game version.")
else
local loaded = LoadAddOn(addonName)
local defeatGlobal = GetAddOnMetadata(i, "X-DBM-DefeatPack-GlobalName")
local insertFunction = _G[defeatGlobal]
if loaded and insertFunction then
insertFunction()
else
DBM:Debug(addonName.." failed to load at time CountPack function ran", 2)
end
end
end
if GetAddOnMetadata(i, "X-DBM-MusicPack") and enabled ~= 0 then
if checkEntry(bannedMods, addonName) then
AddMsg(self, "The mod " .. addonName .. " is deprecated and will not be available. Please remove the folder " .. addonName .. " from your Interface" .. (IsWindowsClient() and "\\" or "/") .. "AddOns folder to get rid of this message. Check for an updated version of " .. addonName .. " that is compatible with your game version.")
else
local loaded = LoadAddOn(addonName)
local musicGlobal = GetAddOnMetadata(i, "X-DBM-MusicPack-GlobalName")
local insertFunction = _G[musicGlobal]
if loaded and insertFunction then
insertFunction()
else
DBM:Debug(addonName.." failed to load at time CountPack function ran", 2)
end
end
end
end
tsort(self.AddOns, function(v1, v2) return v1.sort < v2.sort end)
self:RegisterEvents(
"COMBAT_LOG_EVENT_UNFILTERED",
"GROUP_ROSTER_UPDATE",
"INSTANCE_GROUP_SIZE_CHANGED",
"CHAT_MSG_ADDON",
"BN_CHAT_MSG_ADDON",
"PLAYER_REGEN_DISABLED",
"PLAYER_REGEN_ENABLED",
"INSTANCE_ENCOUNTER_ENGAGE_UNIT",
"UNIT_TARGETABLE_CHANGED",
"UNIT_SPELLCAST_SUCCEEDED boss1 boss2 boss3 boss4 boss5",
"UNIT_TARGET_UNFILTERED",
"ENCOUNTER_START",
"ENCOUNTER_END",
"BOSS_KILL",
"UNIT_DIED",
"UNIT_DESTROYED",
"UNIT_HEALTH mouseover target focus player",
"CHAT_MSG_WHISPER",
"CHAT_MSG_BN_WHISPER",
"CHAT_MSG_MONSTER_YELL",
"CHAT_MSG_MONSTER_EMOTE",
"CHAT_MSG_MONSTER_SAY",
"CHAT_MSG_RAID_BOSS_EMOTE",
"RAID_BOSS_EMOTE",
"RAID_BOSS_WHISPER",
"PLAYER_ENTERING_WORLD",
"LFG_ROLE_CHECK_SHOW",
"LFG_PROPOSAL_SHOW",
"LFG_PROPOSAL_FAILED",
"LFG_PROPOSAL_SUCCEEDED",
"READY_CHECK",
"UPDATE_BATTLEFIELD_STATUS",
"PLAY_MOVIE",
"CINEMATIC_START",
--"PLAYER_LEVEL_UP",--PLAYER_LEVEL_CHANGED
"PLAYER_SPECIALIZATION_CHANGED",
"PARTY_INVITE_REQUEST",
"LOADING_SCREEN_DISABLED",
"SCENARIO_CRITERIA_UPDATE"
)
if RolePollPopup:IsEventRegistered("ROLE_POLL_BEGIN") then
RolePollPopup:UnregisterEvent("ROLE_POLL_BEGIN")
end
self:GROUP_ROSTER_UPDATE()
C_TimerAfter(1.5, function()
combatInitialized = true
end)
C_TimerAfter(20, function()--Delay UNIT_HEALTH combat start for 20 sec. (not to break Timer Recovery stuff)
healthCombatInitialized = true
end)
self:Schedule(10, runDelayedFunctions, self)
end
end
end
-----------------
-- Callbacks --
-----------------
do
local callbacks = {}
function fireEvent(event, ...)
if not callbacks[event] then return end
for i, v in ipairs(callbacks[event]) do
local ok, err = pcall(v, event, ...)
if not ok then DBM:AddMsg(("Error while executing callback %s for event %s: %s"):format(tostring(v), tostring(event), err)) end
end
end
function DBM:FireEvent(event, ...)
fireEvent(event, ...)
end
function DBM:IsCallbackRegistered(event, f)
if not event or type(f) ~= "function" then
error("Usage: IsCallbackRegistered(event, callbackFunc)", 2)
end
if not callbacks[event] then return end
for i = 1, #callbacks[event] do
if callbacks[event][i] == f then return true end
end
return false
end
function DBM:RegisterCallback(event, f)
if not event or type(f) ~= "function" then
error("Usage: DBM:RegisterCallback(event, callbackFunc)", 2)
end
callbacks[event] = callbacks[event] or {}
tinsert(callbacks[event], f)
return #callbacks[event]
end
function DBM:UnregisterCallback(event, f)
if not event or not callbacks[event] then return end
if f then
if type(f) ~= "function" then
error("Usage: UnregisterCallback(event, callbackFunc)", 2)
end
--> checking from the end to start and not stoping after found one result in case of a func being twice registered.
for i = #callbacks[event], 1, -1 do
if callbacks[event][i] == f then tremove (callbacks[event], i) end
end
else
callbacks[event] = nil
end
end
end
--------------------------
-- OnUpdate/Scheduler --
--------------------------
do
-- stack that stores a few tables (up to 8) which will be recycled
local popCachedTable, pushCachedTable
local numChachedTables = 0
do
local tableCache = nil
-- gets a table from the stack, it will then be recycled.
function popCachedTable()
local t = tableCache
if t then
tableCache = t.next
numChachedTables = numChachedTables - 1
end
return t
end
-- tries to push a table on the stack
-- only tables with <= 4 array entries are accepted as cached tables are only used for tasks with few arguments as we don't want to have big arrays wasting our precious memory space doing nothing...
-- also, the maximum number of cached tables is limited to 8 as DBM rarely has more than eight scheduled tasks with less than 4 arguments at the same time
-- this is just to re-use all the tables of the small tasks that are scheduled all the time (like the wipe detection)
-- note that the cache does not use weak references anywhere for performance reasons, so a cached table will never be deleted by the garbage collector
function pushCachedTable(t)
if numChachedTables < 8 and #t <= 4 then
twipe(t)
t.next = tableCache
tableCache = t
numChachedTables = numChachedTables + 1
end
end
end
-- priority queue (min-heap) that stores all scheduled tasks.
-- insert: O(log n)
-- deleteMin: O(log n)
-- getMin: O(1)
-- removeAllMatching: O(n)
local insert, removeAllMatching, getMin, deleteMin
do
local heap = {}
local firstFree = 1
-- gets the next task
function getMin()
return heap[1]
end
-- restores the heap invariant by moving an item up
local function siftUp(n)
local parent = floor(n / 2)
while n > 1 and heap[parent].time > heap[n].time do -- move the element up until the heap invariant is restored, meaning the element is at the top or the element's parent is <= the element
heap[n], heap[parent] = heap[parent], heap[n] -- swap the element with its parent
n = parent
parent = floor(n / 2)
end
end
-- restores the heap invariant by moving an item down
local function siftDown(n)
local m -- position of the smaller child
while 2 * n < firstFree do -- #children >= 1
-- swap the element with its smaller child
if 2 * n + 1 == firstFree then -- n does not have a right child --> it only has a left child as #children >= 1
m = 2 * n -- left child
elseif heap[2 * n].time < heap[2 * n + 1].time then -- #children = 2 and left child < right child
m = 2 * n -- left child
else -- #children = 2 and right child is smaller than the left one
m = 2 * n + 1 -- right
end
if heap[n].time <= heap[m].time then -- n is <= its smallest child --> heap invariant restored
return
end
heap[n], heap[m] = heap[m], heap[n]
n = m
end
end
-- inserts a new element into the heap
function insert(ele)
heap[firstFree] = ele
siftUp(firstFree)
firstFree = firstFree + 1
end
-- deletes the min element
function deleteMin()
local min = heap[1]
firstFree = firstFree - 1
heap[1] = heap[firstFree]
heap[firstFree] = nil
siftDown(1)
return min
end
-- removes multiple scheduled tasks from the heap
-- note that this function is comparatively slow by design as it has to check all tasks and allows partial matches
function removeAllMatching(f, mod, ...)
-- remove all elements that match the signature, this destroyes the heap and leaves a normal array
local v, match
local foundMatch = false
for i = #heap, 1, -1 do -- iterate backwards over the array to allow usage of table.remove
v = heap[i]
if (not f or v.func == f) and (not mod or v.mod == mod) then
match = true
for i = 1, select("#", ...) do
if select(i, ...) ~= v[i] then
match = false
break
end
end
if match then
tremove(heap, i)
firstFree = firstFree - 1
foundMatch = true
end
end
end
-- rebuild the heap from the array in O(n)
if foundMatch then
for i = floor((firstFree - 1) / 2), 1, -1 do
siftDown(i)
end
end
end
end
local wrappers = {}
local function range(max, cur, ...)
cur = cur or 1
if cur > max then
return ...
end
return cur, range(max, cur + 1, select(2, ...))
end
local function getWrapper(n)
wrappers[n] = wrappers[n] or loadstring(([[
return function(func, tbl)
return func(]] .. ("tbl[%s], "):rep(n):sub(0, -3) .. [[)
end
]]):format(range(n)))()
return wrappers[n]
end
local nextModSyncSpamUpdate = 0
--mainFrame:SetScript("OnUpdate", function(self, elapsed)
local function onUpdate(self, elapsed)
local time = GetTime()
-- execute scheduled tasks
local nextTask = getMin()
while nextTask and nextTask.func and nextTask.time <= time do
deleteMin()
local n = nextTask.n
if n == #nextTask then
nextTask.func(unpack(nextTask))
else
-- too many nil values (or a trailing nil)
-- this is bad because unpack will not work properly
-- TODO: is there a better solution?
getWrapper(n)(nextTask.func, nextTask)
end
pushCachedTable(nextTask)
nextTask = getMin()
end
-- execute OnUpdate handlers of all modules
local foundModFunctions = 0
for i, v in pairs(updateFunctions) do
foundModFunctions = foundModFunctions + 1
if i.Options.Enabled and (not i.zones or i.zones[LastInstanceMapID]) then
i.elapsed = (i.elapsed or 0) + elapsed
if i.elapsed >= (i.updateInterval or 0) then
v(i, i.elapsed)
i.elapsed = 0
end
end
end
-- clean up sync spam timers and auto respond spam blockers
if time > nextModSyncSpamUpdate then
nextModSyncSpamUpdate = time + 20
-- TODO: optimize this; using next(t, k) all the time on nearly empty hash tables is not a good idea...doesn't really matter here as modSyncSpam only very rarely contains more than 4 entries...
-- we now do this just every 20 seconds since the earlier assumption about modSyncSpam isn't true any longer
-- note that not removing entries at all would be just a small memory leak and not a problem (the sync functions themselves check the timestamp)
local k, v = next(modSyncSpam, nil)
if v and (time - v > 8) then
modSyncSpam[k] = nil
end
end
if not nextTask and foundModFunctions == 0 then--Nothing left, stop scheduler
schedulerFrame:SetScript("OnUpdate", nil)
schedulerFrame:Hide()
end
end
function startScheduler()
if not schedulerFrame:IsShown() then
schedulerFrame:Show()
schedulerFrame:SetScript("OnUpdate", onUpdate)
end
end
function schedule(t, f, mod, ...)
if type(f) ~= "function" then
error("usage: schedule(time, func, [mod, args...])", 2)
end
startScheduler()
local v
if numChachedTables > 0 and select("#", ...) <= 4 then -- a cached table is available and all arguments fit into an array with four slots
v = popCachedTable()
v.time = GetTime() + t
v.func = f
v.mod = mod
v.n = select("#", ...)
for i = 1, v.n do
v[i] = select(i, ...)
end
-- clear slots if necessary
for i = v.n + 1, 4 do
v[i] = nil
end
else -- create a new table
v = {time = GetTime() + t, func = f, mod = mod, n = select("#", ...), ...}
end
insert(v)
end
function scheduleCountdown(time, numAnnounces, func, mod, self, ...)
time = time or 5
numAnnounces = numAnnounces or 3
for i = 1, numAnnounces do
schedule(time - i, func, mod, self, i, ...)
end
end
function unschedule(f, mod, ...)
if not f and not mod then
-- you really want to kill the complete scheduler? call unscheduleAll
error("cannot unschedule everything, pass a function and/or a mod")
end
return removeAllMatching(f, mod, ...)
end
function unscheduleAll()
return removeAllMatching()
end
end
function DBM:Schedule(t, f, ...)
if type(f) ~= "function" then
error("usage: DBM:Schedule(time, func, [args...])", 2)
end
return schedule(t, f, nil, ...)
end
function DBM:Unschedule(f, ...)
return unschedule(f, nil, ...)
end
---------------
-- Profile --
---------------
function DBM:CreateProfile(name)
if not name or name == "" or name:find(" ") then
self:AddMsg(DBM_CORE_PROFILE_CREATE_ERROR)
return
end
if DBM_AllSavedOptions[name] then
self:AddMsg(DBM_CORE_PROFILE_CREATE_ERROR_D:format(name))
return
end
-- create profile
usedProfile = name
DBM_UsedProfile = usedProfile
DBM_AllSavedOptions[usedProfile] = DBM_AllSavedOptions[usedProfile] or {}
self:AddDefaultOptions(DBM_AllSavedOptions[usedProfile], self.DefaultOptions)
self.Options = DBM_AllSavedOptions[usedProfile]
-- rearrange position
self.Bars:CreateProfile("DBM")
self:RepositionFrames()
self:AddMsg(DBM_CORE_PROFILE_CREATED:format(name))
end
function DBM:ApplyProfile(name)
if not name or not DBM_AllSavedOptions[name] then
self:AddMsg(DBM_CORE_PROFILE_APPLY_ERROR:format(name or DBM_CORE_UNKNOWN))
return
end
usedProfile = name
DBM_UsedProfile = usedProfile
self:AddDefaultOptions(DBM_AllSavedOptions[usedProfile], self.DefaultOptions)
self.Options = DBM_AllSavedOptions[usedProfile]
-- rearrange position
self.Bars:ApplyProfile("DBM")
self:RepositionFrames()
self:AddMsg(DBM_CORE_PROFILE_APPLIED:format(name))
end
function DBM:CopyProfile(name)
if not name or not DBM_AllSavedOptions[name] then
self:AddMsg(DBM_CORE_PROFILE_COPY_ERROR:format(name or DBM_CORE_UNKNOWN))
return
elseif name == usedProfile then
self:AddMsg(DBM_CORE_PROFILE_COPY_ERROR_SELF)
return
end
DBM_AllSavedOptions[usedProfile] = DBM_AllSavedOptions[name]
self:AddDefaultOptions(DBM_AllSavedOptions[usedProfile], self.DefaultOptions)
self.Options = DBM_AllSavedOptions[usedProfile]
-- rearrange position
self.Bars:CopyProfile(name, "DBM")
self:RepositionFrames()
self:AddMsg(DBM_CORE_PROFILE_COPIED:format(name))
end
function DBM:DeleteProfile(name)
if not name or not DBM_AllSavedOptions[name] then
self:AddMsg(DBM_CORE_PROFILE_DELETE_ERROR:format(name or DBM_CORE_UNKNOWN))
return
elseif name == "Default" then-- Default profile cannot be deleted.
self:AddMsg(DBM_CORE_PROFILE_CANNOT_DELETE)
return
end
--Delete
DBM_AllSavedOptions[name] = nil
usedProfile = "Default"--Restore to default
DBM_UsedProfile = usedProfile
self.Options = DBM_AllSavedOptions[usedProfile]
if not self.Options then
-- the default profile got lost somehow (maybe WoW crashed and the saved variables file got corrupted)
self:CreateProfile("Default")
end
-- rearrange position
self.Bars:DeleteProfile(name, "DBM")
self:RepositionFrames()
self:AddMsg(DBM_CORE_PROFILE_DELETED:format(name))
end
function DBM:RepositionFrames()
-- rearrange position
self:UpdateWarningOptions()
self:UpdateSpecialWarningOptions()
self.Arrow:LoadPosition()
if DBMRangeCheck then
DBMRangeCheck:ClearAllPoints()
DBMRangeCheck:SetPoint(self.Options.RangeFramePoint, UIParent, self.Options.RangeFramePoint, self.Options.RangeFrameX, self.Options.RangeFrameY)
end
if DBMRangeCheckRadar then
DBMRangeCheckRadar:ClearAllPoints()
DBMRangeCheckRadar:SetPoint(self.Options.RangeFrameRadarPoint, UIParent, self.Options.RangeFrameRadarPoint, self.Options.RangeFrameRadarX, self.Options.RangeFrameRadarY)
end
if DBMInfoFrame then
DBMInfoFrame:ClearAllPoints()
DBMInfoFrame:SetPoint(self.Options.InfoFramePoint, UIParent, self.Options.InfoFramePoint, self.Options.InfoFrameX, self.Options.InfoFrameY)
end
end
----------------------
-- Slash Commands --
----------------------
do
local function Pull(timer)
local LFGTankException = IsPartyLFG() and UnitGroupRolesAssigned("player") == "TANK"--Tanks in LFG need to be able to send pull timer even if someone refuses to pass lead. LFG locks roles so no one can abuse this.
if (DBM:GetRaidRank(playerName) == 0 and IsInGroup() and not LFGTankException) or select(2, IsInInstance()) == "pvp" or IsEncounterInProgress() then
return DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
end
local targetName = (UnitExists("target") and UnitIsEnemy("player", "target")) and UnitName("target") or nil--Filter non enemies in case player isn't targetting bos but another player/pet
if targetName then
sendSync("PT", timer.."\t"..LastInstanceMapID.."\t"..targetName)
else
sendSync("PT", timer.."\t"..LastInstanceMapID)
end
end
local function Break(timer)
if IsInGroup() and (DBM:GetRaidRank(playerName) == 0 or IsPartyLFG()) or IsEncounterInProgress() or select(2, IsInInstance()) == "pvp" then--No break timers if not assistant or if it's dungeon/raid finder/BG
DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
return
end
if timer > 60 then
DBM:AddMsg(DBM_CORE_BREAK_USAGE)
return
end
timer = timer * 60
sendSync("BT", timer)
end
SLASH_DEADLYBOSSMODS1 = "/dbm"
SLASH_DEADLYBOSSMODSRPULL1 = "/rpull"
SLASH_DEADLYBOSSMODSDWAY1 = "/dway"--/way not used because DBM would load before TomTom and can't check
SlashCmdList["DEADLYBOSSMODSDWAY"] = function(msg)
if DBM:HasMapRestrictions() then
DBM:AddMsg(DBM_CORE_NO_ARROW)
return
end
local x, y = string.split(" ", msg:sub(1):trim())
local xNum, yNum = tonumber(x or ""), tonumber(y or "")
local success
if xNum and yNum then
DBM.Arrow:ShowRunTo(xNum, yNum, 1, nil, true, true)
success = true
else--Check if they used , instead of space.
x, y = string.split(",", msg:sub(1):trim())
xNum, yNum = tonumber(x or ""), tonumber(y or "")
if xNum and yNum then
DBM.Arrow:ShowRunTo(xNum, yNum, 1, nil, true, true)
success = true
end
end
if not success then
if DBM.Arrow:IsShown() then
DBM.Arrow:Hide()--Hide
else--error
DBM:AddMsg(DBM_ARROW_WAY_USAGE)
end
end
end
if not BigWigs then
--Register pull and break slash commands for BW converts, if BW isn't loaded
--This shouldn't raise an issue since BW SHOULD load before DBM in any case they are both present.
SLASH_DEADLYBOSSMODSPULL1 = "/pull"
SLASH_DEADLYBOSSMODSBREAK1 = "/break"
SlashCmdList["DEADLYBOSSMODSPULL"] = function(msg)
Pull(tonumber(msg) or 10)
end
SlashCmdList["DEADLYBOSSMODSBREAK"] = function(msg)
Break(tonumber(msg) or 10)
end
end
SlashCmdList["DEADLYBOSSMODSRPULL"] = function(msg)
Pull(30)
end
SlashCmdList["DEADLYBOSSMODS"] = function(msg)
local cmd = msg:lower()
if cmd == "ver" or cmd == "version" then
DBM:ShowVersions(false)
elseif cmd == "ver2" or cmd == "version2" then
DBM:ShowVersions(true)
elseif cmd == "unlock" or cmd == "move" then
DBM.Bars:ShowMovableBar()
elseif cmd == "help2" then
for i, v in ipairs(DBM_CORE_SLASHCMD_HELP2) do DBM:AddMsg(v) end
elseif cmd == "help" then
for i, v in ipairs(DBM_CORE_SLASHCMD_HELP) do DBM:AddMsg(v) end
elseif cmd:sub(1, 13) == "timer endloop" then
DBM:CreatePizzaTimer(time, "", nil, nil, nil, nil, true)
elseif cmd:sub(1, 5) == "timer" then
local time, text = msg:match("^%w+ ([%d:]+) (.+)$")
if not (time and text) then
for i, v in ipairs(DBM_CORE_TIMER_USAGE) do DBM:AddMsg(v) end
return
end
local min, sec = string.split(":", time)
min = tonumber(min or "") or 0
sec = tonumber(sec or "")
if min and not sec then
sec = min
min = 0
end
time = min * 60 + sec
DBM:CreatePizzaTimer(time, text)
elseif cmd:sub(1, 6) == "ctimer" then
local time, text = msg:match("^%w+ ([%d:]+) (.+)$")
if not (time and text) then
DBM:AddMsg(DBM_PIZZA_ERROR_USAGE)
return
end
local min, sec = string.split(":", time)
min = tonumber(min or "") or 0
sec = tonumber(sec or "")
if min and not sec then
sec = min
min = 0
end
time = min * 60 + sec
DBM:CreatePizzaTimer(time, text, nil, nil, true)
elseif cmd:sub(1, 6) == "ltimer" then
local time, text = msg:match("^%w+ ([%d:]+) (.+)$")
if not (time and text) then
DBM:AddMsg(DBM_PIZZA_ERROR_USAGE)
return
end
local min, sec = string.split(":", time)
min = tonumber(min or "") or 0
sec = tonumber(sec or "")
if min and not sec then
sec = min
min = 0
end
time = min * 60 + sec
DBM:CreatePizzaTimer(time, text, nil, nil, nil, true)
elseif cmd:sub(1, 7) == "cltimer" then
local time, text = msg:match("^%w+ ([%d:]+) (.+)$")
if not (time and text) then
DBM:AddMsg(DBM_PIZZA_ERROR_USAGE)
return
end
local min, sec = string.split(":", time)
min = tonumber(min or "") or 0
sec = tonumber(sec or "")
if min and not sec then
sec = min
min = 0
end
time = min * 60 + sec
DBM:CreatePizzaTimer(time, text, nil, nil, true, true)
elseif cmd:sub(1, 15) == "broadcast timer" then--Standard Timer
local permission = true
if DBM:GetRaidRank(playerName) == 0 or difficultyIndex == 7 or difficultyIndex == 17 then
DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
permission = false
end
local time, text = msg:match("^%w+ %w+ ([%d:]+) (.+)$")
if not (time and text) then
DBM:AddMsg(DBM_PIZZA_ERROR_USAGE)
return
end
local min, sec = string.split(":", time)
min = tonumber(min or "") or 0
sec = tonumber(sec or "")
if min and not sec then
sec = min
min = 0
end
time = min * 60 + sec
DBM:CreatePizzaTimer(time, text, permission)
elseif cmd:sub(1, 16) == "broadcast ctimer" then
local permission = true
if DBM:GetRaidRank(playerName) == 0 or difficultyIndex == 7 or difficultyIndex == 17 then
DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
permission = false
end
local time, text = msg:match("^%w+ %w+ ([%d:]+) (.+)$")
if not (time and text) then
DBM:AddMsg(DBM_PIZZA_ERROR_USAGE)
return
end
local min, sec = string.split(":", time)
min = tonumber(min or "") or 0
sec = tonumber(sec or "")
if min and not sec then
sec = min
min = 0
end
time = min * 60 + sec
DBM:CreatePizzaTimer(time, text, permission, nil, true)
elseif cmd:sub(1, 16) == "broadcast ltimer" then
local permission = true
if DBM:GetRaidRank(playerName) == 0 or difficultyIndex == 7 or difficultyIndex == 17 then
DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
permission = false
end
local time, text = msg:match("^%w+ %w+ ([%d:]+) (.+)$")
if not (time and text) then
DBM:AddMsg(DBM_PIZZA_ERROR_USAGE)
return
end
local min, sec = string.split(":", time)
min = tonumber(min or "") or 0
sec = tonumber(sec or "")
if min and not sec then
sec = min
min = 0
end
time = min * 60 + sec
DBM:CreatePizzaTimer(time, text, permission, nil, nil, true)
elseif cmd:sub(1, 17) == "broadcast cltimer" then
local permission = true
if DBM:GetRaidRank(playerName) == 0 or difficultyIndex == 7 or difficultyIndex == 17 then
DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
permission = false
end
local time, text = msg:match("^%w+ %w+ ([%d:]+) (.+)$")
if not (time and text) then
DBM:AddMsg(DBM_PIZZA_ERROR_USAGE)
return
end
local min, sec = string.split(":", time)
min = tonumber(min or "") or 0
sec = tonumber(sec or "")
if min and not sec then
sec = min
min = 0
end
time = min * 60 + sec
DBM:CreatePizzaTimer(time, text, permission, nil, true, true)
elseif cmd:sub(0,5) == "break" then
local timer = tonumber(cmd:sub(6)) or 5
Break(timer)
elseif cmd:sub(1, 4) == "pull" then
local timer = tonumber(cmd:sub(5)) or 10
Pull(timer)
elseif cmd:sub(1, 5) == "rpull" then
Pull(30)
elseif cmd:sub(1, 3) == "lag" then
if not LL then
DBM:AddMsg(DBM_CORE_UPDATE_REQUIRES_RELAUNCH)
return
end
LL:RequestLatency()
DBM:AddMsg(DBM_CORE_LAG_CHECKING)
C_TimerAfter(5, function() DBM:ShowLag() end)
elseif cmd:sub(1, 10) == "durability" then
if not LD then
DBM:AddMsg(DBM_CORE_UPDATE_REQUIRES_RELAUNCH)
return
end
LD:RequestDurability()
DBM:AddMsg(DBM_CORE_DUR_CHECKING)
C_TimerAfter(5, function() DBM:ShowDurability() end)
elseif cmd:sub(1, 3) == "hud" then
if DBM:HasMapRestrictions() then
DBM:AddMsg(DBM_CORE_NO_HUD)
return
end
local hudType, target, duration = string.split(" ", msg:sub(4):trim())
if hudType == "" then
for i, v in ipairs(DBM_CORE_HUD_USAGE) do
DBM:AddMsg(v)
end
return
end
local hudDuration = tonumber(duration) or 1200--if no duration defined. 20 minutes to cover even longest of fights
local success = false
if type(hudType) == "string" and hudType:trim() ~= "" then
if hudType:upper() == "HIDE" then
DBMHudMap:Disable()
return
end
if not target then
DBM:AddMsg(DBM_CORE_HUD_INVALID_TARGET)
return
end
local uId
if target:upper() == "TARGET" and UnitExists("target") then
uId = "target"
elseif target:upper() == "FOCUS" and UnitExists("focus") then
uId = "focus"
else--Try to use it as player name
uId = DBM:GetRaidUnitId(target)
end
if not uId then
DBM:AddMsg(DBM_CORE_HUD_INVALID_TARGET)
return
end
if UnitIsUnit("player", uId) and not DBM.Options.DebugMode then--Don't allow hud to self, except if debug mode is enabled, then hud to self useful for testing
DBM:AddMsg(DBM_CORE_HUD_INVALID_SELF)
return
end
if hudType:upper() == "ARROW" then
local _, targetClass = UnitClass(uId)
local color2 = RAID_CLASS_COLORS[targetClass]
local m1 = DBMHudMap:RegisterRangeMarkerOnPartyMember(12345, "party", playerName, 0.1, hudDuration, 0, 1, 0, 1, nil, false):Appear()
local m2 = DBMHudMap:RegisterRangeMarkerOnPartyMember(12345, "party", UnitName(uId), 0.75, hudDuration, color2.r, color2.g, color2.b, 1, nil, false):Appear()
m2:EdgeTo(m1, nil, hudDuration, 0, 1, 0, 1)
success = true
elseif hudType:upper() == "DOT" then
local _, targetClass = UnitClass(uId)
local color2 = RAID_CLASS_COLORS[targetClass]
DBMHudMap:RegisterRangeMarkerOnPartyMember(12345, "party", UnitName(uId), 0.75, hudDuration, color2.r, color2.g, color2.b, 1, nil, false):Appear()
success = true
elseif hudType:upper() == "GREEN" then
DBMHudMap:RegisterRangeMarkerOnPartyMember(12345, "highlight", UnitName(uId), 3.5, hudDuration, 0, 1, 0, 0.5, nil, false):Pulse(0.5, 0.5)
success = true
elseif hudType:upper() == "RED" then
DBMHudMap:RegisterRangeMarkerOnPartyMember(12345, "highlight", UnitName(uId), 3.5, hudDuration, 1, 0, 0, 0.5, nil, false):Pulse(0.5, 0.5)
success = true
elseif hudType:upper() == "YELLOW" then
DBMHudMap:RegisterRangeMarkerOnPartyMember(12345, "highlight", UnitName(uId), 3.5, hudDuration, 1, 1, 0, 0.5, nil, false):Pulse(0.5, 0.5)
success = true
elseif hudType:upper() == "BLUE" then
DBMHudMap:RegisterRangeMarkerOnPartyMember(12345, "highlight", UnitName(uId), 3.5, hudDuration, 0, 0, 1, 0.5, nil, false):Pulse(0.5, 0.5)
success = true
elseif hudType:upper() == "ICON" then
local icon = GetRaidTargetIndex(uId)
if not icon then
DBM:AddMsg(DBM_CORE_HUD_INVALID_ICON)
return
end
local iconString = DBM:IconNumToString(icon):lower()
DBMHudMap:RegisterRangeMarkerOnPartyMember(12345, iconString, UnitName(uId), 3.5, hudDuration, 1, 1, 1, 0.5, nil, false):Pulse(0.5, 0.5)
success = true
else
DBM:AddMsg(DBM_CORE_HUD_INVALID_TYPE)
end
end
if success then
DBM:AddMsg(DBM_CORE_HUD_SUCCESS:format(strFromTime(hudDuration)))
end
elseif cmd:sub(1, 5) == "arrow" then
if DBM:HasMapRestrictions() then
DBM:AddMsg(DBM_CORE_NO_ARROW)
return
end
local x, y, z = string.split(" ", msg:sub(6):trim())
local xNum, yNum, zNum = tonumber(x or ""), tonumber(y or ""), tonumber(z or "")
local success
if xNum and yNum then
DBM.Arrow:ShowRunTo(xNum, yNum, 0)
success = true
elseif type(x) == "string" and x:trim() ~= "" then
local subCmd = x:trim()
if subCmd:upper() == "HIDE" then
DBM.Arrow:Hide()
success = true
elseif subCmd:upper() == "MOVE" then
DBM.Arrow:Move()
success = true
elseif subCmd:upper() == "TARGET" then
DBM.Arrow:ShowRunTo("target")
success = true
elseif subCmd:upper() == "FOCUS" then
DBM.Arrow:ShowRunTo("focus")
success = true
elseif subCmd:upper() == "MAP" then
DBM.Arrow:ShowRunTo(yNum, zNum, 0, nil, true)
success = true
elseif DBM:GetRaidUnitId(subCmd) then
DBM.Arrow:ShowRunTo(subCmd)
success = true
end
end
if not success then
for i, v in ipairs(DBM_ARROW_ERROR_USAGE) do
DBM:AddMsg(v)
end
end
elseif cmd:sub(1, 7) == "lockout" or cmd:sub(1, 3) == "ids" then
if DBM:GetRaidRank(playerName) == 0 then
return DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
end
if not IsInRaid() then
return DBM:AddMsg(DBM_ERROR_NO_RAID)
end
DBM:RequestInstanceInfo()
elseif cmd:sub(1, 10) == "debuglevel" then
local level = tonumber(cmd:sub(11)) or 1
if level < 1 or level > 3 then
DBM:AddMsg("Invalid Value. Debug Level must be between 1 and 3.")
return
end
DBM.Options.DebugLevel = level
DBM:AddMsg("Debug Level is " .. level)
elseif cmd:sub(1, 5) == "debug" then
DBM.Options.DebugMode = DBM.Options.DebugMode == false and true or false
DBM:AddMsg("Debug Message is " .. (DBM.Options.DebugMode and "ON" or "OFF"))
elseif cmd:sub(1, 8) == "whereiam" or cmd:sub(1, 8) == "whereami" then
if DBM:HasMapRestrictions() then
local _, _, _, map = UnitPosition("player")
local mapID = C_Map and C_Map.GetBestMapForUnit("player") or GetCurrentMapAreaID()
DBM:AddMsg(("Location Information\nYou are at zone %u (%s).\nLocal Map ID %u (%s)"):format(map, GetRealZoneText(map), mapID, GetZoneText()))
else
local x, y, _, map = UnitPosition("player")
local mapID, mapx, mapy
if wowTOC == 80000 then
mapID = C_Map.GetBestMapForUnit("player")
local tempTable = C_Map.GetPlayerMapPosition(mapID, "player")
mapx, mapy = tempTable.x, tempTable.y
else
SetMapToCurrentZone()
mapID = GetCurrentMapAreaID()
mapx, mapy = GetPlayerMapPosition("player")
end
DBM:AddMsg(("Location Information\nYou are at zone %u (%s): x=%f, y=%f.\nLocal Map ID %u (%s): x=%f, y=%f"):format(map, GetRealZoneText(map), x, y, mapID, GetZoneText(), mapx, mapy))
end
elseif cmd:sub(1, 7) == "request" then
DBM:Unschedule(DBM.RequestTimers)
DBM:RequestTimers(1)
DBM:RequestTimers(2)
DBM:RequestTimers(3)
elseif cmd:sub(1, 6) == "silent" then
DBM.Options.SilentMode = DBM.Options.SilentMode == false and true or false
DBM:AddMsg("SilentMode is " .. (DBM.Options.SilentMode and "ON" or "OFF"))
elseif cmd:sub(1, 10) == "musicstart" then
DBM:TransitionToDungeonBGM(true)
elseif cmd:sub(1, 9) == "musicstop" then
DBM:TransitionToDungeonBGM(false, true)
else
DBM:LoadGUI()
end
end
end
do
local function updateRangeFrame(r, reverse)
if DBM.RangeCheck:IsShown() then
DBM.RangeCheck:Hide(true)
else
if DBM:HasMapRestrictions() then
DBM:AddMsg(DBM_CORE_NO_RANGE)
elseif IsInInstance() then
DBM:AddMsg(DBM_CORE_NO_RANGE_SOON)
end
if r and (r < 201) then
DBM.RangeCheck:Show(r, nil, true, nil, reverse)
else
DBM.RangeCheck:Show(10, nil, true, nil, reverse)
end
end
end
SLASH_DBMRANGE1 = "/range"
SLASH_DBMRANGE2 = "/distance"
SLASH_DBMHUDAR1 = "/hudar"
SLASH_DBMRRANGE1 = "/rrange"
SLASH_DBMRRANGE2 = "/rdistance"
SlashCmdList["DBMRANGE"] = function(msg)
local r = tonumber(msg) or 10
updateRangeFrame(r, false)
end
SlashCmdList["DBMHUDAR"] = function(msg)
local r = tonumber(msg) or 10
DBMHudMap:ToggleHudar(r)
end
SlashCmdList["DBMRRANGE"] = function(msg)
local r = tonumber(msg) or 10
updateRangeFrame(r, true)
end
end
do
local sortMe = {}
local OutdatedUsers = {}
local function sort(v1, v2)
if v1.revision and not v2.revision then
return true
elseif v2.revision and not v1.revision then
return false
elseif v1.revision and v2.revision then
return v1.revision > v2.revision
else
return (v1.bwversion or 0) > (v2.bwversion or 0)
end
end
function DBM:ShowVersions(notify)
for i, v in pairs(raid) do
tinsert(sortMe, v)
end
tsort(sortMe, sort)
twipe(OutdatedUsers)
self:AddMsg(DBM_CORE_VERSIONCHECK_HEADER)
for i, v in ipairs(sortMe) do
local name = v.name
local playerColor = RAID_CLASS_COLORS[DBM:GetRaidClass(name)]
if playerColor then
name = ("|r|cff%.2x%.2x%.2x%s|r|cff%.2x%.2x%.2x"):format(playerColor.r * 255, playerColor.g * 255, playerColor.b * 255, name, 0.41 * 255, 0.8 * 255, 0.94 * 255)
end
if v.displayVersion and not v.bwversion then--DBM, no BigWigs
if self.Options.ShowAllVersions then
self:AddMsg(DBM_CORE_VERSIONCHECK_ENTRY:format(name, "DBM "..v.displayVersion, "r"..v.revision, v.VPVersion or ""), false)--Only display VP version if not running two mods
end
if notify and v.revision < self.ReleaseRevision then
SendChatMessage(chatPrefixShort..DBM_CORE_YOUR_VERSION_OUTDATED, "WHISPER", nil, v.name)
end
elseif self.Options.ShowAllVersions and v.displayVersion and v.bwversion then--DBM & BigWigs
self:AddMsg(DBM_CORE_VERSIONCHECK_ENTRY_TWO:format(name, "DBM "..v.displayVersion, "r"..v.revision, DBM_BIG_WIGS, versionResponseString:format(v.bwversion, v.bwhash)), false)
elseif self.Options.ShowAllVersions and not v.displayVersion and v.bwversion then--BigWigs, No DBM
self:AddMsg(DBM_CORE_VERSIONCHECK_ENTRY:format(name, DBM_BIG_WIGS, versionResponseString:format(v.bwversion, v.bwhash), ""), false)
else
if self.Options.ShowAllVersions then
self:AddMsg(DBM_CORE_VERSIONCHECK_ENTRY_NO_DBM:format(name), false)
end
end
end
local TotalUsers = #sortMe
local NoDBM = 0
local NoBigwigs = 0
local OldMod = 0
for i = #sortMe, 1, -1 do
if not sortMe[i].revision then
NoDBM = NoDBM + 1
end
if not (sortMe[i].bwversion) then
NoBigwigs = NoBigwigs + 1
end
--Table sorting sorts dbm to top, bigwigs underneath. Highest version dbm always at top. so sortMe[1]
--This check compares all dbm version to highest RELEASE version in raid.
if sortMe[i].revision and (sortMe[i].revision < sortMe[1].version) or sortMe[i].bwversion and (sortMe[i].bwversion < fakeBWVersion) then
OldMod = OldMod + 1
local name = sortMe[i].name
local playerColor = RAID_CLASS_COLORS[DBM:GetRaidClass(name)]
if playerColor then
name = ("|r|cff%.2x%.2x%.2x%s|r|cff%.2x%.2x%.2x"):format(playerColor.r * 255, playerColor.g * 255, playerColor.b * 255, name, 0.41 * 255, 0.8 * 255, 0.94 * 255)
end
tinsert(OutdatedUsers, name)
end
end
local TotalDBM = TotalUsers - NoDBM
local TotalBW = TotalUsers - NoBigwigs
self:AddMsg("---", false)
self:AddMsg(DBM_CORE_VERSIONCHECK_FOOTER:format(TotalDBM, TotalBW), false)
self:AddMsg(DBM_CORE_VERSIONCHECK_OUTDATED:format(OldMod, #OutdatedUsers > 0 and tconcat(OutdatedUsers, ", ") or NONE), false)
twipe(OutdatedUsers)
twipe(sortMe)
for i = #sortMe, 1, -1 do
sortMe[i] = nil
end
end
end
-- Lag checking
do
local sortLag = {}
local nolagResponse = {}
local function sortit(v1, v2)
return (v1.worldlag or 0) < (v2.worldlag or 0)
end
function DBM:ShowLag()
for i, v in pairs(raid) do
tinsert(sortLag, v)
end
tsort(sortLag, sortit)
self:AddMsg(DBM_CORE_LAG_HEADER)
for i, v in ipairs(sortLag) do
local name = v.name
local playerColor = RAID_CLASS_COLORS[DBM:GetRaidClass(name)]
if playerColor then
name = ("|r|cff%.2x%.2x%.2x%s|r|cff%.2x%.2x%.2x"):format(playerColor.r * 255, playerColor.g * 255, playerColor.b * 255, name, 0.41 * 255, 0.8 * 255, 0.94 * 255)
end
if v.worldlag then
self:AddMsg(DBM_CORE_LAG_ENTRY:format(name, v.worldlag, v.homelag), false)
else
tinsert(nolagResponse, v.name)
end
end
if #nolagResponse > 0 then
self:AddMsg(DBM_CORE_LAG_FOOTER:format(tconcat(nolagResponse, ", ")), false)
for i = #nolagResponse, 1, -1 do
nolagResponse[i] = nil
end
end
for i = #sortLag, 1, -1 do
sortLag[i] = nil
end
end
if LL then
LL:Register("DBM", function(homelag, worldlag, sender, channel)
if sender and raid[sender] then
raid[sender].homelag = homelag
raid[sender].worldlag = worldlag
end
end)
end
end
-- Durability checking
do
local sortDur = {}
local nodurResponse = {}
local function sortit(v1, v2)
return (v1.worldlag or 0) < (v2.worldlag or 0)
end
function DBM:ShowDurability()
for i, v in pairs(raid) do
tinsert(sortDur, v)
end
tsort(sortDur, sortit)
self:AddMsg(DBM_CORE_DUR_HEADER)
for i, v in ipairs(sortDur) do
local name = v.name
local playerColor = RAID_CLASS_COLORS[DBM:GetRaidClass(name)]
if playerColor then
name = ("|r|cff%.2x%.2x%.2x%s|r|cff%.2x%.2x%.2x"):format(playerColor.r * 255, playerColor.g * 255, playerColor.b * 255, name, 0.41 * 255, 0.8 * 255, 0.94 * 255)
end
if v.durpercent then
self:AddMsg(DBM_CORE_DUR_ENTRY:format(name, v.durpercent, v.durbroken), false)
else
tinsert(nodurResponse, v.name)
end
end
if #nodurResponse > 0 then
self:AddMsg(DBM_CORE_LAG_FOOTER:format(tconcat(nodurResponse, ", ")), false)
for i = #nodurResponse, 1, -1 do
nodurResponse[i] = nil
end
end
for i = #sortDur, 1, -1 do
sortDur[i] = nil
end
end
if LD then
LD:Register("DBM", function(percent, broken, sender, channel)
if sender and raid[sender] then
raid[sender].durpercent = percent
raid[sender].durbroken = broken
end
end)
end
end
-------------------
-- Pizza Timer --
-------------------
do
local function loopTimer(time, text, broadcast, sender, count)
DBM:CreatePizzaTimer(time, text, broadcast, sender, count, true)
end
local ignore = {}
local fakeMod -- dummy mod for the count sound effects
--Standard Pizza Timer
function DBM:CreatePizzaTimer(time, text, broadcast, sender, count, loop, terminate)
if not fakeMod then
fakeMod = self:NewMod("CreateCountTimerDummy")
self:GetModLocalization("CreateCountTimerDummy"):SetGeneralLocalization{ name = DBM_CORE_MINIMAP_TOOLTIP_HEADER }
fakeMod.countdown = fakeMod:NewCountdown(0, 0, nil, nil, nil, true)
end
if terminate or time == 0 then
self:Unschedule(loopTimer)
fakeMod.countdown:Cancel()
self.Bars:CancelBar(text)
fireEvent("DBM_TimerStop", "DBMPizzaTimer")
return
end
if sender and ignore[sender] then return end
text = text:sub(1, 16)
text = text:gsub("%%t", UnitName("target") or "<no target>")
if time < 3 then
self:AddMsg(DBM_PIZZA_ERROR_USAGE)
return
end
self.Bars:CreateBar(time, text, "Interface\\Icons\\Spell_Holy_BorrowedTime")
fireEvent("DBM_TimerStart", "DBMPizzaTimer", text, time, "Interface\\Icons\\Spell_Holy_BorrowedTime", "pizzatimer", nil, 0)
if broadcast then
if count then
if wowTOC == 80000 then
sendLoggedSync("CU", ("%s\t%s"):format(time, text))
else
sendSync("CU", ("%s\t%s"):format(time, text))
end
else
if wowTOC == 80000 then
sendLoggedSync("U", ("%s\t%s"):format(time, text))
else
sendSync("U", ("%s\t%s"):format(time, text))
end
end
end
if sender then self:ShowPizzaInfo(text, sender) end
if count then
if not fakeMod then
local threshold = self.Options.PTCountThreshold
fakeMod = self:NewMod("CreateCountTimerDummy")
self:GetModLocalization("CreateCountTimerDummy"):SetGeneralLocalization{ name = DBM_CORE_MINIMAP_TOOLTIP_HEADER }
local adjustedThreshold = 5
if threshold > 10 then
adjustedThreshold = 10
else
adjustedThreshold = floor(threshold)
end
fakeMod.countdown = fakeMod:NewCountdown(0, 0, nil, nil, adjustedThreshold, true)
end
if not self.Options.DontPlayPTCountdown then
fakeMod.countdown:Cancel()
fakeMod.countdown:Start(time)
end
end
if loop then
self:Unschedule(loopTimer)--Only one loop timer supported at once doing this, but much cleaner this way
self:Schedule(time, loopTimer, time, text, broadcast, sender, count)
end
end
function DBM:AddToPizzaIgnore(name)
ignore[name] = true
end
end
function DBM:ShowPizzaInfo(id, sender)
if self.Options.ShowPizzaMessage then
self:AddMsg(DBM_PIZZA_SYNC_INFO:format(sender, id))
end
end
-----------------
-- GUI Stuff --
-----------------
do
local callOnLoad = {}
function DBM:LoadGUI()
if GetAddOnEnableState(playerName, "VEM-Core") >= 1 then
self:AddMsg(DBM_CORE_VEM)
return
end
if GetAddOnEnableState(playerName, "DBM-Profiles") >= 1 then
self:AddMsg(DBM_CORE_3RDPROFILES)
return
end
if GetAddOnEnableState(playerName, "DPMCore") >= 1 then
self:AddMsg(DBM_CORE_DPMCORE)
return
end
if not dbmIsEnabled then
DBM:AddMsg(DBM_CORE_UPDATEREMINDER_DISABLE)
return
end
if not IsAddOnLoaded("DBM-GUI") then
local enabled = GetAddOnEnableState(playerName, "DBM-GUI")
if enabled == 0 then
EnableAddOn("DBM-GUI")
end
local loaded, reason = LoadAddOn("DBM-GUI")
if not loaded then
if reason then
self:AddMsg(DBM_CORE_LOAD_GUI_ERROR:format(tostring(_G["ADDON_"..reason or ""])))
else
self:AddMsg(DBM_CORE_LOAD_GUI_ERROR:format(DBM_CORE_UNKNOWN))
end
return false
end
tsort(callOnLoad, function(v1, v2) return v1[2] < v2[2] end)
for i, v in ipairs(callOnLoad) do v[1]() end
if not InCombatLockdown() and not UnitAffectingCombat("player") and not IsFalling() then--We loaded in combat but still need to avoid garbage collect in combat
collectgarbage("collect")
end
end
return DBM_GUI:ShowHide()
end
function DBM:RegisterOnGuiLoadCallback(f, sort)
tinsert(callOnLoad, {f, sort or mhuge})
end
end
----------------------
-- Minimap Button --
----------------------
do
local dragMode = nil
local function moveButton(self)
if dragMode == "free" then
local centerX, centerY = Minimap:GetCenter()
local x, y = GetCursorPosition()
x, y = x / self:GetEffectiveScale() - centerX, y / self:GetEffectiveScale() - centerY
self:ClearAllPoints()
self:SetPoint("CENTER", x, y)
else
local centerX, centerY = Minimap:GetCenter()
local x, y = GetCursorPosition()
x, y = x / self:GetEffectiveScale() - centerX, y / self:GetEffectiveScale() - centerY
centerX, centerY = math.abs(x), math.abs(y)
centerX, centerY = (centerX / math.sqrt(centerX^2 + centerY^2)) * 80, (centerY / sqrt(centerX^2 + centerY^2)) * 80
centerX = x < 0 and -centerX or centerX
centerY = y < 0 and -centerY or centerY
self:ClearAllPoints()
self:SetPoint("CENTER", centerX, centerY)
end
end
local button = CreateFrame("Button", "DBMMinimapButton", Minimap)
button:SetHeight(32)
button:SetWidth(32)
button:SetFrameStrata("MEDIUM")
button:SetPoint("CENTER", -65.35, -38.8)
button:SetMovable(true)
button:SetUserPlaced(true)
button:SetNormalTexture("Interface\\AddOns\\DBM-Core\\textures\\Minimap-Button-Up")
button:SetPushedTexture("Interface\\AddOns\\DBM-Core\\textures\\Minimap-Button-Down")
button:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
button:SetScript("OnMouseDown", function(self, button)
if IsShiftKeyDown() and IsAltKeyDown() then
dragMode = "free"
self:SetScript("OnUpdate", moveButton)
elseif IsShiftKeyDown() or button == "RightButton" then
dragMode = nil
self:SetScript("OnUpdate", moveButton)
end
end)
button:SetScript("OnMouseUp", function(self)
self:SetScript("OnUpdate", nil)
end)
button:SetScript("OnClick", function(self, button)
if IsShiftKeyDown() or button == "RightButton" then return end
DBM:LoadGUI()
end)
button:SetScript("OnEnter", function(self)
-- GameTooltip_SetDefaultAnchor(GameTooltip, self)
GameTooltip:SetOwner(self,"TOPLEFT",30,-110) --bf@178.com
GameTooltip:SetText(DBM_CORE_MINIMAP_TOOLTIP_HEADER, 1, 1, 1)
GameTooltip:AddLine(ver, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1)
GameTooltip:AddLine(" ")
GameTooltip:AddLine(DBM_CORE_MINIMAP_TOOLTIP_FOOTER, RAID_CLASS_COLORS.MAGE.r, RAID_CLASS_COLORS.MAGE.g, RAID_CLASS_COLORS.MAGE.b, 1)
GameTooltip:Show()
end)
button:SetScript("OnLeave", function(self)
GameTooltip:Hide()
end)
function DBM:ToggleMinimapButton()
self.Options.ShowMinimapButton = not self.Options.ShowMinimapButton
if self.Options.ShowMinimapButton then
button:Show()
else
button:Hide()
end
end
function DBM:HideMinimapButton()
return button:Hide()
end
end
-------------------------------------------------
-- Raid/Party Handling and Unit ID Utilities --
-------------------------------------------------
do
local inRaid = false
local raidGuids = {}
local iconSeter = {}
-- save playerinfo into raid table on load. (for solo raid)
DBM:RegisterOnLoadCallback(function()
C_TimerAfter(6, function()
if not raid[playerName] then
raid[playerName] = {}
raid[playerName].name = playerName
raid[playerName].shortname = playerName
raid[playerName].guid = UnitGUID("player")
raid[playerName].rank = 0
raid[playerName].class = playerClass
raid[playerName].id = "player"
raid[playerName].groupId = 0
raid[playerName].revision = DBM.Revision
raid[playerName].version = DBM.ReleaseRevision
raid[playerName].displayVersion = DBM.DisplayVersion
raid[playerName].locale = GetLocale()
raid[playerName].enabledIcons = tostring(not DBM.Options.DontSetIcons)
raidGuids[UnitGUID("player") or ""] = playerName
end
end)
end)
local function updateAllRoster(self)
if IsInRaid() then
if not inRaid then
inRaid = true
sendSync("H")
SendAddonMessage("BigWigs", versionQueryString:format(0, fakeBWHash), IsPartyLFG() and "INSTANCE_CHAT" or "RAID")
self:Schedule(2, self.RoleCheck, false, self)
fireEvent("raidJoin", playerName)
if BigWigs and BigWigs.db.profile.raidicon and not self.Options.DontSetIcons and self:GetRaidRank() > 0 then--Both DBM and bigwigs have raid icon marking turned on.
self:AddMsg(DBM_CORE_BIGWIGS_ICON_CONFLICT)--Warn that one of them should be turned off to prevent conflict (which they turn off is obviously up to raid leaders preference, dbm accepts either or turned off to stop this alert)
end
end
for i = 1, GetNumGroupMembers() do
local name, rank, subgroup, _, _, className = GetRaidRosterInfo(i)
-- Maybe GetNumGroupMembers() bug? Seems that GetNumGroupMembers() rarely returns bad value, causing GetRaidRosterInfo() returns to nil.
-- Filter name = nil to prevent nil table error.
if name then
local id = "raid" .. i
local shortname = UnitName(id)
if (not raid[name]) and inRaid then
fireEvent("raidJoin", name)
end
raid[name] = raid[name] or {}
raid[name].name = name
raid[name].shortname = shortname
raid[name].rank = rank
raid[name].subgroup = subgroup
raid[name].class = className
raid[name].id = id
raid[name].groupId = i
raid[name].guid = UnitGUID(id) or ""
raid[name].updated = true
raidGuids[UnitGUID(id) or ""] = name
end
end
enableIcons = false
twipe(iconSeter)
for i, v in pairs(raid) do
if not v.updated then
raidGuids[v.guid] = nil
raid[i] = nil
removeEntry(newerVersionPerson, i)
fireEvent("raidLeave", i)
else
v.updated = nil
if v.revision and v.rank > 0 and (v.enabledIcons or "") == "true" then
iconSeter[#iconSeter + 1] = v.revision.." "..v.name
end
end
end
if #iconSeter > 0 then
tsort(iconSeter, function(a, b) return a > b end)
local elected = iconSeter[1]
if playerName == elected:sub(elected:find(" ") + 1) then
enableIcons = true
end
end
elseif IsInGroup() then
if not inRaid then
-- joined a new party
inRaid = true
sendSync("H")
SendAddonMessage("BigWigs", versionQueryString:format(0, fakeBWHash), IsPartyLFG() and "INSTANCE_CHAT" or "RAID")
self:Schedule(2, self.RoleCheck, false, self)
fireEvent("partyJoin", playerName)
end
for i = 0, GetNumSubgroupMembers() do
local id
if (i == 0) then
id = "player"
else
id = "party"..i
end
local name = GetUnitName(id, true)
local shortname = UnitName(id)
local rank = UnitIsGroupLeader(id) and 2 or 0
local _, className = UnitClass(id)
if (not raid[name]) and inRaid then
fireEvent("partyJoin", name)
end
raid[name] = raid[name] or {}
raid[name].name = name
raid[name].shortname = shortname
raid[name].guid = UnitGUID(id) or ""
raid[name].rank = rank
raid[name].class = className
raid[name].id = id
raid[name].groupId = i
raid[name].updated = true
raidGuids[UnitGUID(id) or ""] = name
end
enableIcons = false
twipe(iconSeter)
for i, v in pairs(raid) do
if not v.updated then
raidGuids[v.guid] = nil
raid[i] = nil
removeEntry(newerVersionPerson, i)
fireEvent("partyLeave", i)
else
v.updated = nil
if v.revision and v.rank > 0 and (v.enabledIcons or "") == "true" then
iconSeter[#iconSeter + 1] = v.revision.." "..v.name
end
end
end
if #iconSeter > 0 then
tsort(iconSeter, function(a, b) return a > b end)
local elected = iconSeter[1]
if playerName == elected:sub(elected:find(" ") + 1) then
enableIcons = true
end
end
else
-- left the current group/raid
inRaid = false
enableIcons = true
fireEvent("raidLeave", playerName)
twipe(raid)
twipe(newerVersionPerson)
-- restore playerinfo into raid table on raidleave. (for solo raid)
raid[playerName] = {}
raid[playerName].name = playerName
raid[playerName].shortname = playerName
raid[playerName].guid = UnitGUID("player")
raid[playerName].rank = 0
raid[playerName].class = playerClass
raid[playerName].id = "player"
raid[playerName].groupId = 0
raid[playerName].revision = DBM.Revision
raid[playerName].version = DBM.ReleaseRevision
raid[playerName].displayVersion = DBM.DisplayVersion
raid[playerName].locale = GetLocale()
raidGuids[UnitGUID("player")] = playerName
end
end
function DBM:GROUP_ROSTER_UPDATE(force)
self:Unschedule(updateAllRoster)
if force then
updateAllRoster(self)
else
self:Schedule(1.5, updateAllRoster, self)
end
end
function DBM:INSTANCE_GROUP_SIZE_CHANGED()
local _, _, _, _, _, _, _, _, instanceGroupSize = GetInstanceInfo()
LastGroupSize = instanceGroupSize
end
--C_Map.GetMapGroupMembersInfo
function DBM:GetNumRealPlayersInZone()
if not IsInGroup() then return 1 end
local total = 0
local _, _, _, currentMapId = UnitPosition("player")
if IsInRaid() then
for i = 1, GetNumGroupMembers() do
local _, _, _, targetMapId = UnitPosition("raid"..i)
if targetMapId == currentMapId then
total = total + 1
end
end
else
total = 1--add player/self for "party" count
for i = 1, GetNumSubgroupMembers() do
local _, _, _, targetMapId = UnitPosition("party"..i)
if targetMapId == currentMapId then
total = total + 1
end
end
end
return total
end
function DBM:GetRaidRank(name)
local name = name or playerName
if name == playerName then--If name is player, try to get actual rank. Because raid[name].rank sometimes seems returning 0 even player is promoted.
return UnitIsGroupLeader("player") and 2 or UnitIsGroupAssistant("player") and 1 or 0
else
return (raid[name] and raid[name].rank) or 0
end
end
function DBM:GetRaidSubgroup(name)
return (raid[name] and raid[name].subgroup) or 0
end
function DBM:GetRaidClass(name)
return (raid[name] and raid[name].class) or "UNKNOWN"
end
function DBM:GetRaidUnitId(name)
return raid[name] and raid[name].id
end
function DBM:GetEnemyUnitIdByGUID(guid)
for i = 1, 5 do
local unitId = "boss"..i
local guid2 = UnitGUID(unitId)
if guid == guid2 then
return unitId
end
end
local idType = (IsInRaid() and "raid") or "party"
for i = 0, GetNumGroupMembers() do
local unitId = ((i == 0) and "target") or idType..i.."target"
local guid2 = UnitGUID(unitId)
if guid == guid2 then
return unitId
end
end
return DBM_CORE_UNKNOWN
end
function DBM:GetPlayerGUIDByName(name)
return raid[name] and raid[name].guid
end
function DBM:GetMyPlayerInfo()
return playerName, playerLevel, playerRealm
end
function DBM:GetUnitFullName(uId)
if not uId then return nil end
return GetUnitName(uId, true)
end
function DBM:GetFullPlayerNameByGUID(guid)
return raidGuids[guid]
end
function DBM:GetPlayerNameByGUID(guid)
return raidGuids[guid] and raidGuids[guid]:gsub("%-.*$", "")
end
function DBM:GetGroupId(name)
local raidMember = raid[name] or raid[GetUnitName(name, true) or ""]
return raidMember and raidMember.groupId or 0
end
end
do
-- yes, we still do avoid memory allocations during fights; so we don't use a closure around a counter here
-- this seems to be the easiest way to write an iterator that returns the unit id *string* as first argument without a memory allocation
local function raidIterator(groupMembers, uId)
local a, b = uId:byte(-2, -1)
local i = (a >= 0x30 and a <= 0x39 and (a - 0x30) * 10 or 0) + b - 0x30
if i < groupMembers then
return "raid" .. i + 1, i + 1
end
end
local function partyIterator(groupMembers, uId)
if not uId then
return "player", 0
elseif uId == "player" then
if groupMembers > 0 then
return "party1", 1
end
else
local i = uId:byte(-1) - 0x30
if i < groupMembers then
return "party" .. i + 1, i + 1
end
end
end
local function soloIterator(_, state)
if not state then -- no state == first call
return "player", 0
end
end
-- returns the unit ids of all raid or party members, including the player's own id
-- limitations: will break if there are ever raids with more than 99 players or partys with more than 10
function DBM:GetGroupMembers()
if IsInRaid() then
return raidIterator, GetNumGroupMembers(), "raid0"
elseif IsInGroup() then
return partyIterator, GetNumSubgroupMembers(), nil
else
-- solo!
return soloIterator, nil, nil
end
end
end
function DBM:GetNumGroupMembers()
return IsInGroup() and GetNumGroupMembers() or 1
end
--For returning the number of players actually in zone with us for status functions
--This is very touchy though and will fail if everyone isn't in same SUB zone (ie same room/area)
--It should work for pretty much any case but outdoor
function DBM:GetNumRealGroupMembers()
if not IsInInstance() then--Not accurate outside of instances (such as world bosses)
return IsInGroup() and GetNumGroupMembers() or 1--So just return regular group members.
end
local _, _, _, currentMapId = UnitPosition("player")
local realGroupMembers = 0
if IsInGroup() then
for uId in self:GetGroupMembers() do
local _, _, _, targetMapId = UnitPosition(uId)
if targetMapId == currentMapId then
realGroupMembers = realGroupMembers + 1
end
end
else
return 1
end
return realGroupMembers
end
function DBM:GetUnitCreatureId(uId)
local guid = UnitGUID(uId)
return self:GetCIDFromGUID(guid)
end
--Creature/Vehicle/Pet
----<type>:<subtype>:<realmID>:<mapID>:<serverID>:<dbID>:<creationbits>
--Player/Item
----<type>:<realmID>:<dbID>
function DBM:GetCIDFromGUID(guid)
local type, _, playerdbID, _, _, cid, creationbits = strsplit("-", guid or "")
if type and (type == "Creature" or type == "Vehicle" or type == "Pet") then
return tonumber(cid)
elseif type and (type == "Player" or type == "Item") then
return tonumber(playerdbID)
end
return 0
end
function DBM:IsCreatureGUID(guid)
local type = strsplit("-", guid or "")
if type and (type == "Creature" or type == "Vehicle") then--To determine, add pet or not?
return true
end
return false
end
function DBM:GetBossUnitId(name, bossOnly)
local returnUnitID
for i = 1, 5 do
if UnitName("boss" .. i) == name then
returnUnitID = "boss"..i
end
end
if not returnUnitID and not bossOnly then
for uId in self:GetGroupMembers() do
if UnitName(uId .. "target") == name and not UnitIsPlayer(uId .. "target") then
returnUnitID = uId.."target"
end
end
end
return returnUnitID
end
function DBM:GetUnitIdFromGUID(guid, bossOnly)
local returnUnitID
for i = 1, 5 do
local unitId = "boss"..i
local bossGUID = UnitGUID(unitId)
if bossGUID == guid then
returnUnitID = bossGUID
end
end
--Didn't find valid unitID from boss units, scan raid targets
if not returnUnitID and not bossOnly then
for uId in self:GetGroupMembers() do
if UnitGUID(uId .. "target") == guid then
returnUnitID = uId.."target"
end
end
end
return returnUnitID
end
---------------
-- Options --
---------------
function DBM:AddDefaultOptions(t1, t2)
for i, v in pairs(t2) do
if t1[i] == nil then
t1[i] = v
elseif type(v) == "table" and type(t1[i]) == "table" then
self:AddDefaultOptions(t1[i], v)
end
end
end
function DBM:LoadModOptions(modId, inCombat, first)
local oldSavedVarsName = modId:gsub("-", "").."_SavedVars"
local savedVarsName = modId:gsub("-", "").."_AllSavedVars"
local savedStatsName = modId:gsub("-", "").."_SavedStats"
local fullname = playerName.."-"..playerRealm
if not currentSpecID or not currentSpecGroup then
self:SetCurrentSpecInfo()
end
local profileNum = playerLevel > 9 and DBM_UseDualProfile and currentSpecGroup or 0
if not _G[savedVarsName] then _G[savedVarsName] = {} end
local savedOptions = _G[savedVarsName][fullname] or {}
local savedStats = _G[savedStatsName] or {}
local existId = {}
for i, id in ipairs(DBM.ModLists[modId]) do
existId[id] = true
-- init
if not savedOptions[id] then savedOptions[id] = {} end
local mod = DBM:GetModByName(id)
-- migrate old option
if _G[oldSavedVarsName] and _G[oldSavedVarsName][id] then
self:Debug("LoadModOptions: Found old options, importing", 2)
local oldTable = _G[oldSavedVarsName][id]
_G[oldSavedVarsName][id] = nil
savedOptions[id][profileNum] = oldTable
end
if not savedOptions[id][profileNum] and not first then--previous profile not found. load defaults
self:Debug("LoadModOptions: No saved options, creating defaults for profile "..profileNum, 2)
local defaultOptions = {}
for option, optionValue in pairs(mod.DefaultOptions) do
if type(optionValue) == "table" then
optionValue = optionValue.value
elseif type(optionValue) == "string" then
optionValue = mod:GetRoleFlagValue(optionValue)
end
defaultOptions[option] = optionValue
end
savedOptions[id][profileNum] = defaultOptions
else
savedOptions[id][profileNum] = savedOptions[id][profileNum] or mod.Options
--check new option
for option, optionValue in pairs(mod.DefaultOptions) do
if savedOptions[id][profileNum][option] == nil then
if type(optionValue) == "table" then
optionValue = optionValue.value
elseif type(optionValue) == "string" then
optionValue = mod:GetRoleFlagValue(optionValue)
end
savedOptions[id][profileNum][option] = optionValue
end
end
--clean unused saved variables (do not work on combat load)
if not inCombat then
for option, optionValue in pairs(savedOptions[id][profileNum]) do
if mod.DefaultOptions[option] == nil then
savedOptions[id][profileNum][option] = nil
elseif mod.DefaultOptions[option] and (type(mod.DefaultOptions[option]) == "table") then--recover broken dropdown option
if savedOptions[id][profileNum][option] and (type(savedOptions[id][profileNum][option]) == "boolean") then
savedOptions[id][profileNum][option] = mod.DefaultOptions[option].value
end
--Fix default options for colored bar by type that were set to 0 because no defaults existed at time they were created, but do now.
elseif option:find("TColor") then
if savedOptions[id][profileNum][option] and savedOptions[id][profileNum][option] == 0 and mod.DefaultOptions[option] and mod.DefaultOptions[option] ~= 0 then
savedOptions[id][profileNum][option] = mod.DefaultOptions[option]
end
end
end
end
end
--apply saved option to actual option table
mod.Options = savedOptions[id][profileNum]
--stats init (only first load)
if first then
savedStats[id] = savedStats[id] or {}
local stats = savedStats[id]
stats.normalKills = stats.normalKills or 0
stats.normalPulls = stats.normalPulls or 0
stats.heroicKills = stats.heroicKills or 0
stats.heroicPulls = stats.heroicPulls or 0
stats.challengeKills = stats.challengeKills or 0
stats.challengePulls = stats.challengePulls or 0
stats.challengeBestRank = stats.challengeBestRank or 0
stats.mythicKills = stats.mythicKills or 0
stats.mythicPulls = stats.mythicPulls or 0
stats.normal25Kills = stats.normal25Kills or 0
stats.normal25Kills = stats.normal25Kills or 0
stats.normal25Pulls = stats.normal25Pulls or 0
stats.heroic25Kills = stats.heroic25Kills or 0
stats.heroic25Pulls = stats.heroic25Pulls or 0
stats.lfr25Kills = stats.lfr25Kills or 0
stats.lfr25Pulls = stats.lfr25Pulls or 0
stats.timewalkerKills = stats.timewalkerKills or 0
stats.timewalkerPulls = stats.timewalkerPulls or 0
mod.stats = stats
--run OnInitialize function
if mod.OnInitialize then mod:OnInitialize(mod) end
end
end
--clean unused saved variables (do not work on combat load)
if not inCombat then
for id, table in pairs(savedOptions) do
if not existId[id] and not id:find("talent") then
savedOptions[id] = nil
end
end
for id, table in pairs(savedStats) do
if not existId[id] then
savedStats[id] = nil
end
end
end
_G[savedVarsName][fullname] = savedOptions
if profileNum > 0 then
_G[savedVarsName][fullname]["talent"..profileNum] = currentSpecName
self:Debug("LoadModOptions: Finished loading "..(_G[savedVarsName][fullname]["talent"..profileNum] or DBM_CORE_UNKNOWN))
end
_G[savedStatsName] = savedStats
if not first and DBM_GUI and DBM_GUI.currentViewing and DBM_GUI_OptionsFrame:IsShown() then
DBM_GUI_OptionsFrame:DisplayFrame(DBM_GUI.currentViewing)
end
end
function DBM:SpecChanged(force)
if not force and not DBM_UseDualProfile then return end
--Load Options again.
self:Debug("SpecChanged fired", 2)
for modId, idTable in pairs(self.ModLists) do
self:LoadModOptions(modId)
end
end
function DBM:PLAYER_LEVEL_UP()
playerLevel = UnitLevel("player")
if playerLevel < 15 and playerLevel > 9 then
self:PLAYER_SPECIALIZATION_CHANGED()
end
end
function DBM:LoadAllModDefaultOption(modId)
-- modId is string like "DBM-Highmaul"
if not modId or not self.ModLists[modId] then return end
-- prevent error
if not currentSpecID or not currentSpecGroup then
self:SetCurrentSpecInfo()
end
-- variable init
local savedVarsName = modId:gsub("-", "").."_AllSavedVars"
local fullname = playerName.."-"..playerRealm
local profileNum = playerLevel > 9 and DBM_UseDualProfile and currentSpecGroup or 0
-- prevent nil table error
if not _G[savedVarsName] then _G[savedVarsName] = {} end
for i, id in ipairs(self.ModLists[modId]) do
-- prevent nil table error
if not _G[savedVarsName][fullname][id] then _G[savedVarsName][fullname][id] = {} end
-- actual do load default option
local mod = self:GetModByName(id)
local defaultOptions = {}
for option, optionValue in pairs(mod.DefaultOptions) do
if type(optionValue) == "table" then
optionValue = optionValue.value
elseif type(optionValue) == "string" then
optionValue = mod:GetRoleFlagValue(optionValue)
end
defaultOptions[option] = optionValue
end
mod.Options = {}
mod.Options = defaultOptions
_G[savedVarsName][fullname][id][profileNum] = {}
_G[savedVarsName][fullname][id][profileNum] = mod.Options
end
self:AddMsg(DBM_CORE_ALLMOD_DEFAULT_LOADED)
-- update gui if showing
if DBM_GUI and DBM_GUI.currentViewing and DBM_GUI_OptionsFrame:IsShown() then
DBM_GUI_OptionsFrame:DisplayFrame(DBM_GUI.currentViewing)
end
end
function DBM:LoadModDefaultOption(mod)
-- mod must be table
if not mod then return end
-- prevent error
if not currentSpecID or not currentSpecGroup then
self:SetCurrentSpecInfo()
end
-- variable init
local savedVarsName = (mod.modId):gsub("-", "").."_AllSavedVars"
local fullname = playerName.."-"..playerRealm
local profileNum = playerLevel > 9 and DBM_UseDualProfile and currentSpecGroup or 0
-- prevent nil table error
if not _G[savedVarsName] then _G[savedVarsName] = {} end
if not _G[savedVarsName][fullname] then _G[savedVarsName][fullname] = {} end
if not _G[savedVarsName][fullname][mod.id] then _G[savedVarsName][fullname][mod.id] = {} end
-- do load default
local defaultOptions = {}
for option, optionValue in pairs(mod.DefaultOptions) do
if type(optionValue) == "table" then
optionValue = optionValue.value
elseif type(optionValue) == "string" then
optionValue = mod:GetRoleFlagValue(optionValue)
end
defaultOptions[option] = optionValue
end
mod.Options = {}
mod.Options = defaultOptions
_G[savedVarsName][fullname][mod.id][profileNum] = {}
_G[savedVarsName][fullname][mod.id][profileNum] = mod.Options
self:AddMsg(DBM_CORE_MOD_DEFAULT_LOADED)
-- update gui if showing
if DBM_GUI and DBM_GUI.currentViewing and DBM_GUI_OptionsFrame:IsShown() then
DBM_GUI_OptionsFrame:DisplayFrame(DBM_GUI.currentViewing)
end
end
function DBM:CopyAllModOption(modId, sourceName, sourceProfile)
-- modId is string like "DBM-Highmaul"
if not modId or not sourceName or not sourceProfile or not DBM.ModLists[modId] then return end
-- prevent error
if not currentSpecID or not currentSpecGroup then
self:SetCurrentSpecInfo()
end
-- variable init
local savedVarsName = modId:gsub("-", "").."_AllSavedVars"
local targetName = playerName.."-"..playerRealm
local targetProfile = playerLevel > 9 and DBM_UseDualProfile and currentSpecGroup or 0
-- do not copy setting itself
if targetName == sourceName and targetProfile == sourceProfile then
self:AddMsg(DBM_CORE_MPROFILE_COPY_SELF_ERROR)
return
end
-- prevent nil table error
if not _G[savedVarsName] then _G[savedVarsName] = {} end
-- check source is exist
if not _G[savedVarsName][sourceName] then
self:AddMsg(DBM_CORE_MPROFILE_COPY_S_ERROR)
return
end
local targetOptions = _G[savedVarsName][targetName] or {}
for i, id in ipairs(self.ModLists[modId]) do
-- check source is exist
if not _G[savedVarsName][sourceName][id] then
self:AddMsg(DBM_CORE_MPROFILE_COPY_S_ERROR)
return
end
if not _G[savedVarsName][sourceName][id][sourceProfile] then
self:AddMsg(DBM_CORE_MPROFILE_COPY_S_ERROR)
return
end
-- prevent nil table error
if not _G[savedVarsName][targetName][id] then _G[savedVarsName][targetName][id] = {} end
-- copy table
_G[savedVarsName][targetName][id][targetProfile] = {}--clear before copy
_G[savedVarsName][targetName][id][targetProfile] = _G[savedVarsName][sourceName][id][sourceProfile]
--check new option
local mod = self:GetModByName(id)
for option, optionValue in pairs(mod.Options) do
if _G[savedVarsName][targetName][id][targetProfile][option] == nil then
_G[savedVarsName][targetName][id][targetProfile][option] = optionValue
end
end
-- apply to options table
mod.Options = {}
mod.Options = _G[savedVarsName][targetName][id][targetProfile]
end
if targetProfile > 0 then
_G[savedVarsName][targetName]["talent"..targetProfile] = currentSpecName
end
self:AddMsg(DBM_CORE_MPROFILE_COPY_SUCCESS:format(sourceName, sourceProfile))
-- update gui if showing
if DBM_GUI and DBM_GUI.currentViewing and DBM_GUI_OptionsFrame:IsShown() then
DBM_GUI_OptionsFrame:DisplayFrame(DBM_GUI.currentViewing)
end
end
function DBM:CopyAllModTypeOption(modId, sourceName, sourceProfile, Type)
-- modId is string like "DBM-Highmaul"
if not modId or not sourceName or not sourceProfile or not self.ModLists[modId] or not Type then return end
-- prevent error
if not currentSpecID or not currentSpecGroup then
self:SetCurrentSpecInfo()
end
-- variable init
local savedVarsName = modId:gsub("-", "").."_AllSavedVars"
local targetName = playerName.."-"..playerRealm
local targetProfile = playerLevel > 9 and DBM_UseDualProfile and currentSpecGroup or 0
-- do not copy setting itself
if targetName == sourceName and targetProfile == sourceProfile then
self:AddMsg(DBM_CORE_MPROFILE_COPYS_SELF_ERROR)
return
end
-- prevent nil table error
if not _G[savedVarsName] then _G[savedVarsName] = {} end
-- check source is exist
if not _G[savedVarsName][sourceName] then
self:AddMsg(DBM_CORE_MPROFILE_COPYS_S_ERROR)
return
end
local targetOptions = _G[savedVarsName][targetName] or {}
for i, id in ipairs(self.ModLists[modId]) do
-- check source is exist
if not _G[savedVarsName][sourceName][id] then
self:AddMsg(DBM_CORE_MPROFILE_COPYS_S_ERROR)
return
end
if not _G[savedVarsName][sourceName][id][sourceProfile] then
self:AddMsg(DBM_CORE_MPROFILE_COPYS_S_ERROR)
return
end
-- prevent nil table error
if not _G[savedVarsName][targetName][id] then _G[savedVarsName][targetName][id] = {} end
-- copy table
for option, optionValue in pairs(_G[savedVarsName][sourceName][id][sourceProfile]) do
if option:find(Type) then
_G[savedVarsName][targetName][id][targetProfile][option] = optionValue
end
end
-- apply to options table
local mod = self:GetModByName(id)
mod.Options = {}
mod.Options = _G[savedVarsName][targetName][id][targetProfile]
end
if targetProfile > 0 then
_G[savedVarsName][targetName]["talent"..targetProfile] = currentSpecName
end
self:AddMsg(DBM_CORE_MPROFILE_COPYS_SUCCESS:format(sourceName, sourceProfile))
-- update gui if showing
if DBM_GUI and DBM_GUI.currentViewing and DBM_GUI_OptionsFrame:IsShown() then
DBM_GUI_OptionsFrame:DisplayFrame(DBM_GUI.currentViewing)
end
end
function DBM:DeleteAllModOption(modId, name, profile)
-- modId is string like "DBM-Highmaul"
if not modId or not name or not profile or not self.ModLists[modId] then return end
-- prevent error
if not currentSpecID or not currentSpecGroup then
self:SetCurrentSpecInfo()
end
-- variable init
local savedVarsName = modId:gsub("-", "").."_AllSavedVars"
local fullname = playerName.."-"..playerRealm
local profileNum = playerLevel > 9 and DBM_UseDualProfile and currentSpecGroup or 0
-- cannot delete current profile.
if fullname == name and profileNum == profile then
self:AddMsg(DBM_CORE_MPROFILE_DELETE_SELF_ERROR)
return
end
-- prevent nil table error
if not _G[savedVarsName] then _G[savedVarsName] = {} end
if not _G[savedVarsName][name] then
self:AddMsg(DBM_CORE_MPROFILE_DELETE_S_ERROR)
return
end
for i, id in ipairs(self.ModLists[modId]) do
-- prevent nil table error
if not _G[savedVarsName][name][id] then
self:AddMsg(DBM_CORE_MPROFILE_DELETE_S_ERROR)
return
end
-- delete
_G[savedVarsName][name][id][profile] = nil
end
_G[savedVarsName][name]["talent"..profile] = nil
self:AddMsg(DBM_CORE_MPROFILE_DELETE_SUCCESS:format(name, profile))
end
function DBM:ClearAllStats(modId)
-- modId is string like "DBM-Highmaul"
if not modId or not self.ModLists[modId] then return end
-- variable init
local savedStatsName = modId:gsub("-", "").."_SavedStats"
-- prevent nil table error
if not _G[savedStatsName] then _G[savedStatsName] = {} end
for i, id in ipairs(self.ModLists[modId]) do
local mod = self:GetModByName(id)
-- prevent nil table error
local defaultStats = {}
defaultStats.normalKills = 0
defaultStats.normalPulls = 0
defaultStats.heroicKills = 0
defaultStats.heroicPulls = 0
defaultStats.challengeKills = 0
defaultStats.challengePulls = 0
defaultStats.challengeBestRank = 0
defaultStats.mythicKills = 0
defaultStats.mythicPulls = 0
defaultStats.normal25Kills = 0
defaultStats.normal25Kills = 0
defaultStats.normal25Pulls = 0
defaultStats.heroic25Kills = 0
defaultStats.heroic25Pulls = 0
defaultStats.lfr25Kills = 0
defaultStats.lfr25Pulls = 0
defaultStats.timewalkerKills = 0
defaultStats.timewalkerPulls = 0
mod.stats = {}
mod.stats = defaultStats
_G[savedStatsName][id] = {}
_G[savedStatsName][id] = defaultStats
end
self:AddMsg(DBM_CORE_ALLMOD_STATS_RESETED)
DBM_GUI:UpdateModList()
end
do
function loadOptions(self)
--init
if not DBM_AllSavedOptions then DBM_AllSavedOptions = {} end
usedProfile = DBM_UsedProfile or usedProfile
if not usedProfile or (usedProfile ~= "Default" and not DBM_AllSavedOptions[usedProfile]) then
-- DBM.Option is not loaded. so use print function
print(DBM_CORE_PROFILE_NOT_FOUND)
usedProfile = "Default"
end
DBM_UsedProfile = usedProfile
--migrate old options
if DBM_SavedOptions and not DBM_AllSavedOptions[usedProfile] then
DBM_AllSavedOptions[usedProfile] = DBM_SavedOptions
end
self.Options = DBM_AllSavedOptions[usedProfile] or {}
dbmIsEnabled = true
self:AddDefaultOptions(self.Options, self.DefaultOptions)
DBM_AllSavedOptions[usedProfile] = self.Options
-- force enable dual profile (change default)
if DBM_CharSavedRevision < 12976 then
if playerClass ~= "MAGE" and playerClass ~= "WARLOCK" and playerClass ~= "ROGUE" then
DBM_UseDualProfile = true
end
end
DBM_CharSavedRevision = self.Revision
-- load special warning options
self:UpdateWarningOptions()
self:UpdateSpecialWarningOptions()
if self.Options.CoreSavedRevision < 16970 then
if self.Options.SpecialWarningSound3 == "Sound\\Creature\\KilJaeden\\KILJAEDEN02.ogg" then self.Options.SpecialWarningSound3 = self.DefaultOptions.SpecialWarningSound3 end
end
self.Options.CoreSavedRevision = self.Revision
end
end
do
local lastLFGAlert = 0
function DBM:LFG_ROLE_CHECK_SHOW()
if not UnitIsGroupLeader("player") and self.Options.LFDEnhance and GetTime() - lastLFGAlert > 5 then
self:FlashClientIcon()
self:PlaySoundFile("Sound\\interface\\levelup2.ogg", true)--Because regular sound uses SFX channel which is too low of volume most of time
lastLFGAlert = GetTime()
end
end
end
function DBM:LFG_PROPOSAL_SHOW()
if self.Options.ShowQueuePop and not self.Options.DontShowBossTimers then
self.Bars:CreateBar(40, DBM_LFG_INVITE, "Interface\\Icons\\Spell_Holy_BorrowedTime")
fireEvent("DBM_TimerStart", "DBMLFGTimer", DBM_LFG_INVITE, 40, "Interface\\Icons\\Spell_Holy_BorrowedTime", "extratimer", nil, 0)
end
if self.Options.LFDEnhance then
self:FlashClientIcon()
self:PlaySoundFile("Sound\\interface\\levelup2.ogg", true)--Because regular sound uses SFX channel which is too low of volume most of time
end
end
function DBM:LFG_PROPOSAL_FAILED()
self.Bars:CancelBar(DBM_LFG_INVITE)
fireEvent("DBM_TimerStop", "DBMLFGTimer")
end
function DBM:LFG_PROPOSAL_SUCCEEDED()
self.Bars:CancelBar(DBM_LFG_INVITE)
fireEvent("DBM_TimerStop", "DBMLFGTimer")
end
function DBM:READY_CHECK()
if self.Options.RLReadyCheckSound then--readycheck sound, if ora3 not installed (bad to have 2 mods do it)
self:FlashClientIcon()
if not BINDING_HEADER_oRA3 then
self:PlaySoundFile("Sound\\interface\\levelup2.ogg", true)--Because regular sound uses SFX channel which is too low of volume most of time
end
end
self:TransitionToDungeonBGM(false, true)
self:Schedule(4, self.TransitionToDungeonBGM, self)
end
function DBM:PLAYER_SPECIALIZATION_CHANGED()
local lastSpecID = currentSpecID
self:SetCurrentSpecInfo()
if currentSpecID ~= lastSpecID then--Don't fire specchanged unless spec actually has changed.
self:SpecChanged()
if IsInGroup() then
self:RoleCheck(false)
end
end
end
do
local function AcceptPartyInvite()
AcceptGroup()
for i=1, STATICPOPUP_NUMDIALOGS do
local whichDialog = _G["StaticPopup"..i].which
if whichDialog == "PARTY_INVITE" or whichDialog == "PARTY_INVITE_XREALM" then
_G["StaticPopup"..i].inviteAccepted = 1
StaticPopup_Hide(whichDialog)
break
end
end
end
function DBM:PARTY_INVITE_REQUEST(sender)
--First off, if you are in queue for something, lets not allow guildies or friends boot you from it.
if IsInInstance() or GetLFGMode(1) or GetLFGMode(2) or GetLFGMode(3) or GetLFGMode(4) or GetLFGMode(5) then return end
--First check realID
if self.Options.AutoAcceptFriendInvite then
local _, numBNetOnline = BNGetNumFriends()
for i = 1, numBNetOnline do
local presenceID, _, _, _, _, _, _, isOnline = BNGetFriendInfo(i)
local friendIndex = BNGetFriendIndex(presenceID)--Check if they are on more than one client at once (very likely with new launcher)
for i=1, BNGetNumFriendGameAccounts(friendIndex) do
local _, toonName, client = BNGetFriendGameAccountInfo(friendIndex, i)
if toonName and client == BNET_CLIENT_WOW then--Check if toon name exists and if client is wow. If yes to both, we found right client
if toonName == sender then--Now simply see if this is sender
AcceptPartyInvite()
return
end
end
end
end
-- Check regular non-BNet friends
local nf = GetNumFriends()
for i = 1, nf do
local toonName = GetFriendInfo(i)
if toonName == sender then
AcceptPartyInvite()
return
end
end
end
--Second check guildies
if self.Options.AutoAcceptGuildInvite then
local totalMembers, numOnlineGuildMembers, numOnlineAndMobileMembers = GetNumGuildMembers()
local scanTotal = GetGuildRosterShowOffline() and totalMembers or numOnlineAndMobileMembers
for i=1, scanTotal do
--At this time, it's not easy to tell an officer from a non officer
--since a guild might have ranks 1-3 or even 1-4 be officers/leader while another might only be 1-2
--therefor, this feature is just a "yes/no" for if sender is a guildy
local name, rank, rankIndex = GetGuildRosterInfo(i)
if not name then break end
name = Ambiguate(name, "none")
if sender == name then
AcceptPartyInvite()
return
end
end
end
end
end
function DBM:UPDATE_BATTLEFIELD_STATUS()
for i = 1, 2 do
if GetBattlefieldStatus(i) == "confirm" then
if self.Options.ShowQueuePop and not self.Options.DontShowBossTimers then
queuedBattlefield[i] = select(2, GetBattlefieldStatus(i))
self.Bars:CreateBar(85, queuedBattlefield[i], "Interface\\Icons\\Spell_Holy_BorrowedTime") -- need to confirm the timer
fireEvent("DBM_TimerStart", "DBMBFSTimer", queuedBattlefield[i], 85, "Interface\\Icons\\Spell_Holy_BorrowedTime", "extratimer", nil, 0)
end
if self.Options.LFDEnhance then
self:PlaySoundFile("Sound\\interface\\levelup2.ogg", true)--Because regular sound uses SFX channel which is too low of volume most of time
end
elseif queuedBattlefield[i] then
self.Bars:CancelBar(queuedBattlefield[i])
fireEvent("DBM_TimerStop", "DBMBFSTimer")
queuedBattlefield[i] = nil
end
end
end
function DBM:SCENARIO_CRITERIA_UPDATE()
local _, currentStage, numStages = C_Scenario.GetInfo()
if #inCombat > 0 and currentStage > numStages and C_Scenario.IsInScenario() then
for i = #inCombat, 1, -1 do
local v = inCombat[i]
if v.inScenario then
self:EndCombat(v)
end
end
end
end
--------------------------------
-- Load Boss Mods on Demand --
--------------------------------
do
local classicZones = {[509]=true,[531]=true,[469]=true,[409]=true,}
local bcZones = {[564]=true,[534]=true,[532]=true,[565]=true,[540]=true,[558]=true,[556]=true,[555]=true,[542]=true,[546]=true,[545]=true,[547]=true,[553]=true,[554]=true,[552]=true,[557]=true,[269]=true,[560]=true,[543]=true,[585]=true,[548]=true,[580]=true,[550]=true}
local wrathZones = {[615]=true,[724]=true,[649]=true,[616]=true,[631]=true,[533]=true,[249]=true,[619]=true,[601]=true,[595]=true,[600]=true,[604]=true,[602]=true,[599]=true,[576]=true,[578]=true,[574]=true,[575]=true,[608]=true,[658]=true,[632]=true,[668]=true,[650]=true,[603]=true,[624]=true}
local cataZones = {[757]=true,[671]=true,[669]=true,[967]=true,[720]=true,[951]=true,[755]=true,[645]=true,[36]=true,[670]=true,[644]=true,[33]=true,[643]=true,[725]=true,[657]=true,[309]=true,[859]=true,[568]=true,[938]=true,[940]=true,[939]=true,[646]=true,[754]=true}
local mopZones = {[1009]=true,[1008]=true,[960]=true,[961]=true,[959]=true,[962]=true,[994]=true,[1011]=true,[1007]=true,[1001]=true,[1004]=true,[1136]=true,[996]=true,[1098]=true}
local wodZones = {[1205]=true,[1448]=true,[1182]=true,[1175]=true,[1208]=true,[1195]=true,[1279]=true,[1176]=true,[1209]=true,[1358]=true}
local challengeScenarios = {[1148]=true,[1698]=true,[1710]=true,[1703]=true,[1702]=true,[1684]=true,[1673]=true,[1616]=true}
function DBM:CheckAvailableMods()
if BigWigs then return end--If they are running two boss mods at once, lets assume they are only using DBM for a specific feature and not nag
local timeWalking = difficultyIndex == 24 or difficultyIndex == 33 or false
if (classicZones[LastInstanceMapID] or bcZones[LastInstanceMapID]) and (timeWalking or playerLevel < 71) and not GetAddOnInfo("DBM-BlackTemple") then
AddMsg(self, DBM_CORE_MOD_AVAILABLE:format("DBM BC/Vanilla mods"))
elseif wrathZones[LastInstanceMapID] and (timeWalking or playerLevel < 81) and not GetAddOnInfo("DBM-Ulduar") then
AddMsg(self, DBM_CORE_MOD_AVAILABLE:format("DBM Wrath of the Lich King mods"))
elseif cataZones[LastInstanceMapID] and (timeWalking or playerLevel < 86) and not GetAddOnInfo("DBM-Party-Cataclysm") then
AddMsg(self, DBM_CORE_MOD_AVAILABLE:format("DBM Cataclysm mods"))
elseif mopZones[LastInstanceMapID] and (timeWalking or playerLevel < 91) and not GetAddOnInfo("DBM-Party-MoP") then
AddMsg(self, DBM_CORE_MOD_AVAILABLE:format("DBM Mists of Pandaria mods"))
elseif wodZones[LastInstanceMapID] and (timeWalking or playerLevel < 101) and not GetAddOnInfo("DBM-MC") then
AddMsg(self, DBM_CORE_MOD_AVAILABLE:format("DBM Warlords of Draenor mods"))
elseif challengeScenarios[LastInstanceMapID] and not GetAddOnInfo("DBM-Challenges") then
AddMsg(self, DBM_CORE_MOD_AVAILABLE:format("DBM-Challenges"))
end
end
function DBM:TransitionToDungeonBGM(force, cleanup)
if cleanup then--Runs on zone change (first load delay) and combat end
self:Unschedule(self.TransitionToDungeonBGM)
if self.Options.tempMusicSetting then
SetCVar("Sound_EnableMusic", self.Options.tempMusicSetting)
self.Options.tempMusicSetting = nil
DBM:Debug("Restoring Sound_EnableMusic CVAR")
end
if self.Options.musicPlaying then--Primarily so DBM doesn't call StopMusic unless DBM is one that started it. We don't want to screw with other addons
StopMusic()
self.Options.musicPlaying = nil
DBM:Debug("Stopping music")
end
fireEvent("DBM_MusicStop", "ZoneOrCombatEndTransition")
return
end
if LastInstanceType ~= "raid" and LastInstanceType ~= "party" and not force then return end
fireEvent("DBM_MusicStart", "RaidOrDungeon")
if self.Options.EventSoundDungeonBGM and self.Options.EventSoundDungeonBGM ~= "None" and self.Options.EventSoundDungeonBGM ~= "" and not (self.Options.EventDungMusicMythicFilter and (savedDifficulty == "mythic" or savedDifficulty == "challenge")) then
if not self.Options.tempMusicSetting then
self.Options.tempMusicSetting = tonumber(GetCVar("Sound_EnableMusic"))
if self.Options.tempMusicSetting == 0 then
SetCVar("Sound_EnableMusic", 1)
else
self.Options.tempMusicSetting = nil--Don't actually need it
end
end
local path = "MISSING"
if self.Options.EventSoundDungeonBGM == "Random" then
local usedTable = self.Options.EventSoundMusicCombined and DBM.Music or DBM.DungeonMusic
local random = fastrandom(3, #usedTable)
path = usedTable[random].value
else
path = self.Options.EventSoundDungeonBGM
end
PlayMusic(path)
self.Options.musicPlaying = true
DBM:Debug("Starting Dungeon music with file: "..path)
end
end
local function SecondaryLoadCheck(self)
local _, instanceType, difficulty, _, _, _, _, mapID, instanceGroupSize = GetInstanceInfo()
if not savedDifficulty then
savedDifficulty, difficultyText = self:GetCurrentInstanceDifficulty()
end
self:Debug("Instance Check fired with mapID "..mapID.." and difficulty "..difficulty, 2)
if LastInstanceMapID == mapID then
self:TransitionToDungeonBGM()
self:Debug("No action taken because mapID hasn't changed since last check", 2)
return
end--ID hasn't changed, don't waste cpu doing anything else (example situation, porting into garrosh stage 4 is a loading screen)
LastInstanceMapID = mapID
LastGroupSize = instanceGroupSize
difficultyIndex = difficulty
if instanceType == "none" or C_Garrison:IsOnGarrisonMap() then
LastInstanceType = "none"
if not targetEventsRegistered then
self:RegisterShortTermEvents("UPDATE_MOUSEOVER_UNIT")
targetEventsRegistered = true
end
else
LastInstanceType = instanceType
if targetEventsRegistered then
self:UnregisterShortTermEvents()
targetEventsRegistered = false
end
if savedDifficulty == "worldboss" then
for i = #inCombat, 1, -1 do
self:EndCombat(inCombat[i], true)
end
end
end
-- LoadMod
self:LoadModsOnDemand("mapId", mapID)
if not self.Options.DontShowReminders then
self:CheckAvailableMods()
end
if DBM:HasMapRestrictions() then
DBM.Arrow:Hide()
DBMHudMap:Disable()
if DBM.RangeCheck:IsRadarShown() then
DBM.RangeCheck:Hide(true)
end
end
end
--Faster and more accurate loading for instances, but useless outside of them
function DBM:LOADING_SCREEN_DISABLED()
self.Bars:CancelBar(DBM_LFG_INVITE)--Disable bar here since LFG_PROPOSAL_SUCCEEDED seems broken right now
fireEvent("DBM_TimerStop", "DBMLFGTimer")
timerRequestInProgress = false
self:Debug("LOADING_SCREEN_DISABLED fired")
self:Unschedule(SecondaryLoadCheck)
--SecondaryLoadCheck(self)
self:Schedule(1, SecondaryLoadCheck, self)--Now delayed by one second to work around an issue on beta where spec info isn't available yet on reloadui
self:TransitionToDungeonBGM(false, true)
self:Schedule(5, SecondaryLoadCheck, self)
if DBM:HasMapRestrictions() then
DBM.Arrow:Hide()
DBMHudMap:Disable()
if DBM.RangeCheck:IsRadarShown() then
DBM.RangeCheck:Hide(true)
end
end
end
function DBM:LoadModsOnDemand(checkTable, checkValue)
self:Debug("LoadModsOnDemand fired")
for i, v in ipairs(self.AddOns) do
local modTable = v[checkTable]
local enabled = GetAddOnEnableState(playerName, v.modId)
--self:Debug(v.modId.." is "..enabled, 2)
if not IsAddOnLoaded(v.modId) and modTable and checkEntry(modTable, checkValue) then
if enabled ~= 0 then
self:LoadMod(v)
else
if not self.Options.DontShowReminders then
self:AddMsg(DBM_CORE_LOAD_MOD_DISABLED:format(v.name))
end
end
end
end
self:ScenarioCheck()--Do not filter. Because ScenarioCheck function includes filter.
end
end
--Scenario mods
function DBM:ScenarioCheck()
if dbmIsEnabled and combatInfo[LastInstanceMapID] then
for i, v in ipairs(combatInfo[LastInstanceMapID]) do
if (v.type == "scenario") and checkEntry(v.msgs, LastInstanceMapID) then
self:StartCombat(v.mod, 0, "LOADING_SCREEN_DISABLED")
end
end
end
end
function DBM:LoadMod(mod, force)
if type(mod) ~= "table" then
self:Debug("LoadMod failed because mod table not valid")
return false
end
if mod.isWorldBoss and not IsInInstance() and not force then
return
end--Don't load world boss mod this way.
if mod.minRevision > self.Revision then
if self:AntiSpam(60, "VER_MISMATCH") then--Throttle message in case person keeps trying to load mod (or it's a world boss player keeps targeting
self:AddMsg(DBM_CORE_LOAD_MOD_VER_MISMATCH:format(mod.name))
end
return
end
if mod.minExpansion > GetExpansionLevel() then
self:AddMsg(DBM_CORE_LOAD_MOD_EXP_MISMATCH:format(mod.name))
return
end
if not currentSpecID then
self:SetCurrentSpecInfo()
end
if not difficultyIndex then -- prevent error in EJ_SetDifficulty if not yet set
savedDifficulty, difficultyText, difficultyIndex, LastGroupSize, difficultyModifier = DBM:GetCurrentInstanceDifficulty()
end
EJ_SetDifficulty(difficultyIndex)--Work around blizzard crash bug where other mods (like Boss) screw with Ej difficulty value, which makes EJ_GetSectionInfo crash the game when called with invalid difficulty index set.
self:Debug("LoadAddOn should have fired for "..mod.name, 2)
local loaded, reason = LoadAddOn(mod.modId)
if not loaded then
if reason then
self:AddMsg(DBM_CORE_LOAD_MOD_ERROR:format(tostring(mod.name), tostring(_G["ADDON_"..reason or ""])))
else
self:Debug("LoadAddOn failed and did not give reason")
end
return false
else
self:Debug("LoadAddOn should have succeeded for "..mod.name, 2)
self:AddMsg(DBM_CORE_LOAD_MOD_SUCCESS:format(tostring(mod.name)))
self:LoadModOptions(mod.modId, InCombatLockdown(), true)
if DBM_GUI then
DBM_GUI:UpdateModList()
end
if LastInstanceType ~= "pvp" and #inCombat == 0 and IsInGroup() then--do timer recovery only mod load
if not timerRequestInProgress then
timerRequestInProgress = true
-- Request timer to 3 person to prevent failure.
self:Unschedule(self.RequestTimers)
self:Schedule(7, self.RequestTimers, self, 1)
self:Schedule(10, self.RequestTimers, self, 2)
self:Schedule(13, self.RequestTimers, self, 3)
C_TimerAfter(15, function() timerRequestInProgress = false end)
self:GROUP_ROSTER_UPDATE(true)
end
end
if not InCombatLockdown() and not UnitAffectingCombat("player") and not IsFalling() then--We loaded in combat but still need to avoid garbage collect in combat
collectgarbage("collect")
end
return true
end
end
do
local function loadModByUnit(uId)
if not uId then
uId = "mouseover"
else
uId = uId.."target"
end
if IsInInstance() or not UnitIsFriend("player", uId) and UnitIsDead("player") or UnitIsDead(uId) then return end--If you're in an instance no reason to waste cpu. If THE BOSS dead, no reason to load a mod for it. To prevent rare lua error, needed to filter on player dead.
local guid = UnitGUID(uId)
if guid and DBM:IsCreatureGUID(guid) then
local cId = DBM:GetCIDFromGUID(guid)
for bosscId, addon in pairs(loadcIds) do
local enabled = GetAddOnEnableState(playerName, addon)
if cId and bosscId and cId == bosscId and not IsAddOnLoaded(addon) and enabled ~= 0 then
for i, v in ipairs(DBM.AddOns) do
if v.modId == addon then
DBM:LoadMod(v, true)
break
end
end
end
end
end
end
--Loading routeens hacks for world bosses based on target or mouseover.
function DBM:UPDATE_MOUSEOVER_UNIT()
loadModByUnit()
end
function DBM:UNIT_TARGET_UNFILTERED(uId)
if targetEventsRegistered then--Allow outdoor mod loading
loadModByUnit(uId)
end
--Debug options for seeing where BossUnitTargetScanner can be used.
if (self.Options.DebugLevel > 2 or (Transcriptor and Transcriptor:IsLogging())) and (uId == "boss1" or uId == "boss2" or uId == "boss3" or uId == "boss4" or uId == "boss5") then
local targetName = uId == "boss1" and UnitName("boss1target") or uId == "boss2" and UnitName("boss2target") or uId == "boss3" and UnitName("boss3target") or uId == "boss4" and UnitName("boss4target") or uId == "boss5" and UnitName("boss5target") or "nil"
self:Debug(uId.." changed targets to "..targetName)
end
--Active BossUnitTargetScanner
if targetMonitor and UnitExists(uId.."target") and UnitPlayerOrPetInRaid(uId.."target") then
self:Debug("targetMonitor exists, target exists", 2)
local modId, unitId, returnFunc = string.split("\t", targetMonitor)
self:Debug("targetMonitor: "..modId..", "..unitId..", "..returnFunc, 2)
local tanking, status = UnitDetailedThreatSituation(unitId, unitId.."target")--Tanking may return 0 if npc is temporarily looking at an NPC (IE fracture) but status will still be 3 on true tank
if tanking or (status == 3) then
self:Debug("targetMonitor ending, it's a tank", 2)
return
end--It's a tank/highest threat, this method ignores tanks
local mod = self:GetModByName(modId)
self:Debug("targetMonitor success, a valid target that's not a tank", 2)
mod[returnFunc](mod, self:GetUnitFullName(unitId.."target"), unitId.."target", unitId)--Return results to warning function with all variables.
targetMonitor = nil
end
end
end
-----------------------------
-- Handle Incoming Syncs --
-----------------------------
do
local function checkForActualPull()
if #inCombat == 0 then
DBM:StopLogging()
end
end
local syncHandlers = {}
local whisperSyncHandlers = {}
-- DBM uses the following prefixes since 4.1 as pre-4.1 sync code is going to be incompatible anways, so this is the perfect opportunity to throw away the old and long names
-- M = Mod
-- C = Combat start
-- GC = Guild Combat Start
-- IS = Icon set info
-- K = Kill
-- H = Hi!
-- V = Incoming version information
-- U = User Timer
-- PT = Pull Timer (for sound effects, the timer itself is still sent as a normal timer)
-- RT = Request Timers
-- CI = Combat Info
-- TI = Timer Info
-- IR = Instance Info Request
-- IRE = Instance Info Requested Ended/Canceled
-- II = Instance Info
-- WBE = World Boss engage info
-- WBD = World Boss defeat info
-- DSW = Disable Send Whisper
-- NS = Note Share
syncHandlers["M"] = function(sender, mod, revision, event, ...)
mod = DBM:GetModByName(mod or "")
if mod and event and revision then
revision = tonumber(revision) or 0
mod:ReceiveSync(event, sender, revision, ...)
end
end
syncHandlers["NS"] = function(sender, modid, modvar, text, abilityName)
if sender == playerName then return end
if DBM.Options.BlockNoteShare or InCombatLockdown() or UnitAffectingCombat("player") or IsFalling() or DBM:GetRaidRank(sender) == 0 then return end
if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and IsInInstance() then return end
--^^You are in LFR, BG, or LFG. Block note syncs. They shouldn't be sendable, but in case someone edits DBM^^
local mod = DBM:GetModByName(modid or "")
local ability = abilityName or DBM_CORE_UNKNOWN
if mod and modvar and text and text ~= "" then
if DBM:AntiSpam(5, modvar) then--Don't allow calling same note more than once per 5 seconds
DBM:AddMsg(DBM_CORE_NOTE_SHARE_SUCCESS:format(sender, abilityName))
DBM:ShowNoteEditor(mod, modvar, ability, text, sender)
else
DBM:Debug(sender.." is attempting to send too many notes so notes are being throttled")
end
else
DBM:AddMsg(DBM_CORE_NOTE_SHARE_FAIL:format(sender, ability))
end
end
syncHandlers["C"] = function(sender, delay, mod, modRevision, startHp, dbmRevision, modHFRevision)
if not dbmIsEnabled or sender == playerName then return end
if LastInstanceType == "pvp" then return end
if LastInstanceType == "none" and (not UnitAffectingCombat("player") or #inCombat > 0) then--world boss
local senderuId = DBM:GetRaidUnitId(sender)
if not senderuId then return end--Should never happen, but just in case. If happens, MANY "C" syncs are sent. losing 1 no big deal.
local _, _, _, playerZone = UnitPosition("player")
local _, _, _, senderZone = UnitPosition(senderuId)
if playerZone ~= senderZone then return end--not same zone
local range = DBM.RangeCheck:GetDistance("player", senderuId)--Same zone, so check range
if not range or range > 120 then return end
end
if not cSyncSender[sender] then
cSyncSender[sender] = true
cSyncReceived = cSyncReceived + 1
if cSyncReceived > 2 then -- need at least 3 sync to combat start. (for security)
local lag = select(4, GetNetStats()) / 1000
delay = tonumber(delay or 0) or 0
mod = DBM:GetModByName(mod or "")
modRevision = tonumber(modRevision or 0) or 0
dbmRevision = tonumber(dbmRevision or 0) or 0
modHFRevision = tonumber(modHFRevision or 0) or 0
startHp = tonumber(startHp or -1) or -1
if dbmRevision < 10481 then return end
if mod and delay and (not mod.zones or mod.zones[LastInstanceMapID]) and (not mod.minSyncRevision or modRevision >= mod.minSyncRevision) then
DBM:StartCombat(mod, delay + lag, "SYNC from - "..sender, true, startHp)
if (mod.revision < modHFRevision) and (mod.revision > 1000) then--mod.revision because we want to compare to OUR revision not senders
if DBM:AntiSpam(3, "HOTFIX") and not DBM.Options.DontShowReminders then
if DBM.HighestRelease < modHFRevision then--There is a newer RELEASE version of DBM out that has this mods fixes
showConstantReminder = 2
DBM:AddMsg(DBM_CORE_UPDATEREMINDER_HOTFIX)
else--This mods fixes are in an alpha version
DBM:AddMsg(DBM_CORE_UPDATEREMINDER_HOTFIX_ALPHA)
end
end
end
end
end
end
end
syncHandlers["DSW"] = function(sender)
if (DBM:GetRaidRank(sender) ~= 2 or not IsInGroup()) then return end--If not on group, we're probably sender, don't disable status. IF not leader, someone is trying to spoof this, block that too
statusWhisperDisabled = true
DBM:Debug("Raid leader has disabled status whispers")
end
syncHandlers["DGP"] = function(sender)
if (DBM:GetRaidRank(sender) ~= 2 or not IsInGroup()) then return end--If not on group, we're probably sender, don't disable status. IF not leader, someone is trying to spoof this, block that too
statusGuildDisabled = true
DBM:Debug("Raid leader has disabled guild progress messages")
end
syncHandlers["IS"] = function(sender, guid, ver, optionName)
ver = tonumber(ver)
if ver > (iconSetRevision[optionName] or 0) then--Save first synced version and person, ignore same version. refresh occurs only above version (fastest person)
iconSetRevision[optionName] = ver
iconSetPerson[optionName] = guid
end
if iconSetPerson[optionName] == UnitGUID("player") then--Check if that highest version was from ourself
canSetIcons[optionName] = true
else--Not from self, it means someone with a higher version than us probably sent it
canSetIcons[optionName] = false
end
local name = DBM:GetFullPlayerNameByGUID(iconSetPerson[optionName]) or DBM_CORE_UNKNOWN
DBM:Debug(name.." was elected icon setter for "..optionName, 2)
end
syncHandlers["K"] = function(sender, cId)
if select(2, IsInInstance()) == "pvp" or select(2, IsInInstance()) == "none" then return end
cId = tonumber(cId or "")
if cId then DBM:OnMobKill(cId, true) end
end
syncHandlers["EE"] = function(sender, eId, success, mod, modRevision)
if select(2, IsInInstance()) == "pvp" then return end
eId = tonumber(eId or "")
success = tonumber(success)
mod = DBM:GetModByName(mod or "")
modRevision = tonumber(modRevision or 0) or 0
if mod and eId and success and (not mod.minSyncRevision or modRevision >= mod.minSyncRevision) and not eeSyncSender[sender] then
eeSyncSender[sender] = true
eeSyncReceived = eeSyncReceived + 1
if eeSyncReceived > 2 then -- need at least 3 person to combat end. (for security)
DBM:EndCombat(mod, success == 0)
end
end
end
local dummyMod -- dummy mod for the pull timer
syncHandlers["PT"] = function(sender, timer, lastMapID, target)
if DBM.Options.DontShowUserTimers then return end
local LFGTankException = IsPartyLFG() and UnitGroupRolesAssigned(sender) == "TANK"
if (DBM:GetRaidRank(sender) == 0 and IsInGroup() and not LFGTankException) or select(2, IsInInstance()) == "pvp" or IsEncounterInProgress() then
return
end
if (lastMapID and tonumber(lastMapID) ~= LastInstanceMapID) or (not lastMapID and DBM.Options.DontShowPTNoID) then return end
timer = tonumber(timer or 0)
if timer > 60 then
return
end
if not dummyMod then
local threshold = DBM.Options.PTCountThreshold
local adjustedThreshold = 5
if threshold > 10 then
adjustedThreshold = 10
else
adjustedThreshold = floor(threshold)
end
dummyMod = DBM:NewMod("PullTimerCountdownDummy")
DBM:GetModLocalization("PullTimerCountdownDummy"):SetGeneralLocalization{ name = DBM_CORE_MINIMAP_TOOLTIP_HEADER }
dummyMod.countdown = dummyMod:NewCountdown(0, 0, nil, nil, adjustedThreshold, true)
dummyMod.text = dummyMod:NewAnnounce("%s", 1, "Interface\\Icons\\ability_warrior_offensivestance")
dummyMod.geartext = dummyMod:NewSpecialWarning(" %s ", nil, nil, nil, 3)
end
--Cancel any existing pull timers before creating new ones, we don't want double countdowns or mismatching blizz countdown text (cause you can't call another one if one is in progress)
if not DBM.Options.DontShowPT2 and DBM.Bars:GetBar(DBM_CORE_TIMER_PULL) then
DBM.Bars:CancelBar(DBM_CORE_TIMER_PULL)
fireEvent("DBM_TimerStop", "pull")
end
if not DBM.Options.DontPlayPTCountdown then
dummyMod.countdown:Cancel()
end
if not DBM.Options.DontShowPTCountdownText then
TimerTracker_OnEvent(TimerTracker, "PLAYER_ENTERING_WORLD")--easiest way to nil out timers on TimerTracker frame. This frame just has no actual star/stop functions
end
dummyMod.text:Cancel()
if timer == 0 then return end--"/dbm pull 0" will strictly be used to cancel the pull timer (which is why we let above part of code run but not below)
DBM:FlashClientIcon()
if not DBM.Options.DontShowPT2 then
DBM.Bars:CreateBar(timer, DBM_CORE_TIMER_PULL, "Interface\\Icons\\Spell_Holy_BorrowedTime")
fireEvent("DBM_TimerStart", "pull", DBM_CORE_TIMER_PULL, timer, "Interface\\Icons\\Spell_Holy_BorrowedTime", "utilitytimer", nil, 0)
end
if not DBM.Options.DontPlayPTCountdown then
dummyMod.countdown:Start(timer)
end
if not DBM.Options.DontShowPTCountdownText then
TimerTracker_OnEvent(TimerTracker, "START_TIMER", 2, timer, timer)
end
if not DBM.Options.DontShowPTText then
if target then
dummyMod.text:Show(DBM_CORE_ANNOUNCE_PULL_TARGET:format(target, timer, sender))
dummyMod.text:Schedule(timer, DBM_CORE_ANNOUNCE_PULL_NOW_TARGET:format(target))
else
dummyMod.text:Show(DBM_CORE_ANNOUNCE_PULL:format(timer, sender))
dummyMod.text:Schedule(timer, DBM_CORE_ANNOUNCE_PULL_NOW)
end
end
DBM:StartLogging(timer, checkForActualPull)
if DBM.Options.CheckGear then
local bagilvl, equippedilvl = GetAverageItemLevel()
local difference = bagilvl - equippedilvl
local weapon = GetInventoryItemLink("player", 16)
local fishingPole = false
if weapon then
local _, _, _, _, _, _, type = GetItemInfo(weapon)
if type and type == DBM_CORE_GEAR_FISHING_POLE then
fishingPole = true
end
end
if IsInRaid() and difference >= 40 then
dummyMod.geartext:Show(DBM_CORE_GEAR_WARNING:format(floor(difference)))
elseif IsInRaid() and (not weapon or fishingPole) then
dummyMod.geartext:Show(DBM_CORE_GEAR_WARNING_WEAPON)
end
end
end
do
local dummyMod2 -- dummy mod for the break timer
function breakTimerStart(self, timer, sender)
if not dummyMod2 then
local threshold = DBM.Options.PTCountThreshold
local adjustedThreshold = 5
if threshold > 10 then
adjustedThreshold = 10
else
adjustedThreshold = floor(threshold)
end
dummyMod2 = DBM:NewMod("BreakTimerCountdownDummy")
DBM:GetModLocalization("BreakTimerCountdownDummy"):SetGeneralLocalization{ name = DBM_CORE_MINIMAP_TOOLTIP_HEADER }
dummyMod2.countdown = dummyMod2:NewCountdown(0, 0, nil, nil, adjustedThreshold, true)
dummyMod2.text = dummyMod2:NewAnnounce("%s", 1, "Interface\\Icons\\Spell_Holy_BorrowedTime")
end
--Cancel any existing break timers before creating new ones, we don't want double countdowns or mismatching blizz countdown text (cause you can't call another one if one is in progress)
if not DBM.Options.DontShowPT2 and DBM.Bars:GetBar(DBM_CORE_TIMER_BREAK) then
DBM.Bars:CancelBar(DBM_CORE_TIMER_BREAK)
fireEvent("DBM_TimerStop", "break")
end
if not DBM.Options.DontPlayPTCountdown then
dummyMod2.countdown:Cancel()
end
dummyMod2.text:Cancel()
DBM.Options.tempBreak2 = nil
if timer == 0 then return end--"/dbm break 0" will strictly be used to cancel the break timer (which is why we let above part of code run but not below)
self.Options.tempBreak2 = timer.."/"..time()
if not self.Options.DontShowPT2 then
self.Bars:CreateBar(timer, DBM_CORE_TIMER_BREAK, "Interface\\Icons\\Spell_Holy_BorrowedTime")
fireEvent("DBM_TimerStart", "break", DBM_CORE_TIMER_BREAK, timer, "Interface\\Icons\\Spell_Holy_BorrowedTime", "utilitytimer", nil, 0)
end
if not self.Options.DontPlayPTCountdown then
dummyMod2.countdown:Start(timer)
end
if not self.Options.DontShowPTText then
local hour, minute = GetGameTime()
minute = minute+(timer/60)
if minute >= 60 then
hour = hour + 1
minute = minute - 60
end
minute = floor(minute)
if minute < 10 then
minute = tostring(0 .. minute)
end
dummyMod2.text:Show(DBM_CORE_BREAK_START:format(strFromTime(timer).." ("..hour..":"..minute..")", sender))
if timer/60 > 10 then dummyMod2.text:Schedule(timer - 10*60, DBM_CORE_BREAK_MIN:format(10)) end
if timer/60 > 5 then dummyMod2.text:Schedule(timer - 5*60, DBM_CORE_BREAK_MIN:format(5)) end
if timer/60 > 2 then dummyMod2.text:Schedule(timer - 2*60, DBM_CORE_BREAK_MIN:format(2)) end
if timer/60 > 1 then dummyMod2.text:Schedule(timer - 1*60, DBM_CORE_BREAK_MIN:format(1)) end
dummyMod2.text:Schedule(timer, DBM_CORE_ANNOUNCE_BREAK_OVER:format(hour..":"..minute))
end
C_TimerAfter(timer, function() self.Options.tempBreak2 = nil end)
end
end
syncHandlers["BT"] = function(sender, timer)
if DBM.Options.DontShowUserTimers then return end
timer = tonumber(timer or 0)
if timer > 3600 then return end
if (DBM:GetRaidRank(sender) == 0 and IsInGroup()) or select(2, IsInInstance()) == "pvp" or IsEncounterInProgress() then
return
end
breakTimerStart(DBM, timer, sender)
end
whisperSyncHandlers["BTR3"] = function(sender, timer)
if DBM.Options.DontShowUserTimers or not DBM:GetRaidUnitId(sender) then return end
timer = tonumber(timer or 0)
if timer > 3600 then return end
DBM:Unschedule(DBM.RequestTimers)--IF we got BTR3 sync, then we know immediately RequestTimers was successful, so abort others
if #inCombat >= 1 then return end
if DBM.Bars:GetBar(DBM_CORE_TIMER_BREAK) then return end--Already recovered. Prevent duplicate recovery
breakTimerStart(DBM, timer, sender)
end
local function SendVersion(guild)
if guild then
local message = ("%d\t%s\t%s"):format(DBM.Revision, tostring(DBM.ReleaseRevision), DBM.DisplayVersion)
SendAddonMessage("D4", "GV\t" .. message, "GUILD")
return
end
if DBM.Options.FakeBWVersion then
SendAddonMessage("BigWigs", versionResponseString:format(fakeBWVersion, fakeBWHash), IsInGroup(2) and "INSTANCE_CHAT" or "RAID")
return
end
--(Note, faker isn't to screw with bigwigs nor is theirs to screw with dbm, but rathor raid leaders who don't let people run WTF they want to run)
local VPVersion
local VoicePack = DBM.Options.ChosenVoicePack
if VoicePack ~= "None" then
VPVersion = "/ VP"..VoicePack..": v"..DBM.VoiceVersions[VoicePack]
end
if VPVersion then
sendSync("V", ("%d\t%s\t%s\t%s\t%s\t%s"):format(DBM.Revision, tostring(DBM.ReleaseRevision), DBM.DisplayVersion, GetLocale(), tostring(not DBM.Options.DontSetIcons), VPVersion))
else
sendSync("V", ("%d\t%s\t%s\t%s\t%s"):format(DBM.Revision, tostring(DBM.ReleaseRevision), DBM.DisplayVersion, GetLocale(), tostring(not DBM.Options.DontSetIcons)))
end
end
local function HandleVersion(revision, version, displayVersion, sender, noRaid)
if version > DBM.Revision then -- Update reminder
if #newerVersionPerson < 4 then
if not checkEntry(newerVersionPerson, sender) then
newerVersionPerson[#newerVersionPerson + 1] = sender
DBM:Debug("Newer version detected from "..sender.." : Rev - "..revision..", Ver - "..version..", Rev Diff - "..(revision - DBM.Revision), 3)
end
if #newerVersionPerson == 2 and updateNotificationDisplayed < 2 then--Only requires 2 for update notification.
if DBM.HighestRelease < version then
DBM.HighestRelease = version
end
DBM.NewerVersion = displayVersion
--UGLY hack to get release version number instead of alpha one
if DBM.NewerVersion:find("alpha") then
local temp1, temp2 = string.split(" ", DBM.NewerVersion)--Strip down to just version, no alpha
if temp1 then
local temp3, temp4, temp5 = string.split(".", temp1)--Strip version down to 3 numbers
if temp3 and temp4 and temp5 and tonumber(temp5) then
temp5 = tonumber(temp5)
temp5 = temp5 - 1
temp5 = tostring(temp5)
DBM.NewerVersion = temp3.."."..temp4.."."..temp5
end
end
end
--Find min revision.
updateNotificationDisplayed = 2
--[[ bf@178.com
AddMsg(DBM, DBM_CORE_UPDATEREMINDER_HEADER:match("([^\n]*)"))
AddMsg(DBM, DBM_CORE_UPDATEREMINDER_HEADER:match("\n(.*)"):format(displayVersion, version))
]]
showConstantReminder = 1
elseif not noRaid and #newerVersionPerson == 3 and updateNotificationDisplayed < 3 then--The following code requires at least THREE people to send that higher revision. That should be more than adaquate
--Disable if revision grossly out of date even if not major patch.
if raid[newerVersionPerson[1]] and raid[newerVersionPerson[2]] and raid[newerVersionPerson[3]] then
local revDifference = mmin((raid[newerVersionPerson[1]].revision - DBM.Revision), (raid[newerVersionPerson[2]].revision - DBM.Revision), (raid[newerVersionPerson[3]].revision - DBM.Revision))
if revDifference > 100 then
if updateNotificationDisplayed < 3 then
updateNotificationDisplayed = 3
AddMsg(DBM, DBM_CORE_UPDATEREMINDER_DISABLE)
DBM:Disable(true)
end
end
--Disable if out of date and it's a major patch.
elseif not testBuild and dbmToc < wowTOC then
updateNotificationDisplayed = 3
AddMsg(DBM, DBM_CORE_UPDATEREMINDER_MAJORPATCH)
DBM:Disable(true)
end
end
end
end
if DBM.DisplayVersion:find("alpha") and #newerRevisionPerson < 3 and updateNotificationDisplayed < 2 and (revision - DBM.Revision) > 20 then
if not checkEntry(newerRevisionPerson, sender) then
newerRevisionPerson[#newerRevisionPerson + 1] = sender
DBM:Debug("Newer revision detected from "..sender.." : Rev - "..revision..", Ver - "..version..", Rev Diff - "..(revision - DBM.Revision))
end
if #newerRevisionPerson == 2 and raid[newerRevisionPerson[1]] and raid[newerRevisionPerson[2]] then
local revDifference = mmin((raid[newerRevisionPerson[1]].revision - DBM.Revision), (raid[newerRevisionPerson[2]].revision - DBM.Revision))
if testBuild and revDifference > 5 then
updateNotificationDisplayed = 3
AddMsg(DBM, DBM_CORE_UPDATEREMINDER_DISABLE)
DBM:Disable(true)
else
updateNotificationDisplayed = 2
AddMsg(DBM, DBM_CORE_UPDATEREMINDER_HEADER_ALPHA:format(revDifference))
end
end
end
end
-- TODO: is there a good reason that version information is broadcasted and not unicasted?
syncHandlers["H"] = function(sender)
DBM:Unschedule(SendVersion)--Throttle so we don't needlessly send tons of comms during initial raid invites
DBM:Schedule(3, SendVersion)--Send version if 3 seconds have past since last "Hi" sync
end
syncHandlers["GH"] = function(sender)
DBM:Unschedule(SendVersion, true)--Throttle so we don't needlessly send tons of comms during initial raid invites
DBM:Schedule(3, SendVersion, true)--Send version if 3 seconds have past since last "Hi" sync
end
syncHandlers["BV"] = function(sender, version, hash)--Parsed from bigwigs V7+
if version and raid[sender] then
raid[sender].bwversion = version
raid[sender].bwhash = hash or ""
end
end
syncHandlers["V"] = function(sender, revision, version, displayVersion, locale, iconEnabled, VPVersion)
revision, version = tonumber(revision), tonumber(version)
if revision and version and displayVersion and raid[sender] then
raid[sender].revision = revision
raid[sender].version = version
raid[sender].displayVersion = displayVersion
raid[sender].VPVersion = VPVersion
raid[sender].locale = locale
raid[sender].enabledIcons = iconEnabled or "false"
DBM:Debug("Received version info from "..sender.." : Rev - "..revision..", Ver - "..version..", Rev Diff - "..(revision - DBM.Revision), 3)
if not DBM.Options.DontShowReminders then
HandleVersion(revision, version, displayVersion, sender)
end
end
DBM:GROUP_ROSTER_UPDATE()
end
syncHandlers["GV"] = function(sender, revision, version, displayVersion)
revision, version = tonumber(revision), tonumber(version)
if revision and version and displayVersion then
DBM:Debug("Received G version info from "..sender.." : Rev - "..revision..", Ver - "..version..", Rev Diff - "..(revision - DBM.Revision), 3)
if not DBM.Options.DontShowReminders then
HandleVersion(revision, version, displayVersion, sender, true)
end
end
end
syncHandlers["U"] = function(sender, time, text)
if select(2, IsInInstance()) == "pvp" then return end -- no pizza timers in battlegrounds
if DBM.Options.DontShowUserTimers then return end
if DBM:GetRaidRank(sender) == 0 or difficultyIndex == 7 or difficultyIndex == 17 then return end
if sender == playerName then return end
time = tonumber(time or 0)
text = tostring(text)
if time and text then
DBM:CreatePizzaTimer(time, text, nil, sender)
end
end
syncHandlers["CU"] = function(sender, time, text)
if select(2, IsInInstance()) == "pvp" then return end -- no pizza timers in battlegrounds
if DBM.Options.DontShowUserTimers then return end
if DBM:GetRaidRank(sender) == 0 or difficultyIndex == 7 or difficultyIndex == 17 then return end
if sender == playerName then return end
time = tonumber(time or 0)
text = tostring(text)
if time and text then
DBM:CreatePizzaTimer(time, text, nil, sender, true)
end
end
-- beware, ugly and missplaced code ahead
-- todo: move this somewhere else
do
local accessList = {}
local savedSender
local inspopup = CreateFrame("Frame", "DBMPopupLockout", UIParent)
inspopup:SetBackdrop({bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = {left = 1, right = 1, top = 1, bottom = 1}}
)
inspopup:SetSize(500, 120)
inspopup:SetPoint("TOP", UIParent, "TOP", 0, -200)
inspopup:SetFrameStrata("DIALOG")
local inspopuptext = inspopup:CreateFontString()
inspopuptext:SetFontObject(ChatFontNormal)
inspopuptext:SetWidth(470)
inspopuptext:SetWordWrap(true)
inspopuptext:SetPoint("TOP", inspopup, "TOP", 0, -15)
local buttonaccept = CreateFrame("Button", nil, inspopup)
buttonaccept:SetNormalTexture("Interface\\Buttons\\UI-DialogBox-Button-Up")
buttonaccept:SetPushedTexture("Interface\\Buttons\\UI-DialogBox-Button-Down")
buttonaccept:SetHighlightTexture("Interface\\Buttons\\UI-DialogBox-Button-Highlight", "ADD")
buttonaccept:SetSize(128, 35)
buttonaccept:SetPoint("BOTTOM", inspopup, "BOTTOM", -75, 0)
local buttonatext = buttonaccept:CreateFontString()
buttonatext:SetFontObject(ChatFontNormal)
buttonatext:SetPoint("CENTER", buttonaccept, "CENTER", 0, 5)
buttonatext:SetText(YES)
local buttondecline = CreateFrame("Button", nil, inspopup)
buttondecline:SetNormalTexture("Interface\\Buttons\\UI-DialogBox-Button-Up")
buttondecline:SetPushedTexture("Interface\\Buttons\\UI-DialogBox-Button-Down")
buttondecline:SetHighlightTexture("Interface\\Buttons\\UI-DialogBox-Button-Highlight", "ADD")
buttondecline:SetSize(128, 35)
buttondecline:SetPoint("BOTTOM", inspopup, "BOTTOM", 75, 0)
local buttondtext = buttondecline:CreateFontString()
buttondtext:SetFontObject(ChatFontNormal)
buttondtext:SetPoint("CENTER", buttondecline, "CENTER", 0, 5)
buttondtext:SetText(NO)
inspopup:Hide()
local function autoDecline(sender, force)
inspopup:Hide()
savedSender = nil
if force then
SendAddonMessage("D4", "II\t" .. "denied", "WHISPER", sender)
else
SendAddonMessage("D4", "II\t" .. "timeout", "WHISPER", sender)
end
end
local function showPopupInstanceIdPermission(sender)
DBM:Unschedule(autoDecline)
DBM:Schedule(59, autoDecline, sender)
inspopup:Hide()
if savedSender ~= sender then
if savedSender then
autoDecline(savedSender, 1) -- Do not allow multiple popups, so auto decline to previous sender.
end
savedSender = sender
end
inspopuptext:SetText(DBM_REQ_INSTANCE_ID_PERMISSION:format(sender, sender))
buttonaccept:SetScript("OnClick", function(f) savedSender = nil DBM:Unschedule(autoDecline) accessList[sender] = true syncHandlers["IR"](sender) f:GetParent():Hide() end)
buttondecline:SetScript("OnClick", function(f) autoDecline(sender, 1) end)
PlaySound(850)
inspopup:Show()
end
syncHandlers["IR"] = function(sender)
if DBM:GetRaidRank(sender) == 0 or sender == playerName then
return
end
accessList = accessList or {}
if not accessList[sender] then
-- ask for permission
showPopupInstanceIdPermission(sender)
return
end
-- okay, send data
local sentData = false
for i = 1, GetNumSavedInstances() do
local name, id, _, difficulty, locked, extended, instanceIDMostSig, isRaid, maxPlayers, textDiff, _, progress = GetSavedInstanceInfo(i)
if (locked or extended) and isRaid then -- only report locked raid instances
SendAddonMessage("D4", "II\tData\t" .. name .. "\t" .. id .. "\t" .. difficulty .. "\t" .. maxPlayers .. "\t" .. (progress or 0) .. "\t" .. textDiff, "WHISPER", sender)
sentData = true
end
end
if not sentData then
-- send something even if there is nothing to report so the receiver is able to tell you apart from someone who just didn't respond...
SendAddonMessage("D4", "II\tNoData", "WHISPER", sender)
end
end
syncHandlers["IRE"] = function(sender)
local popup = inspopup:IsShown()
if popup and savedSender == sender then -- found the popup with the correct data
savedSender = nil
DBM:Unschedule(autoDecline)
inspopup:Hide()
end
end
syncHandlers["GCB"] = function(sender, modId, ver, difficulty, difficultyModifier)
if not DBM.Options.ShowGuildMessages or not difficulty then return end
if not ver or not (ver == "2") then return end--Ignore old versions
if DBM:AntiSpam(10, "GCB") then
if IsInInstance() then return end--Simple filter, if you are inside an instance, just filter it, if not in instance, good to go.
difficulty = tonumber(difficulty)
if not DBM.Options.ShowGuildMessagesPlus and difficulty == 8 then return end
local bossName = EJ_GetEncounterInfo(modId) or DBM_CORE_UNKNOWN
local difficultyName = DBM_CORE_UNKNOWN
if difficulty == 8 then
if difficultyModifier and difficultyModifier ~= 0 then
difficultyName = PLAYER_DIFFICULTY6.."+ ("..difficultyModifier..")"
else
difficultyName = PLAYER_DIFFICULTY6.."+"
end
elseif difficulty == 16 then
difficultyName = PLAYER_DIFFICULTY6
elseif difficulty == 15 then
difficultyName = PLAYER_DIFFICULTY2
else
difficultyName = PLAYER_DIFFICULTY1
end
DBM:AddMsg(DBM_CORE_GUILD_COMBAT_STARTED:format(difficultyName.."-"..bossName))
end
end
syncHandlers["GCE"] = function(sender, modId, ver, wipe, time, difficulty, difficultyModifier, wipeHP)
if not DBM.Options.ShowGuildMessages or not difficulty then return end
if not ver or not (ver == "4") then return end--Ignore old versions
if DBM:AntiSpam(5, "GCE") then
if IsInInstance() then return end--Simple filter, if you are inside an instance, just filter it, if not in instance, good to go.
difficulty = tonumber(difficulty)
if not DBM.Options.ShowGuildMessagesPlus and difficulty == 8 then return end
local bossName = EJ_GetEncounterInfo(modId) or DBM_CORE_UNKNOWN
local difficultyName = DBM_CORE_UNKNOWN
if difficulty == 8 then
if difficultyModifier and difficultyModifier ~= 0 then
difficultyName = PLAYER_DIFFICULTY6.."+ ("..difficultyModifier..")"
else
difficultyName = PLAYER_DIFFICULTY6.."+"
end
elseif difficulty == 16 then
difficultyName = PLAYER_DIFFICULTY6
elseif difficulty == 15 then
difficultyName = PLAYER_DIFFICULTY2
else
difficultyName = PLAYER_DIFFICULTY1
end
if wipe == "1" then
DBM:AddMsg(DBM_CORE_GUILD_COMBAT_ENDED_AT:format(difficultyName.."-"..bossName, wipeHP, time))
else
DBM:AddMsg(DBM_CORE_GUILD_BOSS_DOWN:format(difficultyName.."-"..bossName, time))
end
end
end
syncHandlers["WBE"] = function(sender, modId, realm, health, ver, name)
if not ver or not (ver == "8") then return end--Ignore old versions
if lastBossEngage[modId..realm] and (GetTime() - lastBossEngage[modId..realm] < 30) then return end--We recently got a sync about this boss on this realm, so do nothing.
lastBossEngage[modId..realm] = GetTime()
if realm == playerRealm and DBM.Options.WorldBossAlert and not IsEncounterInProgress() then
modId = tonumber(modId)--If it fails to convert into number, this makes it nil
local bossName = modId and EJ_GetEncounterInfo(modId) or name or DBM_CORE_UNKNOWN
DBM:AddMsg(DBM_CORE_WORLDBOSS_ENGAGED:format(bossName, floor(health), sender))
end
end
syncHandlers["WBD"] = function(sender, modId, realm, ver, name)
if not ver or not (ver == "8") then return end--Ignore old versions
if lastBossDefeat[modId..realm] and (GetTime() - lastBossDefeat[modId..realm] < 30) then return end
lastBossDefeat[modId..realm] = GetTime()
if realm == playerRealm and DBM.Options.WorldBossAlert and not IsEncounterInProgress() then
modId = tonumber(modId)--If it fails to convert into number, this makes it nil
local bossName = modId and EJ_GetEncounterInfo(modId) or name or DBM_CORE_UNKNOWN
DBM:AddMsg(DBM_CORE_WORLDBOSS_DEFEATED:format(bossName, sender))
end
end
whisperSyncHandlers["WBE"] = function(sender, modId, realm, health, ver, name)
if not ver or not (ver == "8") then return end--Ignore old versions
if lastBossEngage[modId..realm] and (GetTime() - lastBossEngage[modId..realm] < 30) then return end
lastBossEngage[modId..realm] = GetTime()
if realm == playerRealm and DBM.Options.WorldBossAlert and not IsEncounterInProgress() then
local _, toonName = BNGetGameAccountInfo(sender)
modId = tonumber(modId)--If it fails to convert into number, this makes it nil
local bossName = modId and EJ_GetEncounterInfo(modId) or name or DBM_CORE_UNKNOWN
DBM:AddMsg(DBM_CORE_WORLDBOSS_ENGAGED:format(bossName, floor(health), toonName))
end
end
whisperSyncHandlers["WBD"] = function(sender, modId, realm, ver, name)
if not ver or not (ver == "8") then return end--Ignore old versions
if lastBossDefeat[modId..realm] and (GetTime() - lastBossDefeat[modId..realm] < 30) then return end
lastBossDefeat[modId..realm] = GetTime()
if realm == playerRealm and DBM.Options.WorldBossAlert and not IsEncounterInProgress() then
local _, toonName = BNGetGameAccountInfo(sender)
modId = tonumber(modId)--If it fails to convert into number, this makes it nil
local bossName = modId and EJ_GetEncounterInfo(modId) or name or DBM_CORE_UNKNOWN
DBM:AddMsg(DBM_CORE_WORLDBOSS_DEFEATED:format(bossName, toonName))
end
end
local lastRequest = 0
local numResponses = 0
local expectedResponses = 0
local allResponded = false
local results
local updateInstanceInfo, showResults
whisperSyncHandlers["II"] = function(sender, result, name, id, diff, maxPlayers, progress, textDiff)
if not DBM:GetRaidUnitId(sender) then return end
if GetTime() - lastRequest > 62 or not results then
return
end
if not result then
return
end
name = name or DBM_CORE_UNKNOWN
id = id or ""
diff = tonumber(diff or 0) or 0
maxPlayers = tonumber(maxPlayers or 0) or 0
progress = tonumber(progress or 0) or 0
textDiff = textDiff or ""
-- count responses
if not results.responses[sender] then
results.responses[sender] = result
numResponses = numResponses + 1
end
-- get localized difficulty text
if textDiff ~= "" then
results.difftext[diff] = textDiff
end
if result == "Data" then
-- got data in that response and not just a "no" or "i'm away"
local instanceId = name.." "..maxPlayers.." "..diff -- locale-dependant dungeon ID
results.data[instanceId] = results.data[instanceId] or {
ids = {}, -- array of all ids of all raid members
name = name,
diff = diff,
maxPlayers = maxPlayers,
}
if diff == 5 or diff == 6 or diff == 16 then
results.data[instanceId].ids[id] = results.data[instanceId].ids[id] or { progress = progress, haveid = true }
tinsert(results.data[instanceId].ids[id], sender)
else
results.data[instanceId].ids[progress] = results.data[instanceId].ids[progress] or { progress = progress }
tinsert(results.data[instanceId].ids[progress], sender)
end
end
if numResponses >= expectedResponses then -- unlikely, lol
DBM:Unschedule(updateInstanceInfo)
DBM:Unschedule(showResults)
if not allResponded then --Only display message once in case we get for example 4 syncs the last sender
DBM:Schedule(0.99, DBM.AddMsg, DBM, DBM_INSTANCE_INFO_ALL_RESPONSES)
allResponded = true
end
C_TimerAfter(1, showResults) --Delay results so we allow time for same sender to send more than 1 lockout, otherwise, if we get expectedResponses before all data is sent from 1 user, we clip some of their data.
end
end
function showResults()
local resultCount = 0
-- TODO: you could catch some localized instances by observing IDs if there are multiple players with the same instance ID but a different name ;) (not that useful if you are trying to get a fresh instance)
DBM:AddMsg(DBM_INSTANCE_INFO_RESULTS, false)
DBM:AddMsg("---", false)
for i, v in pairs(results.data) do
resultCount = resultCount + 1
DBM:AddMsg(DBM_INSTANCE_INFO_DETAIL_HEADER:format(v.name, (results.difftext[v.diff] or v.diff)), false)
for id, v in pairs(v.ids) do
if v.haveid then
DBM:AddMsg(DBM_INSTANCE_INFO_DETAIL_INSTANCE:format(id, v.progress, tconcat(v, ", ")), false)
else
DBM:AddMsg(DBM_INSTANCE_INFO_DETAIL_INSTANCE2:format(v.progress, tconcat(v, ", ")), false)
end
end
DBM:AddMsg("---", false)
end
if resultCount == 0 then
DBM:AddMsg(DBM_INSTANCE_INFO_NOLOCKOUT, false)
end
local denied = {}
local away = {}
local noResponse = {}
for i = 1, GetNumGroupMembers() do
if not UnitIsUnit("raid"..i, "player") then
tinsert(noResponse, (GetRaidRosterInfo(i)))
end
end
for i, v in pairs(results.responses) do
if v == "Data" or v == "NoData" then
elseif v == "timeout" then
tinsert(away, i)
else -- could be "clicked" or "override", in both cases we don't get the data because the dialog requesting it was dismissed
tinsert(denied, i)
end
removeEntry(noResponse, i)
end
if #denied > 0 then
DBM:AddMsg(DBM_INSTANCE_INFO_STATS_DENIED:format(tconcat(denied, ", ")), false)
end
if #away > 0 then
DBM:AddMsg(DBM_INSTANCE_INFO_STATS_AWAY:format(tconcat(away, ", ")), false)
end
if #noResponse > 0 then
DBM:AddMsg(DBM_INSTANCE_INFO_STATS_NO_RESPONSE:format(tconcat(noResponse, ", ")), false)
end
results = nil
end
-- called when the chat link is clicked
function DBM:ShowRaidIDRequestResults()
if not results then -- check if we are currently querying raid IDs, results will be nil if we don't
return
end
self:Unschedule(updateInstanceInfo)
self:Unschedule(showResults)
showResults() -- sets results to nil after the results are displayed, ending the current id request; future incoming data will be discarded
sendSync("IRE")
end
local function getResponseStats()
local numResponses = 0
local sent = 0
local denied = 0
local away = 0
for k, v in pairs(results.responses) do
numResponses = numResponses + 1
if v == "Data" or v == "NoData" then
sent = sent + 1
elseif v == "timeout" then
away = away + 1
else -- could be "clicked" or "override", in both cases we don't get the data because the dialog requesting it was dismissed
denied = denied + 1
end
end
return numResponses, sent, denied, away
end
local function getNumDBMUsers() -- without ourselves
local r = 0
for i, v in pairs(raid) do
if v.revision and v.name ~= playerName and UnitIsConnected(v.id) then
r = r + 1
end
end
return r
end
function updateInstanceInfo(timeRemaining, dontAddShowResultNowButton)
local numResponses, sent, denied, away = getResponseStats()
local dbmUsers = getNumDBMUsers()
DBM:AddMsg(DBM_INSTANCE_INFO_STATUS_UPDATE:format(numResponses, dbmUsers, sent, denied, timeRemaining), false)
if not dontAddShowResultNowButton then
if dbmUsers - numResponses <= 7 then -- waiting for 7 or less players, show their names and the early result option
-- copied from above, todo: implement a smarter way of keeping track of stuff like this
local noResponse = {}
for i = 1, GetNumGroupMembers() do
if not UnitIsUnit("raid"..i, "player") and raid[GetRaidRosterInfo(i)] and raid[GetRaidRosterInfo(i)].revision then -- only show players who actually can respond (== DBM users)
tinsert(noResponse, (GetRaidRosterInfo(i)))
end
end
for i, v in pairs(results.responses) do
removeEntry(noResponse, i)
end
--[[
-- this looked like the easiest way (for some reason?) to create the player string when writing this code -.-
local function dup(...) if select("#", ...) == 0 then return else return ..., ..., dup(select(2, ...)) end end
DBM:AddMsg(DBM_INSTANCE_INFO_SHOW_RESULTS:format(("|Hplayer:%s|h[%s]|h| "):rep(#noResponse):format(dup(unpack(noResponse)))), false)
]]
-- code that one can actually read
for i, v in ipairs(noResponse) do
noResponse[i] = ("|Hplayer:%s|h[%s]|h|"):format(v, v)
end
DBM:AddMsg(DBM_INSTANCE_INFO_SHOW_RESULTS:format(tconcat(noResponse, ", ")), false)
end
end
end
function DBM:RequestInstanceInfo()
self:AddMsg(DBM_INSTANCE_INFO_REQUESTED)
lastRequest = GetTime()
allResponded = false
results = {
responses = { -- who responded to our request?
},
data = { -- the actual data
},
difftext = {
}
}
numResponses = 0
expectedResponses = getNumDBMUsers()
sendSync("IR")
self:Unschedule(updateInstanceInfo)
self:Unschedule(showResults)
self:Schedule(17, updateInstanceInfo, 45, true)
self:Schedule(32, updateInstanceInfo, 30)
self:Schedule(48, updateInstanceInfo, 15)
C_TimerAfter(62, showResults)
end
end
whisperSyncHandlers["RT"] = function(sender)
if not DBM:GetRaidUnitId(sender) then
DBM:Debug(sender.." attempted to request timers but isn't in your group")
return
end
DBM:SendTimers(sender)
end
whisperSyncHandlers["CI"] = function(sender, mod, time)
if not DBM:GetRaidUnitId(sender) then
DBM:Debug(sender.." attempted to send you combat info but isn't in your group")
return
end
mod = DBM:GetModByName(mod or "")
time = tonumber(time or 0)
if mod and time then
DBM:ReceiveCombatInfo(sender, mod, time)
end
end
whisperSyncHandlers["TI"] = function(sender, mod, timeLeft, totalTime, id, ...)
if not DBM:GetRaidUnitId(sender) then return end--This can't be checked fast enough on timer recovery, so it causes it to fail
mod = DBM:GetModByName(mod or "")
timeLeft = tonumber(timeLeft or 0)
totalTime = tonumber(totalTime or 0)
if mod and timeLeft and timeLeft > 0 and totalTime and totalTime > 0 and id then
DBM:ReceiveTimerInfo(sender, mod, timeLeft, totalTime, id, ...)
end
end
whisperSyncHandlers["VI"] = function(sender, mod, name, value)
if not DBM:GetRaidUnitId(sender) then return end--This can't be checked fast enough on timer recovery, so it causes it to fail
mod = DBM:GetModByName(mod or "")
value = tonumber(value) or value
if mod and name and value then
DBM:ReceiveVariableInfo(sender, mod, name, value)
end
end
local function handleSync(channel, sender, prefix, ...)
if not prefix then
return
end
local handler
if channel == "WHISPER" and sender ~= playerName then -- separate between broadcast and unicast, broadcast must not be sent as unicast or vice-versa
handler = whisperSyncHandlers[prefix]
else
handler = syncHandlers[prefix]
end
if handler then
return handler(sender, ...)
end
end
function DBM:CHAT_MSG_ADDON(prefix, msg, channel, sender)
if prefix == "D4" and msg and (channel == "PARTY" or channel == "RAID" or channel == "INSTANCE_CHAT" or channel == "WHISPER" or channel == "GUILD") then
sender = Ambiguate(sender, "none")
handleSync(channel, sender, strsplit("\t", msg))
elseif prefix == "BigWigs" and msg and (channel == "PARTY" or channel == "RAID" or channel == "INSTANCE_CHAT") then
local bwPrefix, bwMsg, extra = strsplit("^", msg)
if bwPrefix and bwMsg then
if bwPrefix == "V" and extra then--Nil check "extra" to avoid error from older version
local verString, hash = bwMsg, extra
local version = tonumber(verString) or 0
if version == 0 then return end--Just a query
sender = Ambiguate(sender, "none")
handleSync(channel, sender, "BV", version, hash)--Prefix changed, so it's not handled by DBMs "V" handler
if version > fakeBWVersion then--Newer revision found, upgrade!
fakeBWVersion = version
fakeBWHash = hash
end
elseif bwPrefix == "Q" then--Version request prefix
self:Unschedule(SendVersion)
self:Schedule(3, SendVersion)
elseif bwPrefix == "B" then--Boss Mod Sync
for i = 1, #inCombat do
local mod = inCombat[i]
if mod and mod.OnBWSync then
mod:OnBWSync(bwMsg, extra, sender)
end
end
for i = 1, #oocBWComms do
local mod = oocBWComms[i]
if mod and mod.OnBWSync then
mod:OnBWSync(bwMsg, extra, sender)
end
end
end
end
elseif prefix == "Transcriptor" and msg then
for i = 1, #inCombat do
local mod = inCombat[i]
if mod and mod.OnTranscriptorSync then
mod:OnTranscriptorSync(msg, sender)
end
end
if msg:find("spell:") and (DBM.Options.DebugLevel > 2 or (Transcriptor and Transcriptor:IsLogging())) then
local spellId = string.match(msg, "spell:(%d+)") or DBM_CORE_UNKNOWN
local spellName = string.match(msg, "h%[(.-)%]|h") or DBM_CORE_UNKNOWN
local message = "RAID_BOSS_WHISPER on "..sender.." with spell of "..spellName.." ("..spellId..")"
self:Debug(message)
end
end
end
function DBM:BN_CHAT_MSG_ADDON(prefix, msg, channel, sender)
if prefix == "D4" and msg then
handleSync(channel, sender, strsplit("\t", msg))
end
end
end
-----------------------
-- Update Reminder --
-----------------------
do
local frame, fontstring, fontstringFooter, editBox, urlText
local function createFrame()
frame = CreateFrame("Frame", "DBMUpdateReminder", UIParent)
frame:SetFrameStrata("FULLSCREEN_DIALOG") -- yes, this isn't a fullscreen dialog, but I want it to be in front of other DIALOG frames (like DBM GUI which might open this frame...)
frame:SetWidth(430)
frame:SetHeight(140)
frame:SetPoint("TOP", 0, -230)
frame:SetBackdrop({
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32,
insets = {left = 11, right = 12, top = 12, bottom = 11},
})
fontstring = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
fontstring:SetWidth(410)
fontstring:SetHeight(0)
fontstring:SetPoint("TOP", 0, -16)
editBox = CreateFrame("EditBox", nil, frame)
do
local editBoxLeft = editBox:CreateTexture(nil, "BACKGROUND")
local editBoxRight = editBox:CreateTexture(nil, "BACKGROUND")
local editBoxMiddle = editBox:CreateTexture(nil, "BACKGROUND")
editBoxLeft:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Left")
editBoxLeft:SetHeight(32)
editBoxLeft:SetWidth(32)
editBoxLeft:SetPoint("LEFT", -14, 0)
editBoxLeft:SetTexCoord(0, 0.125, 0, 1)
editBoxRight:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Right")
editBoxRight:SetHeight(32)
editBoxRight:SetWidth(32)
editBoxRight:SetPoint("RIGHT", 6, 0)
editBoxRight:SetTexCoord(0.875, 1, 0, 1)
editBoxMiddle:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Right")
editBoxMiddle:SetHeight(32)
editBoxMiddle:SetWidth(1)
editBoxMiddle:SetPoint("LEFT", editBoxLeft, "RIGHT")
editBoxMiddle:SetPoint("RIGHT", editBoxRight, "LEFT")
editBoxMiddle:SetTexCoord(0, 0.9375, 0, 1)
end
editBox:SetHeight(32)
editBox:SetWidth(250)
editBox:SetPoint("TOP", fontstring, "BOTTOM", 0, -4)
editBox:SetFontObject("GameFontHighlight")
editBox:SetTextInsets(0, 0, 0, 1)
editBox:SetFocus()
editBox:SetText(urlText)
editBox:HighlightText()
editBox:SetScript("OnTextChanged", function(self)
editBox:SetText(urlText)
editBox:HighlightText()
end)
fontstringFooter = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
fontstringFooter:SetWidth(410)
fontstringFooter:SetHeight(0)
fontstringFooter:SetPoint("TOP", editBox, "BOTTOM", 0, 0)
local button = CreateFrame("Button", nil, frame)
button:SetHeight(24)
button:SetWidth(75)
button:SetPoint("BOTTOM", 0, 13)
button:SetNormalFontObject("GameFontNormal")
button:SetHighlightFontObject("GameFontHighlight")
button:SetNormalTexture(button:CreateTexture(nil, nil, "UIPanelButtonUpTexture"))
button:SetPushedTexture(button:CreateTexture(nil, nil, "UIPanelButtonDownTexture"))
button:SetHighlightTexture(button:CreateTexture(nil, nil, "UIPanelButtonHighlightTexture"))
button:SetText(OKAY)
button:SetScript("OnClick", function(self)
frame:Hide()
end)
end
function DBM:ShowUpdateReminder(newVersion, newRevision, text, url)
--[[ bf@178.com
urlText = url or DBM_CORE_UPDATEREMINDER_URL or "http://www.deadlybossmods.com"
if not frame then
createFrame()
else
editBox:SetText(urlText)
editBox:HighlightText()
end
frame:Show()
if newVersion then
fontstring:SetText(DBM_CORE_UPDATEREMINDER_HEADER:format(newVersion, newRevision))
fontstringFooter:SetText(DBM_CORE_UPDATEREMINDER_FOOTER)
elseif text then
fontstring:SetText(text)
fontstringFooter:SetText(DBM_CORE_UPDATEREMINDER_FOOTER_GENERIC)
end
]]
end
end
--------------------
-- Notes Editor --
--------------------
do
local frame, fontstring, fontstringFooter, editBox, button3
local function createFrame()
frame = CreateFrame("Frame", "DBMNotesEditor", UIParent)
frame:SetFrameStrata("FULLSCREEN_DIALOG") -- yes, this isn't a fullscreen dialog, but I want it to be in front of other DIALOG frames (like DBM GUI which might open this frame...)
frame:SetWidth(430)
frame:SetHeight(140)
frame:SetPoint("TOP", 0, -230)
frame:SetBackdrop({
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32,
insets = {left = 11, right = 12, top = 12, bottom = 11},
})
fontstring = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
fontstring:SetWidth(410)
fontstring:SetHeight(0)
fontstring:SetPoint("TOP", 0, -16)
editBox = CreateFrame("EditBox", nil, frame)
do
local editBoxLeft = editBox:CreateTexture(nil, "BACKGROUND")
local editBoxRight = editBox:CreateTexture(nil, "BACKGROUND")
local editBoxMiddle = editBox:CreateTexture(nil, "BACKGROUND")
editBoxLeft:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Left")
editBoxLeft:SetHeight(32)
editBoxLeft:SetWidth(32)
editBoxLeft:SetPoint("LEFT", -14, 0)
editBoxLeft:SetTexCoord(0, 0.125, 0, 1)
editBoxRight:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Right")
editBoxRight:SetHeight(32)
editBoxRight:SetWidth(32)
editBoxRight:SetPoint("RIGHT", 6, 0)
editBoxRight:SetTexCoord(0.875, 1, 0, 1)
editBoxMiddle:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Right")
editBoxMiddle:SetHeight(32)
editBoxMiddle:SetWidth(1)
editBoxMiddle:SetPoint("LEFT", editBoxLeft, "RIGHT")
editBoxMiddle:SetPoint("RIGHT", editBoxRight, "LEFT")
editBoxMiddle:SetTexCoord(0, 0.9375, 0, 1)
end
editBox:SetHeight(32)
editBox:SetWidth(250)
editBox:SetPoint("TOP", fontstring, "BOTTOM", 0, -4)
editBox:SetFontObject("GameFontHighlight")
editBox:SetTextInsets(0, 0, 0, 1)
editBox:SetFocus()
editBox:SetText("")
fontstringFooter = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
fontstringFooter:SetWidth(410)
fontstringFooter:SetHeight(0)
fontstringFooter:SetPoint("TOP", editBox, "BOTTOM", 0, 0)
local button = CreateFrame("Button", nil, frame)
button:SetHeight(24)
button:SetWidth(75)
button:SetPoint("BOTTOM", 80, 13)
button:SetNormalFontObject("GameFontNormal")
button:SetHighlightFontObject("GameFontHighlight")
button:SetNormalTexture(button:CreateTexture(nil, nil, "UIPanelButtonUpTexture"))
button:SetPushedTexture(button:CreateTexture(nil, nil, "UIPanelButtonDownTexture"))
button:SetHighlightTexture(button:CreateTexture(nil, nil, "UIPanelButtonHighlightTexture"))
button:SetText(OKAY)
button:SetScript("OnClick", function(self)
local mod = DBM.Noteframe.mod
local modvar = DBM.Noteframe.modvar
mod.Options[modvar .. "SWNote"] = editBox:GetText() or ""
DBM.Noteframe.mod = nil
DBM.Noteframe.modvar = nil
DBM.Noteframe.abilityName = nil
frame:Hide()
end)
local button2 = CreateFrame("Button", nil, frame)
button2:SetHeight(24)
button2:SetWidth(75)
button2:SetPoint("BOTTOM", 0, 13)
button2:SetNormalFontObject("GameFontNormal")
button2:SetHighlightFontObject("GameFontHighlight")
button2:SetNormalTexture(button2:CreateTexture(nil, nil, "UIPanelButtonUpTexture"))
button2:SetPushedTexture(button2:CreateTexture(nil, nil, "UIPanelButtonDownTexture"))
button2:SetHighlightTexture(button2:CreateTexture(nil, nil, "UIPanelButtonHighlightTexture"))
button2:SetText(CANCEL)
button2:SetScript("OnClick", function(self)
DBM.Noteframe.mod = nil
DBM.Noteframe.modvar = nil
DBM.Noteframe.abilityName = nil
frame:Hide()
end)
button3 = CreateFrame("Button", nil, frame)
button3:SetHeight(24)
button3:SetWidth(75)
button3:SetPoint("BOTTOM", -80, 13)
button3:SetNormalFontObject("GameFontNormal")
button3:SetHighlightFontObject("GameFontHighlight")
button3:SetNormalTexture(button3:CreateTexture(nil, nil, "UIPanelButtonUpTexture"))
button3:SetPushedTexture(button3:CreateTexture(nil, nil, "UIPanelButtonDownTexture"))
button3:SetHighlightTexture(button3:CreateTexture(nil, nil, "UIPanelButtonHighlightTexture"))
button3:SetText(SHARE_QUEST_ABBREV)
button3:SetScript("OnClick", function(self)
local modid = DBM.Noteframe.mod.id
local modvar = DBM.Noteframe.modvar
local abilityName = DBM.Noteframe.abilityName
local syncText = editBox:GetText() or ""
if syncText == "" then
DBM:AddMsg(DBM_CORE_NOTESHAREERRORBLANK)
elseif IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and IsInInstance() then--For BGs, LFR and LFG (we also check IsInInstance() so if you're in queue but fighting something outside like a world boss, it'll sync in "RAID" instead)
DBM:AddMsg(DBM_CORE_NOTESHAREERRORGROUPFINDER)
else
local msg = modid.."\t"..modvar.."\t"..syncText.."\t"..abilityName
if IsInRaid() then
if DBM:GetRaidRank(playerName) == 0 then
DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
else
SendAddonMessage("D4", "NS\t" .. msg, "RAID")
DBM:AddMsg(DBM_CORE_NOTESHARED)
end
elseif IsInGroup(LE_PARTY_CATEGORY_HOME) then
if DBM:GetRaidRank(playerName) == 0 then
DBM:AddMsg(DBM_ERROR_NO_PERMISSION)
else
SendAddonMessage("D4", "NS\t" .. msg, "PARTY")
DBM:AddMsg(DBM_CORE_NOTESHARED)
end
else--Solo
DBM:AddMsg(DBM_CORE_NOTESHAREERRORSOLO)
end
end
end)
end
function DBM:ShowNoteEditor(mod, modvar, abilityName, syncText, sender)
if not frame then
createFrame()
self.Noteframe = frame
else
if frame:IsShown() and syncText then
self:AddMsg(DBM_CORE_NOTESHAREERRORALREADYOPEN)
return
end
end
frame:Show()
fontstringFooter:SetText(DBM_CORE_NOTEFOOTER)
self.Noteframe.mod = mod
self.Noteframe.modvar = modvar
self.Noteframe.abilityName = abilityName
if syncText then
button3:Hide()--Don't show share button in shared notes
fontstring:SetText(DBM_CORE_NOTESHAREDHEADER:format(sender, abilityName))
editBox:SetText(syncText)
else
button3:Show()
fontstring:SetText(DBM_CORE_NOTEHEADER:format(abilityName))
if type(mod.Options[modvar .. "SWNote"]) == "string" then
editBox:SetText(mod.Options[modvar .. "SWNote"])
else
editBox:SetText("")
end
end
end
end
----------------------
-- Pull Detection --
----------------------
do
local targetList = {}
local function buildTargetList()
local uId = (IsInRaid() and "raid") or "party"
for i = 0, GetNumGroupMembers() do
local id = (i == 0 and "target") or uId..i.."target"
local guid = UnitGUID(id)
if guid and DBM:IsCreatureGUID(guid) then
local cId = DBM:GetCIDFromGUID(guid)
targetList[cId] = id
end
end
end
local function clearTargetList()
twipe(targetList)
end
local function scanForCombat(mod, mob, delay)
if not checkEntry(inCombat, mob) then
buildTargetList()
if targetList[mob] then
if delay > 0 and UnitAffectingCombat(targetList[mob]) and not (UnitPlayerOrPetInRaid(targetList[mob]) or UnitPlayerOrPetInParty(targetList[mob])) then
DBM:StartCombat(mod, delay, "PLAYER_REGEN_DISABLED")
elseif (delay == 0) then
DBM:StartCombat(mod, 0, "PLAYER_REGEN_DISABLED_AND_MESSAGE")
end
end
clearTargetList()
end
end
local function checkForPull(mob, combatInfo)
healthCombatInitialized = false
--This just can't be avoided, tryig to save cpu by using C_TimerAfter broke this
--This needs the redundancy and ability to pass args.
DBM:Schedule(0.5, scanForCombat, combatInfo.mod, mob, 0.5)
DBM:Schedule(2, scanForCombat, combatInfo.mod, mob, 2)
C_TimerAfter(2.1, function()
healthCombatInitialized = true
end)
end
-- TODO: fix the duplicate code that was added for quick & dirty support of zone IDs
-- detects a boss pull based on combat state, this is required for pre-ICC bosses that do not fire INSTANCE_ENCOUNTER_ENGAGE_UNIT events on engage
function DBM:PLAYER_REGEN_DISABLED()
lastCombatStarted = GetTime()
if not combatInitialized then return end
if dbmIsEnabled and combatInfo[LastInstanceMapID] then
for i, v in ipairs(combatInfo[LastInstanceMapID]) do
if v.type:find("combat") and not v.noRegenDetection then
if v.multiMobPullDetection then
for _, mob in ipairs(v.multiMobPullDetection) do
if checkForPull(mob, v) then
break
end
end
else
checkForPull(v.mob, v)
end
end
end
end
if self.Options.AFKHealthWarning and not IsEncounterInProgress() and UnitIsAFK("player") and self:AntiSpam(5, "AFK") then--You are afk and losing health, some griever is trying to kill you while you are afk/tabbed out.
self:FlashClientIcon()
local voice = DBM.Options.ChosenVoicePack
local path = "Sound\\Creature\\CThun\\CThunYouWillDIe.ogg"
if voice ~= "None" then
path = "Interface\\AddOns\\DBM-VP"..voice.."\\checkhp.ogg"
end
self:PlaySoundFile(path)
if UnitHealthMax("player") ~= 0 then
local health = UnitHealth("player") / UnitHealthMax("player") * 100
self:AddMsg(DBM_CORE_AFK_WARNING:format(health))
end
end
end
function DBM:PLAYER_REGEN_ENABLED()
if delayedFunction then--Will throw error if not a function, purposely not doing and type(delayedFunction) == "function" for now to make sure code works though cause it always should be function
delayedFunction()
delayedFunction = nil
end
end
local function isBossEngaged(cId)
-- note that this is designed to work with any number of bosses, but it might be sufficient to check the first 5 unit ids
local i = 1
repeat
local bossUnitId = "boss"..i
local bossGUID = not UnitIsDead(bossUnitId) and UnitGUID(bossUnitId) -- check for UnitIsVisible maybe?
local bossCId = bossGUID and DBM:GetCIDFromGUID(bossGUID)
if bossCId and (type(cId) == "number" and cId == bossCId or type(cId) == "table" and checkEntry(cId, bossCId)) then
return true
end
i = i + 1
until not bossGUID
end
function DBM:INSTANCE_ENCOUNTER_ENGAGE_UNIT()
if timerRequestInProgress then return end--do not start ieeu combat if timer request is progressing. (not to break Timer Recovery stuff)
if dbmIsEnabled and combatInfo[LastInstanceMapID] then
self:Debug("INSTANCE_ENCOUNTER_ENGAGE_UNIT event fired for zoneId"..LastInstanceMapID, 3)
for i, v in ipairs(combatInfo[LastInstanceMapID]) do
if v.type:find("combat") and isBossEngaged(v.multiMobPullDetection or v.mob) then
self:StartCombat(v.mod, 0, "IEEU")
end
end
end
end
function DBM:UNIT_TARGETABLE_CHANGED(uId)
if self.Options.DebugLevel > 2 or (Transcriptor and Transcriptor:IsLogging()) then
local active = UnitExists(uId) and "true" or "false"
self:Debug("UNIT_TARGETABLE_CHANGED event fired for "..UnitName(uId)..". Active: "..active)
end
end
function DBM:UNIT_SPELLCAST_SUCCEEDED(uId, _, bfaSpellId, _, legacySpellId)
local spellId = legacySpellId or bfaSpellId
local spellName = self:GetSpellInfo(spellId)
self:Debug("UNIT_SPELLCAST_SUCCEEDED fired: "..UnitName(uId).."'s "..spellName.."("..spellId..")", 3)
end
function DBM:ENCOUNTER_START(encounterID, name, difficulty, size)
self:Debug("ENCOUNTER_START event fired: "..encounterID.." "..name.." "..difficulty.." "..size)
if dbmIsEnabled then
if not self.Options.DontShowReminders then
self:CheckAvailableMods()
end
if combatInfo[LastInstanceMapID] then
for i, v in ipairs(combatInfo[LastInstanceMapID]) do
if not v.noESDetection then
if v.multiEncounterPullDetection then
for _, eId in ipairs(v.multiEncounterPullDetection) do
if encounterID == eId then
self:StartCombat(v.mod, 0, "ENCOUNTER_START")
return
end
end
elseif encounterID == v.eId then
self:StartCombat(v.mod, 0, "ENCOUNTER_START")
return
end
end
end
end
end
end
function DBM:ENCOUNTER_END(encounterID, name, difficulty, size, success)
self:Debug("ENCOUNTER_END event fired: "..encounterID.." "..name.." "..difficulty.." "..size.." "..success)
for i = #inCombat, 1, -1 do
local v = inCombat[i]
if not v.combatInfo then return end
if v.noEEDetection then return end
if v.respawnTime and success == 0 and self.Options.ShowRespawn and not self.Options.DontShowBossTimers then--No special hacks needed for bad wrath ENCOUNTER_END. Only mods that define respawnTime have a timer, since variable per boss.
local name = string.split(",", name)
self.Bars:CreateBar(v.respawnTime, DBM_CORE_TIMER_RESPAWN:format(name), "Interface\\Icons\\Spell_Holy_BorrowedTime")
fireEvent("DBM_TimerStart", "DBMRespawnTimer", DBM_CORE_TIMER_RESPAWN:format(name), v.respawnTime, "Interface\\Icons\\Spell_Holy_BorrowedTime", "extratimer", nil, 0, v.id)
end
if v.multiEncounterPullDetection then
for _, eId in ipairs(v.multiEncounterPullDetection) do
if encounterID == eId then
self:EndCombat(v, success == 0)
sendSync("EE", encounterID.."\t"..success.."\t"..v.id.."\t"..(v.revision or 0))
return
end
end
elseif encounterID == v.combatInfo.eId then
self:EndCombat(v, success == 0)
sendSync("EE", encounterID.."\t"..success.."\t"..v.id.."\t"..(v.revision or 0))
return
end
end
end
function DBM:BOSS_KILL(encounterID, name)
self:Debug("BOSS_KILL event fired: "..encounterID.." "..name)
for i = #inCombat, 1, -1 do
local v = inCombat[i]
if not v.combatInfo then return end
if v.multiEncounterPullDetection then
for _, eId in ipairs(v.multiEncounterPullDetection) do
if encounterID == eId then
self:EndCombat(v)
sendSync("EE", encounterID.."\t1\t"..v.id.."\t"..(v.revision or 0))
return
end
end
elseif encounterID == v.combatInfo.eId then
self:EndCombat(v)
sendSync("EE", encounterID.."\t1\t"..v.id.."\t"..(v.revision or 0))
return
end
end
end
local function checkExpressionList(exp, str)
for i, v in ipairs(exp) do
if str:match(v) then
return true
end
end
return false
end
-- called for all mob chat events
local function onMonsterMessage(self, type, msg)
-- pull detection
if dbmIsEnabled and combatInfo[LastInstanceMapID] then
for i, v in ipairs(combatInfo[LastInstanceMapID]) do
if v.type == type and checkEntry(v.msgs, msg) or v.type == type .. "_regex" and checkExpressionList(v.msgs, msg) then
self:StartCombat(v.mod, 0, "MONSTER_MESSAGE")
elseif v.type == "combat_" .. type .. "find" and findEntry(v.msgs, msg) or v.type == "combat_" .. type and checkEntry(v.msgs, msg) then
if IsInInstance() then--Indoor boss that uses both combat and message for combat, so in other words (such as hodir), don't require "target" of boss for yell like scanForCombat does for World Bosses
self:StartCombat(v.mod, 0, "MONSTER_MESSAGE")
else--World Boss
scanForCombat(v.mod, v.mob, 0)
if v.mod.readyCheckQuestId and (self.Options.WorldBossNearAlert or v.mod.Options.ReadyCheck) and not IsQuestFlaggedCompleted(v.mod.readyCheckQuestId) then
self:FlashClientIcon()
self:PlaySoundFile("Sound\\interface\\levelup2.ogg", true)
end
end
end
end
end
-- kill detection (wipe detection would also be nice to have)
-- todo: add sync
for i = #inCombat, 1, -1 do
local v = inCombat[i]
if not v.combatInfo then return end
if v.combatInfo.killType == type and v.combatInfo.killMsgs[msg] then
self:EndCombat(v)
end
end
end
function DBM:CHAT_MSG_MONSTER_YELL(msg, npc, _, _, target)
if IsEncounterInProgress() or (IsInInstance() and InCombatLockdown()) then--Too many 5 mans/old raids don't properly return encounterinprogress
local targetName = target or "nil"
self:Debug("CHAT_MSG_MONSTER_YELL from "..npc.." while looking at "..targetName, 2)
end
return onMonsterMessage(self, "yell", msg)
end
function DBM:CHAT_MSG_MONSTER_EMOTE(msg)
return onMonsterMessage(self, "emote", msg)
end
function DBM:CHAT_MSG_RAID_BOSS_EMOTE(msg, ...)
onMonsterMessage(self, "emote", msg)
return self:FilterRaidBossEmote(msg, ...)
end
function DBM:RAID_BOSS_EMOTE(msg, ...)--This is a mirror of above prototype only it has less args, both still exist for some reason.
onMonsterMessage(self, "emote", msg)
return self:FilterRaidBossEmote(msg, ...)
end
function DBM:RAID_BOSS_WHISPER(msg)
--Make it easier for devs to detect whispers they are unable to see
--TINTERFACE\\ICONS\\ability_socererking_arcanewrath.blp:20|t You have been branded by |cFFF00000|Hspell:156238|h[Arcane Wrath]|h|r!"
if IsInGroup() and not BigWigs then
SendAddonMessage("Transcriptor", msg, IsInGroup(2) and "INSTANCE_CHAT" or IsInRaid() and "RAID" or "PARTY")--Send any emote to transcriptor, even if no spellid
end
end
function DBM:CHAT_MSG_MONSTER_SAY(msg)
return onMonsterMessage(self, "say", msg)
end
end
---------------------------
-- Kill/Wipe Detection --
---------------------------
function checkWipe(self, confirm)
if #inCombat > 0 then
if not savedDifficulty or not difficultyText or not difficultyIndex then--prevent error if savedDifficulty or difficultyText is nil
savedDifficulty, difficultyText, difficultyIndex, LastGroupSize, difficultyModifier = self:GetCurrentInstanceDifficulty()
end
--hack for no iEEU information is provided.
if not bossuIdFound then
for i = 1, 5 do
if UnitExists("boss"..i) then
bossuIdFound = true
break
end
end
end
local wipe = 1 -- 0: no wipe, 1: normal wipe, 2: wipe by UnitExists check.
if IsInScenarioGroup() or (difficultyIndex == 11) or (difficultyIndex == 12) then -- Scenario mod uses special combat start and must be enabled before sceniro end. So do not wipe.
wipe = 0
elseif IsEncounterInProgress() then -- Encounter Progress marked, you obviously in combat with boss. So do not Wipe
wipe = 0
elseif savedDifficulty == "worldboss" and UnitIsDeadOrGhost("player") then -- On dead or ghost, unit combat status detection would be fail. If you ghost in instance, that means wipe. But in worldboss, ghost means not wipe. So do not wipe.
wipe = 0
elseif bossuIdFound and LastInstanceType == "raid" then -- Combat started by IEEU and no boss exist and no EncounterProgress marked, that means wipe
wipe = 2
for i = 1, 5 do
if UnitExists("boss"..i) then
wipe = 0 -- Boss found. No wipe
break
end
end
else -- Unit combat status detection. No combat unit in your party and no EncounterProgress marked, that means wipe
wipe = 1
local uId = (IsInRaid() and "raid") or "party"
for i = 0, GetNumGroupMembers() do
local id = (i == 0 and "player") or uId..i
if UnitAffectingCombat(id) and not UnitIsDeadOrGhost(id) then
wipe = 0 -- Someone still in combat. No wipe
break
end
end
end
if wipe == 0 then
self:Schedule(3, checkWipe, self)
elseif confirm then
for i = #inCombat, 1, -1 do
local reason = (wipe == 1 and "No combat unit found in your party." or "No boss found : "..(wipe or "nil"))
self:Debug("You wiped. Reason : "..reason)
self:EndCombat(inCombat[i], true)
end
else
local maxDelayTime = (savedDifficulty == "worldboss" and 15) or 5 --wait 10s more on worldboss do actual wipe.
for i, v in ipairs(inCombat) do
maxDelayTime = v.combatInfo and v.combatInfo.wipeTimer and v.combatInfo.wipeTimer > maxDelayTime and v.combatInfo.wipeTimer or maxDelayTime
end
self:Schedule(maxDelayTime, checkWipe, self, true)
end
end
end
function checkBossHealth(self)
if #inCombat > 0 then
for i, v in ipairs(inCombat) do
if not v.multiMobPullDetection or v.mainBoss then
self:GetBossHP(v.mainBoss or v.combatInfo.mob or -1)
else
for _, mob in ipairs(v.multiMobPullDetection) do
self:GetBossHP(mob)
end
end
end
self:Schedule(1, checkBossHealth, self)
end
end
function checkCustomBossHealth(self, mod)
mod:CustomHealthUpdate()
self:Schedule(1, checkCustomBossHealth, self, mod)
end
do
local statVarTable = {
--6.0+
["event5"] = "normal",
["event20"] = "lfr25",
["event40"] = "lfr25",
["normal5"] = "normal",
["heroic5"] = "heroic",
["challenge5"] = "challenge",
["lfr"] = "lfr25",
["normal"] = "normal",
["heroic"] = "heroic",
["mythic"] = "mythic",
["worldboss"] = "normal",
["timewalker"] = "timewalker",
--Legacy
["lfr25"] = "lfr25",
["normal10"] = "normal",
["normal25"] = "normal25",
["heroic10"] = "heroic",
["heroic25"] = "heroic25",
}
function DBM:StartCombat(mod, delay, event, synced, syncedStartHp)
cSyncSender = {}
cSyncReceived = 0
if not checkEntry(inCombat, mod) then
if not mod.Options.Enabled then return end
if not mod.combatInfo then return end
if mod.combatInfo.noCombatInVehicle and UnitInVehicle("player") then -- HACK
return
end
--HACK: makes sure that we don't detect a false pull if the event fires again when the boss dies...
if mod.lastKillTime and GetTime() - mod.lastKillTime < (mod.reCombatTime or 120) and event ~= "LOADING_SCREEN_DISABLED" then return end
if mod.lastWipeTime and GetTime() - mod.lastWipeTime < (event == "ENCOUNTER_START" and 3 or mod.reCombatTime2 or 20) and event ~= "LOADING_SCREEN_DISABLED" then return end
if event then
self:Debug("StartCombat called by : "..event..". LastInstanceMapID is "..LastInstanceMapID)
if event ~= "ENCOUNTER_START" then
self:Debug("This event is started by"..event..". Review ENCOUNTER_START event to ensure if this is still needed", 2)
end
else
self:Debug("StartCombat called by individual mod or unknown reason. LastInstanceMapID is "..LastInstanceMapID)
end
--check completed. starting combat
if self.Options.DisableGuildStatus and UnitIsGroupLeader("player") then
sendSync("DGP")
end
tinsert(inCombat, mod)
if mod.inCombatOnlyEvents and not mod.inCombatOnlyEventsRegistered then
mod.inCombatOnlyEventsRegistered = 1
mod:RegisterEvents(unpack(mod.inCombatOnlyEvents))
end
--Fix for "attempt to perform arithmetic on field 'stats' (a nil value)"
if not mod.stats then
self:AddMsg(DBM_CORE_BAD_LOAD)--Warn user that they should reload ui soon as they leave combat to get their mod to load correctly as soon as possible
mod.ignoreBestkill = true--Force this to true so we don't check any more occurances of "stats"
elseif event == "TIMER_RECOVERY" then --add a lag time to delay when TIMER_RECOVERY
delay = delay + select(4, GetNetStats()) / 1000
end
--set mod default info
savedDifficulty, difficultyText, difficultyIndex, LastGroupSize, difficultyModifier = self:GetCurrentInstanceDifficulty()
local name = mod.combatInfo.name
local modId = mod.id
if C_Scenario.IsInScenario() and (mod.addon.type == "SCENARIO") then
mod.inScenario = true
end
mod.inCombat = true
mod.blockSyncs = nil
mod.combatInfo.pull = GetTime() - (delay or 0)
bossuIdFound = (event or "") == "IEEU"
if mod.minCombatTime then
self:Schedule(mmax((mod.minCombatTime - delay), 3), checkWipe, self)
else
self:Schedule(3, checkWipe, self)
end
--get boss hp at pull
if syncedStartHp and syncedStartHp < 1 then
syncedStartHp = syncedStartHp * 100
end
local startHp = syncedStartHp or mod:GetBossHP(mod.mainBoss or mod.combatInfo.mob or -1) or 100
--check boss engaged first?
if (savedDifficulty == "worldboss" and startHp < 98) or (event == "UNIT_HEALTH" and delay > 4) or event == "TIMER_RECOVERY" then--Boss was not full health when engaged, disable combat start timer and kill record
mod.ignoreBestkill = true
elseif mod.inScenario then
local _, currentStage, numStages = C_Scenario.GetInfo()
if currentStage > 1 and numStages > 1 then
mod.ignoreBestkill = true
end
else--Reset ignoreBestkill after wipe
mod.ignoreBestkill = false
--It was a clean pull, so cancel any RequestTimers which might fire after boss was pulled if boss was pulled right after mod load
--Only want timer recovery on in progress bosses, not clean pulls
if startHp > 98 and (savedDifficulty == "worldboss" or event == "IEEU") or event == "ENCOUNTER_START" then
self:Unschedule(self.RequestTimers)
end
end
if not mod.inScenario then
if self.Options.HideTooltips then
--Better or cleaner way?
tooltipsHidden = true
GameTooltip.Temphide = function() GameTooltip:Hide() end; GameTooltip:SetScript("OnShow", GameTooltip.Temphide)
end
if self.Options.DisableSFX and GetCVar("Sound_EnableSFX") == "1" then
self.Options.sfxDisabled = true
SetCVar("Sound_EnableSFX", 0)
end
--boss health info scheduler
if not mod.CustomHealthUpdate then
self:Schedule(1, checkBossHealth, self)
else
self:Schedule(1, checkCustomBossHealth, self, mod)
end
end
--process global options
self:HideBlizzardEvents(1)
self:StartLogging(0, nil)
if self.Options.HideObjectivesFrame and mod.addon.type ~= "SCENARIO" and GetNumTrackedAchievements() == 0 and difficultyIndex ~= 8 then
if ObjectiveTrackerFrame:IsVisible() then
ObjectiveTrackerFrame:Hide()
watchFrameRestore = true
end
end
fireEvent("pull", mod, delay, synced, startHp)
self:FlashClientIcon()
--serperate timer recovery and normal start.
if event ~= "TIMER_RECOVERY" then
--add pull count
if mod.stats then
if not mod.stats[statVarTable[savedDifficulty].."Pulls"] then mod.stats[statVarTable[savedDifficulty].."Pulls"] = 0 end
mod.stats[statVarTable[savedDifficulty].."Pulls"] = mod.stats[statVarTable[savedDifficulty].."Pulls"] + 1
end
--show speed timer
if self.Options.AlwaysShowSpeedKillTimer2 and mod.stats and not mod.ignoreBestkill then
local bestTime
if difficultyIndex == 8 then--Mythic+/Challenge Mode
local bestMPRank = mod.stats.challengeBestRank or 0
if bestMPRank == difficultyModifier then
--Don't show speed kill timer if not our highest rank. DBM only stores highest rank
bestTime = mod.stats[statVarTable[savedDifficulty].."BestTime"]
end
else
bestTime = mod.stats[statVarTable[savedDifficulty].."BestTime"]
end
if bestTime and bestTime > 0 then
local speedTimer = mod:NewTimer(bestTime, DBM_SPEED_KILL_TIMER_TEXT, "Interface\\Icons\\Spell_Holy_BorrowedTime", nil, false)
speedTimer:Start()
end
end
--update boss left
if mod.numBoss then
mod.vb.bossLeft = mod.numBoss
end
--elect icon person
if mod.findFastestComputer and not self.Options.DontSetIcons then
if self:GetRaidRank() > 0 then
for i = 1, #mod.findFastestComputer do
local option = mod.findFastestComputer[i]
if mod.Options[option] then
sendSync("IS", UnitGUID("player").."\t"..DBM.Revision.."\t"..option)
end
end
elseif not IsInGroup() then
for i = 1, #mod.findFastestComputer do
local option = mod.findFastestComputer[i]
if mod.Options[option] then
canSetIcons[option] = true
end
end
end
end
--call OnCombatStart
if mod.OnCombatStart then
mod:OnCombatStart(delay or 0, event == "PLAYER_REGEN_DISABLED_AND_MESSAGE" or event == "SPELL_CAST_SUCCESS")
end
--send "C" sync
if not synced then
sendSync("C", (delay or 0).."\t"..modId.."\t"..(mod.revision or 0).."\t"..startHp.."\t"..DBM.Revision.."\t"..(mod.hotfixNoticeRev or 0))
end
if self.Options.DisableStatusWhisper and UnitIsGroupLeader("player") and (difficultyIndex == 8 or difficultyIndex == 14 or difficultyIndex == 15 or difficultyIndex == 16) then
sendSync("DSW")
end
--show bigbrother check
if self.Options.ShowBigBrotherOnCombatStart and BigBrother and type(BigBrother.ConsumableCheck) == "function" then
if self.Options.BigBrotherAnnounceToRaid then
BigBrother:ConsumableCheck("RAID")
else
BigBrother:ConsumableCheck("SELF")
end
end
--show enage message
if self.Options.ShowEngageMessage then
if mod.ignoreBestkill and (savedDifficulty == "worldboss") then--Should only be true on in progress field bosses, not in progress raid bosses we did timer recovery on.
self:AddMsg(DBM_CORE_COMBAT_STARTED_IN_PROGRESS:format(difficultyText..name))
elseif mod.ignoreBestkill and mod.inScenario then
self:AddMsg(DBM_CORE_SCENARIO_STARTED_IN_PROGRESS:format(difficultyText..name))
else
if mod.addon.type == "SCENARIO" then
self:AddMsg(DBM_CORE_SCENARIO_STARTED:format(difficultyText..name))
else
self:AddMsg(DBM_CORE_COMBAT_STARTED:format(difficultyText..name))
if (difficultyIndex == 8 or difficultyIndex == 14 or difficultyIndex == 15 or difficultyIndex == 16) and InGuildParty() and not statusGuildDisabled and not self.Options.DisableGuildStatus then--Only send relevant content, not guild beating down lich king or LFR.
SendAddonMessage("D4", "GCB\t"..modId.."\t2\t"..difficultyIndex.."\t"..difficultyModifier, "GUILD")
end
end
end
end
--stop pull count
local dummyMod = self:GetModByName("PullTimerCountdownDummy")
if dummyMod then--stop pull timer, warning, countdowns
dummyMod.countdown:Cancel()
dummyMod.text:Cancel()
self.Bars:CancelBar(DBM_CORE_TIMER_PULL)
fireEvent("DBM_TimerStop", "pull")
TimerTracker_OnEvent(TimerTracker, "PLAYER_ENTERING_WORLD")
end
if BigWigs and BigWigs.db.profile.raidicon and not self.Options.DontSetIcons and self:GetRaidRank() > 0 then--Both DBM and bigwigs have raid icon marking turned on.
self:AddMsg(DBM_CORE_BIGWIGS_ICON_CONFLICT)--Warn that one of them should be turned off to prevent conflict (which they turn off is obviously up to raid leaders preference, dbm accepts either or turned off to stop this alert)
end
if self.Options.EventSoundEngage and self.Options.EventSoundEngage ~= "" and self.Options.EventSoundEngage ~= "None" then
self:PlaySoundFile(self.Options.EventSoundEngage)
end
fireEvent("DBM_MusicStart", "BossEncounter")
if self.Options.EventSoundMusic and self.Options.EventSoundMusic ~= "None" and self.Options.EventSoundMusic ~= "" and not (self.Options.EventMusicMythicFilter and (savedDifficulty == "mythic" or savedDifficulty == "challenge")) then
if not self.Options.tempMusicSetting then
self.Options.tempMusicSetting = tonumber(GetCVar("Sound_EnableMusic"))
if self.Options.tempMusicSetting == 0 then
SetCVar("Sound_EnableMusic", 1)
else
self.Options.tempMusicSetting = nil--Don't actually need it
end
end
local path = "MISSING"
if self.Options.EventSoundMusic == "Random" then
local usedTable = self.Options.EventSoundMusicCombined and DBM.Music or DBM.BattleMusic
local random = fastrandom(3, #usedTable)
path = usedTable[random].value
else
path = self.Options.EventSoundMusic
end
PlayMusic(path)
self.Options.musicPlaying = true
DBM:Debug("Starting combat music with file: "..path)
end
else
self:AddMsg(DBM_CORE_COMBAT_STATE_RECOVERED:format(difficultyText..name, strFromTime(delay)))
if mod.OnTimerRecovery then
mod:OnTimerRecovery()
end
end
if savedDifficulty == "worldboss" and not mod.noWBEsync then
if lastBossEngage[modId..playerRealm] and (GetTime() - lastBossEngage[modId..playerRealm] < 30) then return end--Someone else synced in last 10 seconds so don't send out another sync to avoid needless sync spam.
lastBossEngage[modId..playerRealm] = GetTime()--Update last engage time, that way we ignore our own sync
if IsInGuild() then
SendAddonMessage("D4", "WBE\t"..modId.."\t"..playerRealm.."\t"..startHp.."\t8\t"..name, "GUILD")--Even guild syncs send realm so we can keep antispam the same across realid as well.
end
local _, numBNetOnline = BNGetNumFriends()
for i = 1, numBNetOnline do
local sameRealm = false
local presenceID, _, _, _, _, _, client, isOnline = BNGetFriendInfo(i)
if isOnline and client == BNET_CLIENT_WOW then
local _, _, _, userRealm = BNGetGameAccountInfo(presenceID)
if connectedServers then
for i = 1, #connectedServers do
if userRealm == connectedServers[i] then
sameRealm = true
break
end
end
else
if userRealm == playerRealm then
sameRealm = true
end
end
if sameRealm then
BNSendGameData(presenceID, "D4", "WBE\t"..modId.."\t"..userRealm.."\t"..startHp.."\t8\t"..name)--Just send users realm for pull, so we can eliminate connectedServers checks on sync handler
end
end
end
end
end
end
function DBM:UNIT_HEALTH(uId)
local cId = self:GetCIDFromGUID(UnitGUID(uId))
local health
if UnitHealthMax(uId) ~= 0 then
health = UnitHealth(uId) / UnitHealthMax(uId) * 100
end
if not health or health < 2 then return end -- no worthy of combat start if health is below 2%
if dbmIsEnabled and InCombatLockdown() then
if cId ~= 0 and not bossHealth[cId] and bossIds[cId] and UnitAffectingCombat(uId) and not (UnitPlayerOrPetInRaid(uId) or UnitPlayerOrPetInParty(uId)) and healthCombatInitialized then -- StartCombat by UNIT_HEALTH.
if combatInfo[LastInstanceMapID] then
for i, v in ipairs(combatInfo[LastInstanceMapID]) do
if v.mod.Options.Enabled and not v.mod.disableHealthCombat and v.type:find("combat") and (v.multiMobPullDetection and checkEntry(v.multiMobPullDetection, cId) or v.mob == cId) then
-- Delay set, > 97% = 0.5 (consider as normal pulling), max dealy limited to 20s.
self:StartCombat(v.mod, health > 97 and 0.5 or mmin(GetTime() - lastCombatStarted, 20), "UNIT_HEALTH", nil, health)
end
end
end
end
if self.Options.AFKHealthWarning and UnitIsUnit(uId, "player") and (health < 85) and not IsEncounterInProgress() and UnitIsAFK("player") and self:AntiSpam(5, "AFK") then--You are afk and losing health, some griever is trying to kill you while you are afk/tabbed out.
self:PlaySoundFile("Sound\\Creature\\CThun\\CThunYouWillDIe.ogg")--So fire an alert sound to save yourself from this person's behavior.
self:AddMsg(DBM_CORE_AFK_WARNING:format(health))
end
end
end
function DBM:EndCombat(mod, wipe)
if removeEntry(inCombat, mod) then
local scenario = mod.addon.type == "SCENARIO" and not mod.soloChallenge
if mod.inCombatOnlyEvents and mod.inCombatOnlyEventsRegistered then
-- unregister all events except for SPELL_AURA_REMOVED events (might still be needed to remove icons etc...)
mod:UnregisterInCombatEvents()
self:Schedule(2, mod.UnregisterInCombatEvents, mod, true) -- 2 seconds should be enough for all auras to fade
self:Schedule(3, mod.Stop, mod) -- Remove accident started timers.
mod.inCombatOnlyEventsRegistered = nil
end
if mod.updateInterval then
mod:UnregisterOnUpdateHandler()
end
mod:Stop()
if enableIcons and not self.Options.DontSetIcons and not self.Options.DontRestoreIcons then
-- restore saved previous icon
for uId, icon in pairs(mod.iconRestore) do
SetRaidTarget(uId, icon)
end
twipe(mod.iconRestore)
end
mod.inCombat = false
mod.blockSyncs = true
if mod.combatInfo.killMobs then
for i, v in pairs(mod.combatInfo.killMobs) do
mod.combatInfo.killMobs[i] = true
end
end
if not savedDifficulty or not difficultyText or not difficultyIndex then--prevent error if savedDifficulty or difficultyText is nil
savedDifficulty, difficultyText, difficultyIndex, LastGroupSize, difficultyModifier = DBM:GetCurrentInstanceDifficulty()
end
if not mod.stats then--This will be nil if the mod for this intance failed to load fully because "script ran too long" (it tried to load in combat and failed)
self:AddMsg(DBM_CORE_BAD_LOAD)--Warn user that they should reload ui soon as they leave combat to get their mod to load correctly as soon as possible
return--Don't run any further, stats are nil on a bad load so rest of this code will also error out.
end
local name = mod.combatInfo.name
local modId = mod.id
if wipe then
mod.lastWipeTime = GetTime()
--Fix for "attempt to perform arithmetic on field 'pull' (a nil value)" (which was actually caused by stats being nil, so we never did getTime on pull, fixing one SHOULD fix the other)
local thisTime = GetTime() - mod.combatInfo.pull
local hp = mod.highesthealth and mod:GetHighestBossHealth() or mod:GetLowestBossHealth()
local wipeHP = mod.CustomHealthUpdate and mod:CustomHealthUpdate() or hp and ("%d%%"):format(hp) or DBM_CORE_UNKNOWN
if mod.vb.phase then
wipeHP = wipeHP.." ("..SCENARIO_STAGE:format(mod.vb.phase)..")"
end
if mod.numBoss then
local bossesKilled = mod.numBoss - mod.vb.bossLeft
wipeHP = wipeHP.." ("..BOSSES_KILLED:format(bossesKilled, mod.numBoss)..")"
end
local totalPulls = mod.stats[statVarTable[savedDifficulty].."Pulls"]
local totalKills = mod.stats[statVarTable[savedDifficulty].."Kills"]
if thisTime < 30 then -- Normally, one attempt will last at least 30 sec.
totalPulls = totalPulls - 1
mod.stats[statVarTable[savedDifficulty].."Pulls"] = totalPulls
if self.Options.ShowDefeatMessage then
if scenario then
self:AddMsg(DBM_CORE_SCENARIO_ENDED_AT:format(difficultyText..name, strFromTime(thisTime)))
else
self:AddMsg(DBM_CORE_COMBAT_ENDED_AT:format(difficultyText..name, wipeHP, strFromTime(thisTime)))
--No reason to GCE it here, so omited on purpose.
end
end
else
if self.Options.ShowDefeatMessage then
if scenario then
self:AddMsg(DBM_CORE_SCENARIO_ENDED_AT_LONG:format(difficultyText..name, strFromTime(thisTime), totalPulls - totalKills))
else
self:AddMsg(DBM_CORE_COMBAT_ENDED_AT_LONG:format(difficultyText..name, wipeHP, strFromTime(thisTime), totalPulls - totalKills))
if (difficultyIndex == 8 or difficultyIndex == 14 or difficultyIndex == 15 or difficultyIndex == 16) and InGuildParty() and not statusGuildDisabled and not self.Options.DisableGuildStatus then--Maybe add mythic plus/CM?
SendAddonMessage("D4", "GCE\t"..modId.."\t4\t1\t"..strFromTime(thisTime).."\t"..difficultyIndex.."\t"..difficultyModifier.."\t"..wipeHP, "GUILD")
end
end
end
end
if not self.Options.DontShowReminders and showConstantReminder == 2 and IsInGroup() and savedDifficulty ~= "lfr" and savedDifficulty ~= "lfr25" then
showConstantReminder = 1
--Show message any time this is a mod that has a newer hotfix revision
--These people need to know the wipe could very well be their fault.
self:AddMsg(DBM_CORE_OUT_OF_DATE_NAG)
end
local msg
for k, v in pairs(autoRespondSpam) do
if self.Options.WhisperStats then
if scenario then
msg = msg or chatPrefixShort..DBM_CORE_WHISPER_SCENARIO_END_WIPE_STATS:format(playerName, difficultyText..(name or ""), totalPulls - totalKills)
else
msg = msg or chatPrefixShort..DBM_CORE_WHISPER_COMBAT_END_WIPE_STATS_AT:format(playerName, difficultyText..(name or ""), wipeHP, totalPulls - totalKills)
end
else
if scenario then
msg = msg or chatPrefixShort..DBM_CORE_WHISPER_SCENARIO_END_WIPE:format(playerName, difficultyText..(name or ""))
else
msg = msg or chatPrefixShort..DBM_CORE_WHISPER_COMBAT_END_WIPE_AT:format(playerName, difficultyText..(name or ""), wipeHP)
end
end
sendWhisper(k, msg)
end
fireEvent("wipe", mod)
if self.Options.EventSoundWipe and self.Options.EventSoundWipe ~= "None" and self.Options.EventSoundWipe ~= "" then
if self.Options.EventSoundWipe == "Random" then
local random = fastrandom(3, #DBM.Defeat)
self:PlaySoundFile(DBM.Defeat[random].value)
else
self:PlaySoundFile(self.Options.EventSoundWipe)
end
end
else
mod.lastKillTime = GetTime()
local thisTime = GetTime() - (mod.combatInfo.pull or 0)
local lastTime = mod.stats[statVarTable[savedDifficulty].."LastTime"]
local bestTime = mod.stats[statVarTable[savedDifficulty].."BestTime"]
if not mod.stats[statVarTable[savedDifficulty].."Kills"] or mod.stats[statVarTable[savedDifficulty].."Kills"] < 0 then mod.stats[statVarTable[savedDifficulty].."Kills"] = 0 end
--Fix logical error i've seen where for some reason we have more kills then pulls for boss as seen by - stats for wipe messages.
mod.stats[statVarTable[savedDifficulty].."Kills"] = mod.stats[statVarTable[savedDifficulty].."Kills"] + 1
if mod.stats[statVarTable[savedDifficulty].."Kills"] > mod.stats[statVarTable[savedDifficulty].."Pulls"] then mod.stats[statVarTable[savedDifficulty].."Kills"] = mod.stats[statVarTable[savedDifficulty].."Pulls"] end
if not mod.ignoreBestkill and mod.combatInfo.pull then
mod.stats[statVarTable[savedDifficulty].."LastTime"] = thisTime
--Just to prevent pre mature end combat calls from broken mods from saving bad time stats.
if bestTime and bestTime > 0 and bestTime < 1.5 then
mod.stats[statVarTable[savedDifficulty].."BestTime"] = thisTime
else
if difficultyIndex == 8 then--Mythic+/Challenge Mode
local bestMPRank = mod.stats.challengeBestRank or 0
if mod.stats.challengeBestRank > difficultyModifier then--Don't save time stats at all
--DO nothing
elseif mod.stats.challengeBestRank < difficultyModifier then--Update best time and best rank, even if best time is lower (for a lower rank)
mod.stats.challengeBestRank = difficultyModifier--Update best rank
mod.stats[statVarTable[savedDifficulty].."BestTime"] = thisTime--Write this time no matter what.
else--Best rank must match current rank, so update time normally
mod.stats[statVarTable[savedDifficulty].."BestTime"] = mmin(bestTime or mhuge, thisTime)
end
else
mod.stats[statVarTable[savedDifficulty].."BestTime"] = mmin(bestTime or mhuge, thisTime)
end
end
end
local totalKills = mod.stats[statVarTable[savedDifficulty].."Kills"]
if self.Options.ShowDefeatMessage then
local msg = ""
if not mod.combatInfo.pull then--was a bad pull so we ignored thisTime, should never happen
if scenario then
msg = DBM_CORE_SCENARIO_COMPLETE:format(difficultyText..name, DBM_CORE_UNKNOWN)
else
msg = DBM_CORE_BOSS_DOWN:format(difficultyText..name, DBM_CORE_UNKNOWN)
end
elseif mod.ignoreBestkill then--Should never happen in a scenario so no need for scenario check.
if scenario then
msg = DBM_CORE_SCENARIO_COMPLETE_I:format(difficultyText..name, totalKills)
else
msg = DBM_CORE_BOSS_DOWN_I:format(difficultyText..name, totalKills)
end
elseif not lastTime then
if scenario then
msg = DBM_CORE_SCENARIO_COMPLETE:format(difficultyText..name, strFromTime(thisTime))
else
msg = DBM_CORE_BOSS_DOWN:format(difficultyText..name, strFromTime(thisTime))
if (difficultyIndex == 8 or difficultyIndex == 14 or difficultyIndex == 15 or difficultyIndex == 16) and InGuildParty() and not statusGuildDisabled and not self.Options.DisableGuildStatus then
SendAddonMessage("D4", "GCE\t"..modId.."\t4\t0\t"..strFromTime(thisTime).."\t"..difficultyIndex.."\t"..difficultyModifier, "GUILD")
end
end
elseif thisTime < (bestTime or mhuge) then
if scenario then
msg = DBM_CORE_SCENARIO_COMPLETE_NR:format(difficultyText..name, strFromTime(thisTime), strFromTime(bestTime), totalKills)
else
msg = DBM_CORE_BOSS_DOWN_NR:format(difficultyText..name, strFromTime(thisTime), strFromTime(bestTime), totalKills)
if (difficultyIndex == 8 or difficultyIndex == 14 or difficultyIndex == 15 or difficultyIndex == 16) and InGuildParty() and not statusGuildDisabled and not self.Options.DisableGuildStatus then
SendAddonMessage("D4", "GCE\t"..modId.."\t4\t0\t"..strFromTime(thisTime).."\t"..difficultyIndex.."\t"..difficultyModifier, "GUILD")
end
end
else
if scenario then
msg = DBM_CORE_SCENARIO_COMPLETE_L:format(difficultyText..name, strFromTime(thisTime), strFromTime(lastTime), strFromTime(bestTime), totalKills)
else
msg = DBM_CORE_BOSS_DOWN_L:format(difficultyText..name, strFromTime(thisTime), strFromTime(lastTime), strFromTime(bestTime), totalKills)
if (difficultyIndex == 8 or difficultyIndex == 14 or difficultyIndex == 15 or difficultyIndex == 16) and InGuildParty() and not statusGuildDisabled and not self.Options.DisableGuildStatus then
SendAddonMessage("D4", "GCE\t"..modId.."\t4\t0\t"..strFromTime(thisTime).."\t"..difficultyIndex.."\t"..difficultyModifier, "GUILD")
end
end
end
self:Schedule(1, self.AddMsg, self, msg)
end
local msg
for k, v in pairs(autoRespondSpam) do
if self.Options.WhisperStats then
if scenario then
msg = msg or chatPrefixShort..DBM_CORE_WHISPER_SCENARIO_END_KILL_STATS:format(playerName, difficultyText..(name or ""), totalKills)
else
msg = msg or chatPrefixShort..DBM_CORE_WHISPER_COMBAT_END_KILL_STATS:format(playerName, difficultyText..(name or ""), totalKills)
end
else
if scenario then
msg = msg or chatPrefixShort..DBM_CORE_WHISPER_SCENARIO_END_KILL:format(playerName, difficultyText..(name or ""))
else
msg = msg or chatPrefixShort..DBM_CORE_WHISPER_COMBAT_END_KILL:format(playerName, difficultyText..(name or ""))
end
end
sendWhisper(k, msg)
end
fireEvent("kill", mod)
if savedDifficulty == "worldboss" and not mod.noWBEsync then
if lastBossDefeat[modId..playerRealm] and (GetTime() - lastBossDefeat[modId..playerRealm] < 30) then return end--Someone else synced in last 10 seconds so don't send out another sync to avoid needless sync spam.
lastBossDefeat[modId..playerRealm] = GetTime()--Update last defeat time before we send it, so we don't handle our own sync
if IsInGuild() then
SendAddonMessage("D4", "WBD\t"..modId.."\t"..playerRealm.."\t8\t"..name, "GUILD")--Even guild syncs send realm so we can keep antispam the same across realid as well.
end
local _, numBNetOnline = BNGetNumFriends()
for i = 1, numBNetOnline do
local sameRealm = false
local presenceID, _, _, _, _, _, client, isOnline = BNGetFriendInfo(i)
if isOnline and client == BNET_CLIENT_WOW then
local _, _, _, userRealm = BNGetGameAccountInfo(presenceID)
if connectedServers then
for i = 1, #connectedServers do
if userRealm == connectedServers[i] then
sameRealm = true
break
end
end
else
if userRealm == playerRealm then
sameRealm = true
end
end
if sameRealm then
BNSendGameData(presenceID, "D4", "WBD\t"..modId.."\t"..userRealm.."\t8\t"..name)
end
end
end
end
if self.Options.EventSoundVictory2 and self.Options.EventSoundVictory2 ~= "" then
if self.Options.EventSoundVictory2 == "Random" then
local random = fastrandom(3, #DBM.Victory)
self:PlaySoundFile(DBM.Victory[random].value)
else
self:PlaySoundFile(self.Options.EventSoundVictory2)
end
end
end
if mod.OnCombatEnd then mod:OnCombatEnd(wipe) end
if mod.OnLeavingCombat then delayedFunction = mod.OnLeavingCombat end
if #inCombat == 0 then--prevent error if you pulled multiple boss. (Earth, Wind and Fire)
statusWhisperDisabled = false
statusGuildDisabled = false
self:Schedule(10, self.StopLogging, self)--small delay to catch kill/died combatlog events
self:HideBlizzardEvents(0)
self:Unschedule(checkBossHealth)
self:Unschedule(checkCustomBossHealth)
self.Arrow:Hide(true)
if watchFrameRestore then
ObjectiveTrackerFrame:Show()
watchFrameRestore = false
end
if tooltipsHidden then
--Better or cleaner way?
tooltipsHidden = false
GameTooltip:SetScript("OnShow", GameTooltip.Show)
end
if self.Options.sfxDisabled then
self.Options.sfxDisabled = nil
SetCVar("Sound_EnableSFX", 1)
end
--cache table
twipe(autoRespondSpam)
twipe(bossHealth)
twipe(bossHealthuIdCache)
twipe(bossuIdCache)
--sync table
twipe(canSetIcons)
twipe(iconSetRevision)
twipe(iconSetPerson)
twipe(addsGUIDs)
bossuIdFound = false
eeSyncSender = {}
eeSyncReceived = 0
targetMonitor = nil
self:CreatePizzaTimer(time, "", nil, nil, nil, nil, true)--Auto Terminate infinite loop timers on combat end
self:TransitionToDungeonBGM(false, true)
self:Schedule(22, self.TransitionToDungeonBGM, self)--
end
end
end
end
function DBM:OnMobKill(cId, synced)
for i = #inCombat, 1, -1 do
local v = inCombat[i]
if not v.combatInfo then
return
end
if v.combatInfo.killMobs and v.combatInfo.killMobs[cId] then
if not synced then
sendSync("K", cId)
end
v.combatInfo.killMobs[cId] = false
if v.numBoss then
v.vb.bossLeft = (v.vb.bossLeft or v.numBoss) - 1
self:Debug("Boss left - "..v.vb.bossLeft.."/"..v.numBoss, 2)
end
local allMobsDown = true
for i, v in pairs(v.combatInfo.killMobs) do
if v then
allMobsDown = false
break
end
end
if allMobsDown then
self:EndCombat(v)
end
elseif cId == v.combatInfo.mob and not v.combatInfo.killMobs and not v.combatInfo.multiMobPullDetection then
if not synced then
sendSync("K", cId)
end
self:EndCombat(v)
end
end
end
do
local autoLog = false
local autoTLog = false
local function isCurrentContent()
if LastInstanceMapID == 1520 or LastInstanceMapID == 1530 or LastInstanceMapID == 1220 or LastInstanceMapID == 1648 or LastInstanceMapID == 1676 or LastInstanceMapID == 1712 then--Legion
return true
end
return false
end
function DBM:StartLogging(timer, checkFunc)
self:Unschedule(DBM.StopLogging)
if self.Options.LogOnlyRaidBosses and ((LastInstanceType ~= "raid") or IsPartyLFG() or not isCurrentContent()) then return end
if self.Options.AutologBosses then--Start logging here to catch pre pots.
if not LoggingCombat() then
autoLog = true
self:AddMsg("|cffffff00"..COMBATLOGENABLED.."|r")
LoggingCombat(true)
if checkFunc then
self:Unschedule(checkFunc)
self:Schedule(timer+10, checkFunc)--But if pull was canceled and we don't have a boss engaged within 10 seconds of pull timer ending, abort log
end
end
end
if self.Options.AdvancedAutologBosses and Transcriptor then
if not Transcriptor:IsLogging() then
autoTLog = true
self:AddMsg("|cffffff00"..DBM_CORE_TRANSCRIPTOR_LOG_START.."|r")
Transcriptor:StartLog(1)
end
if checkFunc then
self:Unschedule(checkFunc)
self:Schedule(timer+10, checkFunc)--But if pull was canceled and we don't have a boss engaged within 10 seconds of pull timer ending, abort log
end
end
end
function DBM:StopLogging()
if self.Options.AutologBosses and LoggingCombat() and autoLog then
autoLog = false
self:AddMsg("|cffffff00"..COMBATLOGDISABLED.."|r")
LoggingCombat(false)
end
if self.Options.AdvancedAutologBosses and Transcriptor and autoTLog then
if Transcriptor:IsLogging() then
autoTLog = false
self:AddMsg("|cffffff00"..DBM_CORE_TRANSCRIPTOR_LOG_END.."|r")
Transcriptor:StopLog(1)
end
end
end
end
function DBM:SetCurrentSpecInfo()
currentSpecGroup = GetSpecialization() or 1
currentSpecID, currentSpecName = GetSpecializationInfo(currentSpecGroup)--give temp first spec id for non-specialization char. no one should use dbm with no specialization, below level 10, should not need dbm.
currentSpecID = tonumber(currentSpecID)
end
function DBM:GetCurrentInstanceDifficulty()
local _, instanceType, difficulty, difficultyName, _, _, _, _, instanceGroupSize = GetInstanceInfo()
local keystoneLevel = C_ChallengeMode.GetActiveKeystoneInfo() or 0
if difficulty == 0 or (difficulty == 1 and instanceType == "none") or C_Garrison:IsOnGarrisonMap() then--draenor field returns 1, causing world boss mod bug.
return "worldboss", RAID_INFO_WORLD_BOSS.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 1 then
return "normal5", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 2 then
return "heroic5", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 3 then
return "normal10", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 4 then
return "normal25", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 5 then
return "heroic10", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 6 then
return "heroic25", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 7 then--Fixed LFR (ie pre WoD zones)
return "lfr25", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 8 then
return "challenge5", PLAYER_DIFFICULTY6.."+ ("..keystoneLevel..") - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 9 then--40 man raids have their own difficulty now, no longer returned as normal 10man raids
return "normal10", difficultyName.." - ",difficulty, instanceGroupSize, keystoneLevel--Just use normal10 anyways, since that's where we been saving 40 man stuff for so long anyways, no reason to change it now, not like any 40 mans can be toggled between 10 and 40 where we NEED to tell the difference.
elseif difficulty == 11 then
return "heroic5", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 12 then
return "normal5", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 14 then
return "normal", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 15 then
return "heroic", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 16 then
return "mythic", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 17 then--Variable LFR (ie post WoD zones)
return "lfr", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 18 then
return "event40", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 19 then
return "event5", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 20 then
return "event20", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 23 then
return "mythic", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
elseif difficulty == 24 or difficulty == 33 then
return "timewalker", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
-- elseif difficulty == 25 then--Used by Ashran in 7.x.
-- return "pvpscenario", difficultyName.." - ", difficulty, instanceGroupSize, keystoneLevel
else--failsafe
return "normal5", "", difficulty, instanceGroupSize, keystoneLevel
end
end
function DBM:GetCurrentArea()
return LastInstanceMapID
end
function DBM:GetGroupSize()
return LastGroupSize
end
function DBM:GetKeyStoneLevel()
return difficultyModifier
end
function DBM:HasMapRestrictions()
--Check playerX and playerY. if they are nil restrictions are active
--Restrictions active in all party, raid, pvp, arena maps. No restrictions in "none" or "scenario"
local playerX, playerY = UnitPosition("player")
if not playerX or not playerY then
return true
end
return false
end
function DBM:PlaySoundFile(path, ignoreSFX)
if self.Options.SilentMode then return end
local soundSetting = self.Options.UseSoundChannel
if soundSetting == "Dialog" then
PlaySoundFile(path, "Dialog")
elseif ignoreSFX or soundSetting == "Master" then
PlaySoundFile(path, "Master")
else
PlaySoundFile(path)
end
end
--Future proofing EJ_GetSectionInfo compat layer to make it easier updatable. EJ_GetSectionInfo won't be depricated functions forever.
function DBM:EJ_GetSectionInfo(sectionID)
local info = EJ_GetSectionInfo(sectionID);
local flag1, flag2, flag3, flag4;
local flags = GetSectionIconFlags(sectionID);
if flags then
flag1, flag2, flag3, flag4 = unpack(flags);
end
return info.title, info.description, info.headerType, info.abilityIcon, info.creatureDisplayID, info.siblingSectionID, info.firstChildSectionID, info.filteredByDifficulty, info.link, info.startsOpen, flag1, flag2, flag3, flag4
end
--Handle new spell name requesting with wrapper, to make api changes easier to handle
function DBM:GetSpellInfo(spellId)
local name, rank, icon, castingTime, minRange, maxRange, returnedSpellId = GetSpellInfo(spellId)
if not returnedSpellId then--Bad request all together
DBM:Debug("|cffff0000Invalid call to GetSpellInfo for spellID: |r"..spellId)
return nil
else--Good request, return now
return name, rank, icon, castingTime, minRange, maxRange, returnedSpellId
end
end
function DBM:UnitDebuff(uId, spellInput, spellInput2, spellInput3)
if wowTOC == 80000 then
for i = 1, 60 do
local spellName, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, nameplateShowPersonal, spellId, canApplyAura, isBossDebuff, nameplateShowAll, timeMod, value1, value2, value3 = UnitDebuff(uId, i)
if not spellName then return end
if spellInput == spellName or spellInput == spellId or spellInput2 == spellName or spellInput2 == spellId or spellInput3 == spellName or spellInput3 == spellId then
return spellName, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, nameplateShowPersonal, spellId, canApplyAura, isBossDebuff, nameplateShowAll, timeMod, value1, value2, value3
end
end
else
if type(spellInput) == "number" then
for i = 1, 60 do
local spellName, rank, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, nameplateShowPersonal, spellId, canApplyAura, isBossDebuff, nameplateShowAll, timeMod, value1, value2, value3 = UnitDebuff(uId, i)
if not spellName then return end
if spellInput == spellName or spellInput == spellId or spellInput2 == spellName or spellInput2 == spellId or spellInput3 == spellName or spellInput3 == spellId then
return spellName, rank, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, nameplateShowPersonal, spellId, canApplyAura, isBossDebuff, nameplateShowAll, timeMod, value1, value2, value3
end
end
else
return UnitDebuff(uId, spellInput)
end
end
end
function DBM:UnitBuff(uId, spellInput, spellInput2, spellInput3)
if wowTOC == 80000 then
for i = 1, 60 do
local spellName, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, nameplateShowPersonal, spellId, canApplyAura, isBossDebuff, nameplateShowAll, timeMod, value1, value2, value3 = UnitBuff(uId, i)
if not spellName then return end
if spellInput == spellName or spellInput == spellId or spellInput2 == spellName or spellInput2 == spellId or spellInput3 == spellName or spellInput3 == spellId then
return spellName, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, nameplateShowPersonal, spellId, canApplyAura, isBossDebuff, nameplateShowAll, timeMod, value1, value2, value3
end
end
else
if type(spellInput) == "number" then
for i = 1, 60 do
local spellName, rank, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, nameplateShowPersonal, spellId, canApplyAura, isBossDebuff, nameplateShowAll, timeMod, value1, value2, value3 = UnitBuff(uId, i)
if not spellName then return end
if spellInput == spellName or spellInput == spellId or spellInput2 == spellName or spellInput2 == spellId or spellInput3 == spellName or spellInput3 == spellId then
return spellName, rank, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, nameplateShowPersonal, spellId, canApplyAura, isBossDebuff, nameplateShowAll, timeMod, value1, value2, value3
end
end
else
return UnitBuff(uId, spellInput)
end
end
end
function DBM:PlaySound(path)
if self.Options.SilentMode then return end
local soundSetting = self.Options.UseSoundChannel
if soundSetting == "Master" then
PlaySound(path, "Master")
elseif soundSetting == "Dialog" then
PlaySound(path, "Dialog")
else
PlaySound(path)
end
end
function DBM:UNIT_DIED(args)
local GUID = args.destGUID
if self:IsCreatureGUID(GUID) then
self:OnMobKill(self:GetCIDFromGUID(GUID))
end
if self.Options.AFKHealthWarning and GUID == UnitGUID("player") and not IsEncounterInProgress() and UnitIsAFK("player") and self:AntiSpam(5, "AFK") then--You are afk and losing health, some griever is trying to kill you while you are afk/tabbed out.
self:FlashClientIcon()
self:PlaySoundFile("Sound\\Creature\\CThun\\CThunYouWillDIe.ogg")--So fire an alert sound to save yourself from this person's behavior.
self:AddMsg(DBM_CORE_AFK_WARNING:format(0))
end
end
DBM.UNIT_DESTROYED = DBM.UNIT_DIED
----------------------
-- Timer recovery --
----------------------
do
local requestedFrom = {}
local requestTime = 0
local clientUsed = {}
local sortMe = {}
local function sort(v1, v2)
if v1.revision and not v2.revision then
return true
elseif v2.revision and not v1.revision then
return false
elseif v1.revision and v2.revision then
return v1.revision > v2.revision
else
return (v1.bwversion or 0) > (v2.bwversion or 0)
end
end
function DBM:RequestTimers(requestNum)
twipe(sortMe)
for i, v in pairs(raid) do
tinsert(sortMe, v)
end
tsort(sortMe, sort)
self:Debug("RequestTimers Running", 2)
local selectedClient
local listNum = 0
for i, v in ipairs(sortMe) do
-- If selectedClient player's realm is not same with your's, timer recovery by selectedClient not works at all.
-- SendAddonMessage target channel is "WHISPER" and target player is other realm, no msg sends at all. At same realm, message sending works fine. (Maybe bliz bug or SendAddonMessage function restriction?)
if v.name ~= playerName and UnitIsConnected(v.id) and (not UnitIsGhost(v.id)) and UnitRealmRelationship(v.id) ~= 2 and (GetTime() - (clientUsed[v.name] or 0)) > 10 then
listNum = listNum + 1
if listNum == requestNum then
selectedClient = v
clientUsed[v.name] = GetTime()
break
end
end
end
if not selectedClient then return end
self:Debug("Requesting timer recovery to "..selectedClient.name)
requestedFrom[selectedClient.name] = true
requestTime = GetTime()
SendAddonMessage("D4", "RT", "WHISPER", selectedClient.name)
end
function DBM:ReceiveCombatInfo(sender, mod, time)
if dbmIsEnabled and requestedFrom[sender] and (GetTime() - requestTime) < 5 and #inCombat == 0 then
self:StartCombat(mod, time, "TIMER_RECOVERY")
--Recovery successful, someone sent info, abort other recovery requests
self:Unschedule(self.RequestTimers)
twipe(requestedFrom)
end
end
function DBM:ReceiveTimerInfo(sender, mod, timeLeft, totalTime, id, ...)
if requestedFrom[sender] and (GetTime() - requestTime) < 5 then
local lag = select(4, GetNetStats()) / 1000
for i, v in ipairs(mod.timers) do
if v.id == id then
v:Start(totalTime, ...)
v:Update(totalTime - timeLeft + lag, totalTime, ...)
end
end
end
end
function DBM:ReceiveVariableInfo(sender, mod, name, value)
if requestedFrom[sender] and (GetTime() - requestTime) < 5 then
if value == "true" then
mod.vb[name] = true
elseif value == "false" then
mod.vb[name] = false
else
mod.vb[name] = value
end
end
end
end
do
local spamProtection = {}
function DBM:SendTimers(target)
self:Debug("SendTimers requested by "..target, 2)
local spamForTarget = spamProtection[target] or 0
-- just try to clean up the table, that should keep the hash table at max. 4 entries or something :)
for k, v in pairs(spamProtection) do
if GetTime() - v >= 1 then
spamProtection[k] = nil
end
end
if GetTime() - spamForTarget < 1 then -- just to prevent players from flooding this on purpose
return
end
spamProtection[target] = GetTime()
if UnitInBattleground("player") then
self:SendBGTimers(target)
return
end
if #inCombat < 1 then
--Break timer is up, so send that
--But only if we are not in combat with a boss
if self.Bars:GetBar(DBM_CORE_TIMER_BREAK) then
local remaining = self.Bars:GetBar(DBM_CORE_TIMER_BREAK).timer
SendAddonMessage("D4", "BTR3\t"..remaining, "WHISPER", target)
end
return
end
local mod
for i, v in ipairs(inCombat) do
mod = not v.isCustomMod and v
end
mod = mod or inCombat[1]
self:SendCombatInfo(mod, target)
self:SendVariableInfo(mod, target)
self:SendTimerInfo(mod, target)
end
end
function DBM:SendBGTimers(target)
local mod
if IsActiveBattlefieldArena() then
mod = self:GetModByName("Arenas")
else
-- FIXME: this doesn't work for non-english clients
local zone = GetRealZoneText():gsub(" ", "")--Does this need updating to mapid arta?
mod = self:GetModByName(zone)
end
if mod and mod.timers then
self:SendTimerInfo(mod, target)
end
end
function DBM:SendCombatInfo(mod, target)
return SendAddonMessage("D4", ("CI\t%s\t%s"):format(mod.id, GetTime() - mod.combatInfo.pull), "WHISPER", target)
end
function DBM:SendTimerInfo(mod, target)
for i, v in ipairs(mod.timers) do
for _, uId in ipairs(v.startedTimers) do
local elapsed, totalTime, timeLeft
if select("#", string.split("\t", uId)) > 1 then
elapsed, totalTime = v:GetTime(select(2, string.split("\t", uId)))
else
elapsed, totalTime = v:GetTime()
end
timeLeft = totalTime - elapsed
if timeLeft > 0 and totalTime > 0 then
SendAddonMessage("D4", ("TI\t%s\t%s\t%s\t%s"):format(mod.id, timeLeft, totalTime, uId), "WHISPER", target)
end
end
end
end
function DBM:SendVariableInfo(mod, target)
for vname, v in pairs(mod.vb) do
local v2 = tostring(v)
if v2 then
SendAddonMessage("D4", ("VI\t%s\t%s\t%s"):format(mod.id, vname, v2), "WHISPER", target)
end
end
end
do
function DBM:PLAYER_ENTERING_WORLD()
if not self.Options.DontShowReminders then
C_TimerAfter(25, function() if self.Options.SilentMode then self:AddMsg(DBM_SILENT_REMINDER) end end)
C_TimerAfter(30, function() if not self.Options.SettingsMessageShown then self.Options.SettingsMessageShown = true self:AddMsg(DBM_HOW_TO_USE_MOD) end end)
end
if type(RegisterAddonMessagePrefix) == "function" then
if not RegisterAddonMessagePrefix("D4") then -- main prefix for DBM4
self:AddMsg("Error: unable to register DBM addon message prefix (reached client side addon message filter limit), synchronization will be unavailable") -- TODO: confirm that this actually means that the syncs won't show up
end
if not RegisterAddonMessagePrefix("BigWigs") then
self:AddMsg("Error: unable to register BigWigs addon message prefix (reached client side addon message filter limit), BigWigs version checks will be unavailable")
end
if not RegisterAddonMessagePrefix("Transcriptor") then
self:AddMsg("Error: unable to register Transcriptor addon message prefix (reached client side addon message filter limit)")
end
end
if self.Options.sfxDisabled then--Check if sound was disabled by previous session and not re-enabled.
self.Options.sfxDisabled = nil
SetCVar("Sound_EnableSFX", 1)
end
if self.Options.RestoreRange then self.Options.RestoreRange = nil end--User DCed while this was true, clear it
end
end
------------------------------------
-- Auto-respond/Status whispers --
------------------------------------
do
local function getNumAlivePlayers()
local alive = 0
if IsInRaid() then
for i = 1, GetNumGroupMembers() do
alive = alive + ((UnitIsDeadOrGhost("raid"..i) and 0) or 1)
end
else
alive = (UnitIsDeadOrGhost("player") and 0) or 1
for i = 1, GetNumSubgroupMembers() do
alive = alive + ((UnitIsDeadOrGhost("party"..i) and 0) or 1)
end
end
return alive
end
--Cleanup in 8.x with C_Map.GetMapGroupMembersInfo
local function getNumRealAlivePlayers()
local alive = 0
local isInInstance = IsInInstance() or false
local currentMapId = isInInstance and select(4, UnitPosition("player")) or C_Map and C_Map.GetBestMapForUnit("player") or GetPlayerMapAreaID("player")
if not currentMapId then--REMOVE in 8.x, C_Map should never fail
SetMapToCurrentZone()
currentMapId = C_Map and C_Map.GetCurrentMapID("player") or GetCurrentMapAreaID()
end
local currentMapName = C_Map and C_Map.GetMapInfo(currentMapId) or GetMapNameByID(currentMapId)
if IsInRaid() then
for i = 1, GetNumGroupMembers() do
if isInInstance and select(4, UnitPosition("raid"..i)) == currentMapId or select(7, GetRaidRosterInfo(i)) == currentMapName then
alive = alive + ((UnitIsDeadOrGhost("raid"..i) and 0) or 1)
end
end
else
alive = (UnitIsDeadOrGhost("player") and 0) or 1
for i = 1, GetNumSubgroupMembers() do
if isInInstance and select(4, UnitPosition("party"..i)) == currentMapId or select(7, GetRaidRosterInfo(i)) == currentMapName then
alive = alive + ((UnitIsDeadOrGhost("party"..i) and 0) or 1)
end
end
end
return alive
end
local function isOnSameServer(presenceId)
local toonID, client = select(6, BNGetFriendInfoByID(presenceId))
if client ~= "WoW" then
return false
end
return GetRealmName() == select(4, BNGetGameAccountInfo(toonID))
end
-- sender is a presenceId for real id messages, a character name otherwise
local function onWhisper(msg, sender, isRealIdMessage)
if statusWhisperDisabled then return end--RL has disabled status whispers for entire raid.
if msg:find(chatPrefix) and not InCombatLockdown() and DBM:AntiSpam(60, "Ogron") and DBM.Options.AutoReplySound then
--Might need more validation if people figure out they can just whisper people with chatPrefix to trigger it.
--However if I have to add more validation it probably won't work in most languages :\ So lets hope antispam and combat check is enough
DBM:PlaySoundFile("sound\\creature\\aggron1\\VO_60_HIGHMAUL_AGGRON_1_AGGRO_1.ogg")
elseif msg == "status" and #inCombat > 0 and DBM.Options.StatusEnabled then
if not difficultyText then -- prevent error when timer recovery function worked and etc (StartCombat not called)
savedDifficulty, difficultyText, difficultyIndex, LastGroupSize, difficultyModifier = DBM:GetCurrentInstanceDifficulty()
end
local mod
for i, v in ipairs(inCombat) do
mod = not v.isCustomMod and v
end
mod = mod or inCombat[1]
if IsInScenarioGroup() and not mod.soloChallenge then return end--status not really useful on scenario mods since there is no way to report progress as a percent. We just ignore it.
local hp = mod.highesthealth and mod:GetHighestBossHealth() or mod:GetLowestBossHealth()
local hpText = mod.CustomHealthUpdate and mod:CustomHealthUpdate() or hp and ("%d%%"):format(hp) or DBM_CORE_UNKNOWN
if mod.vb.phase then
hpText = hpText.." ("..SCENARIO_STAGE:format(mod.vb.phase)..")"
end
if mod.numBoss then
local bossesKilled = mod.numBoss - mod.vb.bossLeft
hpText = hpText.." ("..BOSSES_KILLED:format(bossesKilled, mod.numBoss)..")"
end
sendWhisper(sender, chatPrefix..DBM_CORE_STATUS_WHISPER:format(difficultyText..(mod.combatInfo.name or ""), hpText, IsInInstance() and getNumRealAlivePlayers() or getNumAlivePlayers(), DBM:GetNumRealGroupMembers()))
elseif #inCombat > 0 and DBM.Options.AutoRespond and (isRealIdMessage and (not isOnSameServer(sender) or not DBM:GetRaidUnitId(select(5, BNGetFriendInfoByID(sender)))) or not isRealIdMessage and not DBM:GetRaidUnitId(sender)) then
if not difficultyText then -- prevent error when timer recovery function worked and etc (StartCombat not called)
savedDifficulty, difficultyText, difficultyIndex, LastGroupSize, difficultyModifier = DBM:GetCurrentInstanceDifficulty()
end
local mod
for i, v in ipairs(inCombat) do
mod = not v.isCustomMod and v
end
mod = mod or inCombat[1]
local hp = mod.highesthealth and mod:GetHighestBossHealth() or mod:GetLowestBossHealth()
local hpText = mod.CustomHealthUpdate and mod:CustomHealthUpdate() or hp and ("%d%%"):format(hp) or DBM_CORE_UNKNOWN
if mod.vb.phase then
hpText = hpText.." ("..SCENARIO_STAGE:format(mod.vb.phase)..")"
end
if mod.numBoss then
local bossesKilled = mod.numBoss - mod.vb.bossLeft
hpText = hpText.." ("..BOSSES_KILLED:format(bossesKilled, mod.numBoss)..")"
end
if not autoRespondSpam[sender] then
if IsInScenarioGroup() and not mod.soloChallenge then
sendWhisper(sender, chatPrefix..DBM_CORE_AUTO_RESPOND_WHISPER_SCENARIO:format(playerName, difficultyText..(mod.combatInfo.name or ""), getNumAlivePlayers(), DBM:GetNumGroupMembers()))
else
sendWhisper(sender, chatPrefix..DBM_CORE_AUTO_RESPOND_WHISPER:format(playerName, difficultyText..(mod.combatInfo.name or ""), hpText, IsInInstance() and getNumRealAlivePlayers() or getNumAlivePlayers(), DBM:GetNumRealGroupMembers()))
end
DBM:AddMsg(DBM_CORE_AUTO_RESPONDED)
end
autoRespondSpam[sender] = true
end
end
function DBM:CHAT_MSG_WHISPER(msg, name, _, _, _, status)
if status ~= "GM" then
name = Ambiguate(name, "none")
return onWhisper(msg, name, false)
end
end
function DBM:CHAT_MSG_BN_WHISPER(msg, ...)
local presenceId = select(12, ...) -- srsly?
return onWhisper(msg, presenceId, true)
end
end
--This completely unregisteres or registers distruptive events so they don't obstruct combat
--Toggle is for if we are turning off or on.
--Custom is for external mods to call function without duplication and allowing pvp mods custom toggle.
do
local unregisteredEvents = {}
local function DisableEvent(frameName, eventName)
if frameName:IsEventRegistered(eventName) then
frameName:UnregisterEvent(eventName)
unregisteredEvents[eventName] = true
end
end
local function EnableEvent(frameName, eventName)
if unregisteredEvents[eventName] then
frameName:RegisterEvent(eventName)
unregisteredEvents[eventName] = nil
end
end
function DBM:HideBlizzardEvents(toggle, custom)
if toggle == 1 then
if self.Options.HideQuestTooltips then
SetCVar("showQuestTrackingTooltips", 0)
end
if (self.Options.HideBossEmoteFrame2 or custom) and not testBuild then
DisableEvent(RaidBossEmoteFrame, "RAID_BOSS_EMOTE")
DisableEvent(RaidBossEmoteFrame, "RAID_BOSS_WHISPER")
DisableEvent(RaidBossEmoteFrame, "CLEAR_BOSS_EMOTES")
SOUNDKIT.UI_RAID_BOSS_WHISPER_WARNING = 999999--Since blizzard can still play the sound via RaidBossEmoteFrame_OnEvent (line 148) via encounter scripts in certain cases despite the frame having no registered events
end
if self.Options.HideGarrisonToasts or custom then
DisableEvent(AlertFrame, "GARRISON_MISSION_FINISHED")
DisableEvent(AlertFrame, "GARRISON_BUILDING_ACTIVATABLE")
end
if self.Options.HideGuildChallengeUpdates or custom then
DisableEvent(AlertFrame, "GUILD_CHALLENGE_COMPLETED")
end
elseif toggle == 0 then
if self.Options.HideQuestTooltips then
SetCVar("showQuestTrackingTooltips", 1)
end
if (self.Options.HideBossEmoteFrame2 or custom) and not testBuild then
EnableEvent(RaidBossEmoteFrame, "RAID_BOSS_EMOTE")
EnableEvent(RaidBossEmoteFrame, "RAID_BOSS_WHISPER")
EnableEvent(RaidBossEmoteFrame, "CLEAR_BOSS_EMOTES")
SOUNDKIT.UI_RAID_BOSS_WHISPER_WARNING = 37666--restore it
end
if self.Options.HideGarrisonToasts then
EnableEvent(AlertFrame, "GARRISON_MISSION_FINISHED")
EnableEvent(AlertFrame, "GARRISON_BUILDING_ACTIVATABLE")
end
if self.Options.HideGuildChallengeUpdates then
EnableEvent(AlertFrame, "GUILD_CHALLENGE_COMPLETED")
end
end
end
end
--------------------------
-- Enable/Disable DBM --
--------------------------
do
local forceDisabled = false
function DBM:Disable(forceDisable)
unscheduleAll()
dbmIsEnabled = false
forceDisabled = forceDisable
end
function DBM:Enable()
if not forceDisabled then
dbmIsEnabled = true
end
end
function DBM:IsEnabled()
return dbmIsEnabled
end
end
-----------------------
-- Misc. Functions --
-----------------------
function DBM:AddMsg(text, prefix)
local tag = prefix or (self.localization and self.localization.general.name) or "DBM"
local frame = _G[tostring(DBM.Options.ChatFrame)]
frame = frame and frame:IsShown() and frame or DEFAULT_CHAT_FRAME
if prefix ~= false then
frame:AddMessage(("|cffff7d0a<|r|cffffd200%s|r|cffff7d0a>|r %s"):format(tostring(tag), tostring(text)), 0.41, 0.8, 0.94)
else
frame:AddMessage(text, 0.41, 0.8, 0.94)
end
end
AddMsg = DBM.AddMsg
function DBM:Debug(text, level)
if not self.Options or not self.Options.DebugMode then return end
if (level or 1) <= DBM.Options.DebugLevel then
local frame = _G[tostring(DBM.Options.ChatFrame)]
frame = frame and frame:IsShown() and frame or DEFAULT_CHAT_FRAME
frame:AddMessage("|cffff7d0aDBM Debug:|r "..text, 1, 1, 1)
end
end
do
local testMod
local testWarning1, testWarning2, testWarning3
local testTimer1, testTimer2, testTimer3, testTimer4, testTimer5, testTimer6, testTimer7, testTimer8
local testCount1, testCount2
local testSpecialWarning1, testSpecialWarning2, testSpecialWarning3
function DBM:DemoMode()
if not testMod then
testMod = self:NewMod("TestMod")
self:GetModLocalization("TestMod"):SetGeneralLocalization{ name = "Test Mod" }
testWarning1 = testMod:NewAnnounce("%s", 1, "Interface\\Icons\\Spell_Nature_WispSplode")
testWarning2 = testMod:NewAnnounce("%s", 2, "Interface\\Icons\\Spell_Shadow_ShadesOfDarkness")
testWarning3 = testMod:NewAnnounce("%s", 3, "Interface\\Icons\\Spell_Fire_SelfDestruct")
testTimer1 = testMod:NewTimer(20, "%s", "Interface\\Icons\\Spell_Nature_WispSplode", nil, nil)
testTimer2 = testMod:NewTimer(20, "%s ", "Interface\\ICONS\\INV_Misc_Head_Orc_01.blp", nil, nil, 1)
testTimer3 = testMod:NewTimer(20, "%s ", "Interface\\Icons\\Spell_Shadow_ShadesOfDarkness", nil, nil, 3, DBM_CORE_MAGIC_ICON)
testTimer4 = testMod:NewTimer(20, "%s ", "Interface\\Icons\\Spell_Nature_WispSplode", nil, nil, 4, DBM_CORE_INTERRUPT_ICON)
testTimer5 = testMod:NewTimer(20, "%s ", "Interface\\Icons\\Spell_Fire_SelfDestruct", nil, nil, 2, DBM_CORE_HEALER_ICON)
testTimer6 = testMod:NewTimer(20, "%s ", "Interface\\Icons\\Spell_Nature_WispSplode", nil, nil, 5, DBM_CORE_TANK_ICON)
testTimer7 = testMod:NewTimer(20, "%s ", "Interface\\Icons\\Spell_Nature_WispSplode", nil, nil, 6)
testTimer8 = testMod:NewTimer(20, "%s ", "Interface\\Icons\\Spell_Nature_WispSplode", nil, nil, 7)
testCount1 = testMod:NewCountdown(0, 0, nil, nil, nil, true)
testCount2 = testMod:NewCountdown(0, 0, nil, nil, nil, true, true)
testSpecialWarning1 = testMod:NewSpecialWarning("%s", nil, nil, nil, 1, 2)
testSpecialWarning2 = testMod:NewSpecialWarning(" %s ", nil, nil, nil, 2, 2)
testSpecialWarning3 = testMod:NewSpecialWarning(" %s ", nil, nil, nil, 3, 2) -- hack: non auto-generated special warnings need distinct names (we could go ahead and give them proper names with proper localization entries, but this is much easier)
end
testTimer1:Start(10, "Test Bar")
testTimer2:Start(30, "Adds")
testTimer3:Start(43, "Evil Debuff")
testTimer4:Start(20, "Important Interrupt")
testTimer5:Start(60, "Boom!")
testTimer6:Start(35, "Handle your Role")
testTimer7:Start(50, "Next Stage")
testTimer8:Start(55, "Custom User Bar")
testCount1:Cancel()
testCount1:Start(43)
testCount2:Cancel()
testCount2:Start(60)
testWarning1:Cancel()
testWarning2:Cancel()
testWarning3:Cancel()
testSpecialWarning1:Cancel()
testSpecialWarning1:CancelVoice()
testSpecialWarning2:Cancel()
testSpecialWarning2:CancelVoice()
testSpecialWarning3:Cancel()
testSpecialWarning3:CancelVoice()
testWarning1:Show("Test-mode started...")
testWarning1:Schedule(62, "Test-mode finished!")
testWarning3:Schedule(50, "Boom in 10 sec!")
testWarning3:Schedule(20, "Pew Pew Laser Owl!")
testWarning2:Schedule(38, "Evil Spell in 5 sec!")
testWarning2:Schedule(43, "Evil Spell!")
testWarning1:Schedule(10, "Test bar expired!")
testSpecialWarning1:Schedule(20, "Pew Pew Laser Owl")
testSpecialWarning1:ScheduleVoice(20, "runaway")
testSpecialWarning2:Schedule(43, "Fear!")
testSpecialWarning2:ScheduleVoice(43, "fearsoon")
testSpecialWarning3:Schedule(60, "Boom!")
testSpecialWarning3:ScheduleVoice(60, "defensive")
end
end
DBM.Bars:SetAnnounceHook(function(bar)
local prefix
if bar.color and bar.color.r == 1 and bar.color.g == 0 and bar.color.b == 0 then
prefix = DBM_CORE_HORDE or FACTION_HORDE
elseif bar.color and bar.color.r == 0 and bar.color.g == 0 and bar.color.b == 1 then
prefix = DBM_CORE_ALLIANCE or FACTION_ALLIANCE
end
if prefix then
return ("%s: %s %d:%02d"):format(prefix, _G[bar.frame:GetName().."BarName"]:GetText(), floor(bar.timer / 60), bar.timer % 60)
end
end)
function DBM:Capitalize(str)
local firstByte = str:byte(1, 1)
local numBytes = 1
if firstByte >= 0xF0 then -- firstByte & 0b11110000
numBytes = 4
elseif firstByte >= 0xE0 then -- firstByte & 0b11100000
numBytes = 3
elseif firstByte >= 0xC0 then -- firstByte & 0b11000000
numBytes = 2
end
return str:sub(1, numBytes):upper()..str:sub(numBytes + 1):lower()
end
--copied from big wigs with permission from funkydude. Modified by MysticalOS
function DBM:RoleCheck(ignoreLoot)
local spec = GetSpecialization()
if not spec then return end
local role = GetSpecializationRole(spec)
if not role then return end
local specID = GetLootSpecialization()
local _, _, _, _, lootrole = GetSpecializationInfoByID(specID)
if not InCombatLockdown() and not IsFalling() and ((IsPartyLFG() and (difficultyIndex == 14 or difficultyIndex == 15)) or not IsPartyLFG()) then
if UnitGroupRolesAssigned("player") ~= role then
UnitSetRole("player", role)
end
end
--Loot reminder even if spec isn't known or we are in LFR where we have a valid for role without us being ones that set us.
if not ignoreLoot and lootrole and (role ~= lootrole) and self.Options.RoleSpecAlert then
self:AddMsg(DBM_CORE_LOOT_SPEC_REMINDER:format(_G[role] or DBM_CORE_UNKNOWN, _G[lootrole]))
end
end
-- An anti spam function to throttle spammy events (e.g. SPELL_AURA_APPLIED on all group members)
-- @param time the time to wait between two events (optional, default 2.5 seconds)
-- @param id the id to distinguish different events (optional, only necessary if your mod keeps track of two different spam events at the same time)
function DBM:AntiSpam(time, id)
if GetTime() - (id and (self["lastAntiSpam" .. tostring(id)] or 0) or self.lastAntiSpam or 0) > (time or 2.5) then
if id then
self["lastAntiSpam" .. tostring(id)] = GetTime()
else
self.lastAntiSpam = GetTime()
end
return true
else
return false
end
end
function DBM:GetTOC()
return wowTOC, testBuild, wowVersionString
end
function DBM:InCombat()
if #inCombat > 0 then
return true
end
return false
end
function DBM:FlashClientIcon()
if self:AntiSpam(5, "FLASH") then
FlashClientIcon()
end
end
do
local iconStrings = {[1] = RAID_TARGET_1, [2] = RAID_TARGET_2, [3] = RAID_TARGET_3, [4] = RAID_TARGET_4, [5] = RAID_TARGET_5, [6] = RAID_TARGET_6, [7] = RAID_TARGET_7, [8] = RAID_TARGET_8,}
function DBM:IconNumToString(number)
return iconStrings[number] or number
end
function DBM:IconNumToTexture(number)
return "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_"..number..".blp:12:12|t" or number
end
end
--To speed up creating new mods.
function DBM:FindDungeonIDs()
for i=1, 3000 do
local dungeon = GetRealZoneText(i)
if dungeon and dungeon ~= "" then
self:AddMsg(i..": "..dungeon)
end
end
end
function DBM:FindInstanceIDs()
for i=1, 3000 do
local instance = EJ_GetInstanceInfo(i)
if instance then
self:AddMsg(i..": "..instance)
end
end
end
--/run DBM:FindEncounterIDs(1028)--Kul Tiras
--/run DBM:FindEncounterIDs(1029)--Zandalar
--/run DBM:FindEncounterIDs(1031)--Uldir
--/run DBM:FindEncounterIDs(1001, 23)--Dungeon Template (mythic difficulty)
function DBM:FindEncounterIDs(instanceID, diff)
if not instanceID then
self:AddMsg("Error: Function requires instanceID be provided")
end
if not diff then diff = 14 end--Default to "normal" in 6.0+ if diff arg not given.
EJ_SetDifficulty(diff)--Make sure it's set to right difficulty or it'll ignore mobs (ie ra-den if it's not set to heroic). Use user specified one as primary, with curernt zone difficulty as fallback
for i=1, 25 do
local name, _, encounterID = EJ_GetEncounterInfoByIndex(i, instanceID)
if name then
self:AddMsg(encounterID..": "..name)
end
end
end
--Taint the script that disables /run /dump, etc
--ScriptsDisallowedForBeta = function() return false end
-------------------
-- Movie Filter --
-------------------
do
local neverFilter = {
[486] = true, -- Tomb of Sarg Intro
[487] = true, -- Alliance Broken Shore cut-scene
[488] = true, -- Horde Broken Shore cut-scene
[489] = true, -- Unknown, currently encrypted
[490] = true, -- Unknown, currently encrypted
}
function DBM:PLAY_MOVIE(id)
if id and not neverFilter[id] then
DBM:Debug("PLAY_MOVIE fired for ID: "..id, 2)
local isInstance, instanceType = IsInInstance()
if not isInstance or C_Garrison:IsOnGarrisonMap() or instanceType == "scenario" or DBM.Options.MovieFilter == "Never" then return end
if DBM.Options.MovieFilter == "Block" or DBM.Options.MovieFilter == "AfterFirst" and DBM.Options.MoviesSeen[id] then
MovieFrame:Hide()--can only just hide movie frame safely now, which means can't stop audio anymore :\
DBM:AddMsg(DBM_CORE_MOVIE_SKIPPED)
else
DBM.Options.MoviesSeen[id] = true
end
end
end
function DBM:CINEMATIC_START()
self:Debug("CINEMATIC_START fired", 2)
local isInstance, instanceType = IsInInstance()
if not isInstance or C_Garrison:IsOnGarrisonMap() or instanceType == "scenario" or self.Options.MovieFilter == "Never" then return end
SetMapToCurrentZone()
local currentMapID
if C_Map then
currentMapID = C_Map.GetBestMapForUnit("player")
else
currentMapID = GetCurrentMapAreaID()
end
if not currentMapID then return end--Protection from map failures in zones that have no maps yet
local currentFloor = GetCurrentMapDungeonLevel and GetCurrentMapDungeonLevel() or 0--REMOVE In 8.x
if self.Options.MovieFilter == "Block" or self.Options.MovieFilter == "AfterFirst" and self.Options.MoviesSeen[currentMapID..currentFloor] then
CinematicFrame_CancelCinematic()
self:AddMsg(DBM_CORE_MOVIE_SKIPPED)
else
self.Options.MoviesSeen[currentMapID..currentFloor] = true
end
end
end
----------------------------
-- Boss Mod Constructor --
----------------------------
do
local modsById = setmetatable({}, {__mode = "v"})
local mt = {__index = bossModPrototype}
function DBM:NewMod(name, modId, modSubTab, instanceId, nameModifier)
name = tostring(name) -- the name should never be a number of something as it confuses sync handlers that just receive some string and try to get the mod from it
if name == "DBM-ProfilesDummy" then return end
if modsById[name] then error("DBM:NewMod(): Mod names are used as IDs and must therefore be unique.", 2) end
local obj = setmetatable(
{
Options = {
Enabled = true,
},
DefaultOptions = {
Enabled = true,
},
subTab = modSubTab,
optionCategories = {
},
categorySort = {"announce", "announceother", "announcepersonal", "announcerole", "timer", "sound", "misc"},
id = name,
announces = {},
specwarns = {},
timers = {},
countdowns = {},
vb = {},
iconRestore = {},
modId = modId,
instanceId = instanceId,
revision = 0,
SyncThreshold = 8,
localization = self:GetModLocalization(name)
},
mt
)
for i, v in ipairs(self.AddOns) do
if v.modId == modId then
obj.addon = v
break
end
end
if tonumber(name) then
local t = EJ_GetEncounterInfo(tonumber(name))
if type(nameModifier) == "number" then--Get name form EJ_GetCreatureInfo
t = select(2, EJ_GetCreatureInfo(nameModifier, tonumber(name)))
elseif type(nameModifier) == "function" then--custom name modify function
t = nameModifier(t or name)
else--default name modify
t = tostring(t)
t = string.split(",", t or name)
end
obj.localization.general.name = t or name
obj.modelId = select(4, EJ_GetCreatureInfo(1, tonumber(name)))
elseif name:match("z%d+") then
local t = GetRealZoneText(string.sub(name, 2))
if type(nameModifier) == "number" then--do nothing
elseif type(nameModifier) == "function" then--custom name modify function
t = nameModifier(t or name)
else--default name modify
t = string.split(",", t or name)
end
obj.localization.general.name = t or name
elseif name:match("d%d+") then
local t = GetDungeonInfo(string.sub(name, 2))
if type(nameModifier) == "number" then--do nothing
elseif type(nameModifier) == "function" then--custom name modify function
t = nameModifier(t or name)
else--default name modify
t = string.split(",", t or name)
end
obj.localization.general.name = t or name
else
obj.localization.general.name = obj.localization.general.name or name
end
tinsert(self.Mods, obj)
if modId then
self.ModLists[modId] = self.ModLists[modId] or {}
tinsert(self.ModLists[modId], name)
end
modsById[name] = obj
obj:SetZone()
return obj
end
function DBM:GetModByName(name)
return modsById[tostring(name)]
end
end
-----------------------
-- General Methods --
-----------------------
bossModPrototype.RegisterEvents = DBM.RegisterEvents
bossModPrototype.UnregisterInCombatEvents = DBM.UnregisterInCombatEvents
bossModPrototype.AddMsg = DBM.AddMsg
bossModPrototype.RegisterShortTermEvents = DBM.RegisterShortTermEvents
bossModPrototype.UnregisterShortTermEvents = DBM.UnregisterShortTermEvents
function bossModPrototype:SetZone(...)
if select("#", ...) == 0 then
self.zones = {}
if self.addon and self.addon.mapId then
for i, v in ipairs(self.addon.mapId) do
self.zones[v] = true
end
end
elseif select(1, ...) ~= DBM_DISABLE_ZONE_DETECTION then
self.zones = {}
for i = 1, select("#", ...) do
self.zones[select(i, ...)] = true
end
else -- disable zone detection
self.zones = nil
end
end
function bossModPrototype:Toggle()
if self.Options.Enabled then
self:DisableMod()
else
self:EnableMod()
end
end
function bossModPrototype:EnableMod()
self.Options.Enabled = true
end
function bossModPrototype:DisableMod()
self:Stop()
self.Options.Enabled = false
end
function bossModPrototype:Stop()
for i, v in ipairs(self.timers) do
v:Stop()
end
for i, v in ipairs(self.countdowns) do
v:Stop()
end
self:Unschedule()
end
function bossModPrototype:SetUsedIcons(...)
self.usedIcons = {}
for i = 1, select("#", ...) do
self.usedIcons[select(i, ...)] = true
end
end
function bossModPrototype:RegisterOnUpdateHandler(func, interval)
startScheduler()
if type(func) ~= "function" then return end
self.elapsed = 0
self.updateInterval = interval or 0
updateFunctions[self] = func
end
function bossModPrototype:UnregisterOnUpdateHandler()
self.elapsed = nil
self.updateInterval = nil
twipe(updateFunctions)
end
--------------
-- Events --
--------------
function bossModPrototype:RegisterEventsInCombat(...)
if self.inCombatOnlyEvents then
geterrorhandler()("combat events already set")
end
self.inCombatOnlyEvents = {...}
for k, v in pairs(self.inCombatOnlyEvents) do
if v:sub(0, 5) == "UNIT_" and v:sub(v:len() - 10) ~= "_UNFILTERED" and not v:find(" ") and v ~= "UNIT_DIED" and v ~= "UNIT_DESTROYED" then
-- legacy event, oh noes
self.inCombatOnlyEvents[k] = v .. " boss1 boss2 boss3 boss4 boss5 target focus"
end
end
end
-----------------------
-- Utility Methods --
-----------------------
function bossModPrototype:IsDifficulty(...)
local diff = savedDifficulty or DBM:GetCurrentInstanceDifficulty()
for i = 1, select("#", ...) do
if diff == select(i, ...) then
return true
end
end
return false
end
function bossModPrototype:IsLFR()
local diff = savedDifficulty or DBM:GetCurrentInstanceDifficulty()
if diff == "lfr" or diff == "lfr25" then
return true
end
return false
end
--Dungeons: normal, heroic. Raids: LFR, normal
function bossModPrototype:IsEasy()
local diff = savedDifficulty or DBM:GetCurrentInstanceDifficulty()
if diff == "normal" or diff == "lfr" or diff == "lfr25" or diff == "heroic5" or diff == "normal5" then
return true
end
return false
end
--Dungeons, mythic, mythic+. Raids: heroic, mythic
function bossModPrototype:IsHard()
local diff = savedDifficulty or DBM:GetCurrentInstanceDifficulty()
if diff == "mythic" or diff == "challenge5" or diff == "heroic" then
return true
end
return false
end
function bossModPrototype:IsNormal()
local diff = savedDifficulty or DBM:GetCurrentInstanceDifficulty()
if diff == "normal" or diff == "normal5" or diff == "normal10" or diff == "normal25" then
return true
end
return false
end
function bossModPrototype:IsHeroic()
local diff = savedDifficulty or DBM:GetCurrentInstanceDifficulty()
if diff == "heroic" or diff == "heroic5" or diff == "heroic10" or diff == "heroic25" then
return true
end
return false
end
function bossModPrototype:IsMythic()
local diff = savedDifficulty or DBM:GetCurrentInstanceDifficulty()
if diff == "mythic" then
return true
end
return false
end
function bossModPrototype:IsEvent()
local diff = savedDifficulty or DBM:GetCurrentInstanceDifficulty()
if diff == "event5" or diff == "event20" or diff == "event40" then
return true
end
return false
end
function bossModPrototype:IsTrivial(level)
if difficultyIndex == 24 then return false end--Timewalker dungeon, ignore level and return false for trivial
if playerLevel >= level then
return true
end
return false
end
--Skip param is used when CheckInterruptFilter is actually being used for a simpe target/focus check and nothing more.
--checkCooldown should never be passed with skip or COUNT interrupt warnings. It should be passed with any other interrupt filter
function bossModPrototype:CheckInterruptFilter(sourceGUID, skip, checkCooldown)
if DBM.Options.FilterInterrupt2 == "None" and not skip then return true end--use doesn't want to use interrupt filter, always return true
--Pummel, Mind Freeze, Counterspell, Kick, Skull Bash, Rebuke, Silence, Wind Shear
local InterruptAvailable = true
local requireCooldown = checkCooldown
if (DBM.Options.FilterInterrupt2 == "onlyTandF") or self.isTrashMod and (DBM.Options.FilterInterrupt2 == "TandFandBossCooldown") then
requireCooldown = false
end
if requireCooldown and ((GetSpellCooldown(6552)) ~= 0 or (GetSpellCooldown(47528)) ~= 0 or (GetSpellCooldown(2139)) ~= 0 or (GetSpellCooldown(1766)) ~= 0 or (GetSpellCooldown(106839)) ~= 0 or (GetSpellCooldown(96231)) ~= 0 or (GetSpellCooldown(15487)) ~= 0 or (GetSpellCooldown(57994)) ~= 0) then
InterruptAvailable = false--checkCooldown check requested and player has no spell that can interrupt available
end
if InterruptAvailable and (UnitGUID("target") == sourceGUID or UnitGUID("focus") == sourceGUID) then
return true
end
return false
end
function bossModPrototype:CheckDispelFilter()
if not DBM.Options.FilterDispel then return true end
--Druid: Nature's Cure (88423), Remove Corruption (2782), Monk: Detox (115450), Priest: Purify (527), Plaadin: Cleanse (4987), Shaman: Cleanse Spirit (51886), Purify Spirit (77130), Mage: Remove Curse (475)
--start, duration, enable = GetSpellCooldown
--start & duration == 0 if spell not on cd
if (GetSpellCooldown(88423)) ~= 0 or (GetSpellCooldown(2782)) ~= 0 or (GetSpellCooldown(115450)) ~= 0 or (GetSpellCooldown(527)) ~= 0 or (GetSpellCooldown(4987)) ~= 0 or (GetSpellCooldown(51886)) ~= 0 or (GetSpellCooldown(77130)) ~= 0 or (GetSpellCooldown(475)) ~= 0 then
return false
end
return true
end
function bossModPrototype:IsCriteriaCompleted(criteriaIDToCheck)
if not criteriaIDToCheck then
geterrorhandler()("usage: mod:IsCriteriaComplected(criteriaId)")
return false
end
local _, _, numCriteria = C_Scenario.GetStepInfo()
for i = 1, numCriteria do
local _, _, criteriaCompleted, _, _, _, _, _, criteriaID = C_Scenario.GetCriteriaInfo(i)
if criteriaID == criteriaIDToCheck and criteriaCompleted then
return true
end
end
return false
end
function bossModPrototype:LatencyCheck()
return select(4, GetNetStats()) < DBM.Options.LatencyThreshold
end
function bossModPrototype:CheckBigWigs(name)
if raid[name] and raid[name].bwversion then
return raid[name].bwversion
else
return false
end
end
bossModPrototype.IconNumToString = DBM.IconNumToString
bossModPrototype.IconNumToTexture = DBM.IconNumToTexture
bossModPrototype.AntiSpam = DBM.AntiSpam
bossModPrototype.HasMapRestrictions = DBM.HasMapRestrictions
bossModPrototype.GetUnitCreatureId = DBM.GetUnitCreatureId
bossModPrototype.GetCIDFromGUID = DBM.GetCIDFromGUID
bossModPrototype.IsCreatureGUID = DBM.IsCreatureGUID
bossModPrototype.GetUnitIdFromGUID = DBM.GetUnitIdFromGUID
do
local bossTargetuIds = {
"boss1", "boss2", "boss3", "boss4", "boss5", "focus", "target"
}
local targetScanCount = {}
local repeatedScanEnabled = {}
local function getBossTarget(guid, scanOnlyBoss)
local name, uid, bossuid
local cacheuid = bossuIdCache[guid] or "boss1"
if UnitGUID(cacheuid) == guid then
bossuid = cacheuid
name = DBM:GetUnitFullName(cacheuid.."target")
uid = cacheuid.."target"
bossuIdCache[guid] = bossuid
end
if name then return name, uid, bossuid end
for i, uId in ipairs(bossTargetuIds) do
if UnitGUID(uId) == guid then
bossuid = uId
name = DBM:GetUnitFullName(uId.."target")
uid = uId.."target"
bossuIdCache[guid] = bossuid
break
end
end
if name or scanOnlyBoss then return name, uid, bossuid end
-- Now lets check nameplates
for i = 1, 40 do
if UnitGUID("nameplate"..i) == guid then
bossuid = "nameplate"..i
name = DBM:GetUnitFullName("nameplate"..i.."target")
uid = "nameplate"..i.."target"
bossuIdCache[guid] = bossuid
break
end
end
if name then return name, uid, bossuid end
-- failed to detect from default uIds, scan all group members's target.
if IsInRaid() then
for i = 1, GetNumGroupMembers() do
if UnitGUID("raid"..i.."target") == guid then
bossuid = "raid"..i.."target"
name = DBM:GetUnitFullName("raid"..i.."targettarget")
uid = "raid"..i.."targettarget"
bossuIdCache[guid] = bossuid
break
end
end
elseif IsInGroup() then
for i = 1, GetNumSubgroupMembers() do
if UnitGUID("party"..i.."target") == guid then
bossuid = "party"..i.."target"
name = DBM:GetUnitFullName("party"..i.."targettarget")
uid = "party"..i.."targettarget"
bossuIdCache[guid] = bossuid
break
end
end
end
return name, uid, bossuid
end
function bossModPrototype:GetBossTarget(cidOrGuid, scanOnlyBoss)
local name, uid, bossuid
if type(cidOrGuid) == "number" then
local cidOrGuid = cidOrGuid or self.creatureId
local cacheuid = bossuIdCache[cidOrGuid] or "boss1"
if self:GetUnitCreatureId(cacheuid) == cidOrGuid then
bossuIdCache[cidOrGuid] = cacheuid
bossuIdCache[UnitGUID(cacheuid)] = cacheuid
name, uid, bossuid = getBossTarget(UnitGUID(cacheuid), scanOnlyBoss)
else
local found = false
for i, uId in ipairs(bossTargetuIds) do
if self:GetUnitCreatureId(uId) == cidOrGuid then
found = true
bossuIdCache[cidOrGuid] = uId
bossuIdCache[UnitGUID(uId)] = uId
name, uid, bossuid = getBossTarget(UnitGUID(uId), scanOnlyBoss)
break
end
end
if not found and not scanOnlyBoss then
if IsInRaid() then
for i = 1, GetNumGroupMembers() do
if self:GetUnitCreatureId("raid"..i.."target") == cidOrGuid then
bossuIdCache[cidOrGuid] = "raid"..i.."target"
bossuIdCache[UnitGUID("raid"..i.."target")] = "raid"..i.."target"
name, uid, bossuid = getBossTarget(UnitGUID("raid"..i.."target"))
break
end
end
elseif IsInGroup() then
for i = 1, GetNumSubgroupMembers() do
if self:GetUnitCreatureId("party"..i.."target") == cidOrGuid then
bossuIdCache[cidOrGuid] = "party"..i.."target"
bossuIdCache[UnitGUID("party"..i.."target")] = "party"..i.."target"
name, uid, bossuid = getBossTarget(UnitGUID("party"..i.."target"))
break
end
end
end
end
end
else
name, uid, bossuid = getBossTarget(cidOrGuid, scanOnlyBoss)
end
if uid then
local cid = DBM:GetUnitCreatureId(uid)
if cid == 24207 or cid == 80258 or cid == 87519 then--filter army of the dead/Garrison Footman (basically same thing as army)
return nil, nil, nil
end
end
return name, uid, bossuid
end
function bossModPrototype:BossTargetScannerAbort(cidOrGuid, returnFunc)
targetScanCount[cidOrGuid] = nil--Reset count for later use.
self:UnscheduleMethod("BossTargetScanner", cidOrGuid, returnFunc)
DBM:Debug("Boss target scan for "..cidOrGuid.." should be aborting.", 3)
end
function bossModPrototype:BossUnitTargetScannerAbort()
targetMonitor = nil
DBM:Debug("Boss unit target scan should be aborting.", 3)
end
function bossModPrototype:BossUnitTargetScanner(unitId, returnFunc, scanTime)
--UNIT_TARGET technique was originally used by DXE on heroic lich king back in wrath to give most accurate defile/shadow trap warnings. Recently bigwigs started using it.
--This is fastest and most accurate method for getting the target and probably should be used where it does work 100% of time.
--This method fails if boss is already looking at correct target!! This method needs to monitor a target change so it must start before that target change
--In most cases, using BossTargetScanner is probably still better, especially if boss is expected to look at target before or immediately on cast start
--Limited to only one unitTarget scanner at a time. TODO, maybe make targetMonitor a table or something to support more than one scan at a time?
--This code is much prettier if it's in mod, but then it'd require copying and pasting it all the time. SO ugly code in core more convinient.
local modId = self.id
local scanDuration = scanTime or 1.5
targetMonitor = modId.."\t"..unitId.."\t"..returnFunc
self:ScheduleMethod(scanDuration, "BossUnitTargetScannerAbort")--In case of BossUnitTargetScanner firing too late, and boss already having changed target before monitor started, it needs to abort after x seconds
end
function bossModPrototype:BossTargetScanner(cidOrGuid, returnFunc, scanInterval, scanTimes, scanOnlyBoss, isEnemyScan, isFinalScan, targetFilter, tankFilter)
--Increase scan count
local cidOrGuid = cidOrGuid or self.creatureId
if not cidOrGuid then return end
if not targetScanCount[cidOrGuid] then targetScanCount[cidOrGuid] = 0 end
targetScanCount[cidOrGuid] = targetScanCount[cidOrGuid] + 1
--Set default values
local scanInterval = scanInterval or 0.05
local scanTimes = scanTimes or 16
local targetname, targetuid, bossuid = self:GetBossTarget(cidOrGuid, scanOnlyBoss)
DBM:Debug("Boss target scan "..targetScanCount[cidOrGuid].." of "..scanTimes..", found target "..(targetname or "nil").." using "..(bossuid or "nil"), 3)--Doesn't hurt to keep this, as level 3
--Do scan
if targetname and targetname ~= DBM_CORE_UNKNOWN and (not targetFilter or (targetFilter and targetFilter ~= targetname)) then
if not IsInGroup() then scanTimes = 1 end--Solo, no reason to keep scanning, give faster warning. But only if first scan is actually a valid target, which is why i have this check HERE
if (isEnemyScan and UnitIsFriend("player", targetuid) or self:IsTanking(targetuid, bossuid)) and not isFinalScan then--On player scan, ignore tanks. On enemy scan, ignore friendly player.
if targetScanCount[cidOrGuid] < scanTimes then--Make sure no infinite loop.
self:ScheduleMethod(scanInterval, "BossTargetScanner", cidOrGuid, returnFunc, scanInterval, scanTimes, scanOnlyBoss, isEnemyScan, nil, targetFilter, tankFilter)--Scan multiple times to be sure it's not on something other then tank (or friend on enemy scan).
else--Go final scan.
self:BossTargetScanner(cidOrGuid, returnFunc, scanInterval, scanTimes, scanOnlyBoss, isEnemyScan, true, targetFilter, tankFilter)
end
else--Scan success. (or failed to detect right target.) But some spells can be used on tanks, anyway warns tank if player scan. (enemy scan block it)
targetScanCount[cidOrGuid] = nil--Reset count for later use.
self:UnscheduleMethod("BossTargetScanner", cidOrGuid, returnFunc)--Unschedule all checks just to be sure none are running, we are done.
if (tankFilter and self:IsTanking(targetuid, bossuid)) or (isFinalScan and isEnemyScan) then return end--If enemyScan and playerDetected, return nothing
self[returnFunc](self, targetname, targetuid, bossuid)--Return results to warning function with all variables.
end
else--target was nil, lets schedule a rescan here too.
if targetScanCount[cidOrGuid] < scanTimes then--Make sure not to infinite loop here as well.
self:ScheduleMethod(scanInterval, "BossTargetScanner", cidOrGuid, returnFunc, scanInterval, scanTimes, scanOnlyBoss, isEnemyScan, nil, targetFilter, tankFilter)
else
targetScanCount[cidOrGuid] = nil--Reset count for later use.
self:UnscheduleMethod("BossTargetScanner", cidOrGuid, returnFunc)--Unschedule all checks just to be sure none are running, we are done.
end
end
end
--infinite scanner. so use this carefully.
local function repeatedScanner(cidOrGuid, returnFunc, scanInterval, scanOnlyBoss, includeTank, mod)
if repeatedScanEnabled[returnFunc] then
local cidOrGuid = cidOrGuid or mod.creatureId
local scanInterval = scanInterval or 0.1
local targetname, targetuid, bossuid = mod:GetBossTarget(cidOrGuid, scanOnlyBoss)
if targetname and (includeTank or not mod:IsTanking(targetuid, bossuid)) then
mod[returnFunc](mod, targetname, targetuid, bossuid)
end
DBM:Schedule(scanInterval, repeatedScanner, cidOrGuid, returnFunc, scanInterval, scanOnlyBoss, includeTank, mod)
end
end
function bossModPrototype:StartRepeatedScan(cidOrGuid, returnFunc, scanInterval, scanOnlyBoss, includeTank)
repeatedScanEnabled[returnFunc] = true
repeatedScanner(cidOrGuid, returnFunc, scanInterval, scanOnlyBoss, includeTank, self)
end
function bossModPrototype:StopRepeatedScan(returnFunc)
repeatedScanEnabled[returnFunc] = nil
end
end
function bossModPrototype:CheckNearby(range, targetname)
if not targetname and DBM.RangeCheck:GetDistanceAll(range) then
return true--No target name means check if anyone is near self, period
else
local uId = DBM:GetRaidUnitId(targetname)
if uId and not UnitIsUnit("player", uId) then
local inRange = DBM.RangeCheck:GetDistance(uId)
if inRange and inRange < range+0.5 then
return true
end
end
end
return false
end
do
local bossCache = {}
local lastTank = nil
function bossModPrototype:GetCurrentTank(cidOrGuid)
if lastTank and GetTime() - (bossCache[cidOrGuid] or 0) < 2 then -- return last tank within 2 seconds of call
return lastTank
else
local cidOrGuid = cidOrGuid or self.creatureId--GetBossTarget supports GUID or CID and it will automatically return correct values with EITHER ONE
local uId
local _, fallbackuId, mobuId = self:GetBossTarget(cidOrGuid)
if mobuId then--Have a valid mob unit ID
--First, use trust threat more than fallbackuId and see what we pull from it first.
--This is because for GetCurrentTank we want to know who is tanking it, not who it's targeting.
local unitId = (IsInRaid() and "raid") or "party"
for i = 0, GetNumGroupMembers() do
local id = (i == 0 and "target") or unitId..i
local tanking, status = UnitDetailedThreatSituation(id, mobuId)--Tanking may return 0 if npc is temporarily looking at an NPC (IE fracture) but status will still be 3 on true tank
if tanking or (status == 3) then uId = id end--Found highest threat target, make them uId
if uId then break end
end
--Did not get anything useful from threat, so use who the boss was looking at, at time of cast (ie fallbackuId)
if fallbackuId and not uId then
uId = fallbackuId
end
end
if uId then--Now we have a valid uId
bossCache[cidOrGuid] = GetTime()
lastTank = UnitName(uId)
return UnitName(lastTank), uId
end
return false
end
end
end
--Now this function works perfectly. But have some limitation due to DBM.RangeCheck:GetDistance() function.
--Unfortunely, DBM.RangeCheck:GetDistance() function cannot reflects altitude difference. This makes range unreliable.
--So, we need to cafefully check range in difference altitude (Especially, tower top and bottom)
do
local rangeCache = {}
local rangeUpdated = {}
function bossModPrototype:CheckTankDistance(cidOrGuid, distance, defaultReturn)
if not DBM.Options.DontShowFarWarnings then return true end--Global disable.
if rangeCache[cidOrGuid] and (GetTime() - (rangeUpdated[cidOrGuid] or 0)) < 2 then -- return same range within 2 sec call
if rangeCache[cidOrGuid] > distance then
return false
else
return true
end
else
local cidOrGuid = cidOrGuid or self.creatureId--GetBossTarget supports GUID or CID and it will automatically return correct values with EITHER ONE
local distance = distance or 40
local uId
local _, fallbackuId, mobuId = self:GetBossTarget(cidOrGuid)
if mobuId then--Have a valid mob unit ID
--First, use trust threat more than fallbackuId and see what we pull from it first.
--This is because for CheckTankDistance we want to know who is tanking it, not who it's targeting.
local unitId = (IsInRaid() and "raid") or "party"
for i = 0, GetNumGroupMembers() do
local id = (i == 0 and "target") or unitId..i
local tanking, status = UnitDetailedThreatSituation(id, mobuId)--Tanking may return 0 if npc is temporarily looking at an NPC (IE fracture) but status will still be 3 on true tank
if tanking or (status == 3) then uId = id end--Found highest threat target, make them uId
if uId then break end
end
--Did not get anything useful from threat, so use who the boss was looking at, at time of cast (ie fallbackuId)
if fallbackuId and not uId then
uId = fallbackuId
end
end
if uId then--Now we have a valid uId
if UnitIsUnit(uId, "player") then return true end--If "player" is target, avoid doing any complicated stuff
local inRange = 0
if not UnitIsPlayer(uId) then
local inRange2, checkedRange = UnitInRange(uId)
if checkedRange then--checkedRange only returns true if api worked, so if we get false, true then we are not near npc
return inRange2 and true or false
else--Its probably a totem or just something we can't assess. Fall back to no filtering
return true
end
else
inRange = DBM.RangeCheck:GetDistance("player", uId)--We check how far we are from the tank who has that boss
end
rangeCache[cidOrGuid] = inRange
rangeUpdated[cidOrGuid] = GetTime()
if inRange and (inRange > distance) then--You are not near the person tanking boss
return false
end
--Tank in range, return true.
return true
end
return (defaultReturn == nil) or defaultReturn--When we simply can't figure anything out, return true and allow warnings using this filter to fire. But some spells will prefer not to fire(i.e : Galakras tower spell), we can define it on this function calling.
end
end
end
---------------------
-- Class Methods --
---------------------
do
--[[local specFlags ={
["Tank"] = true,
["Dps"] = true,
["Healer"] = true,
["Melee"] = true,--ANY melee, including tanks or healers that are 100% excempt from healer/ranged mechanics (like mistweaver monks)
["MeleeDps"] = true,
["Physical"] = true,
["Ranged"] = true,--ANY ranged, healer and dps included
["RangedDps"] = true,--Only ranged dps
["ManaUser"] = true,--Affected by things like mana drains, or mana detonation, etc
["SpellCaster"] = true,--Has channeled casts, can be interrupted/spell locked by roars, etc, include healers. Use CasterDps if dealing with reflect
["CasterDps"] = true,--Ranged dps that uses spells, relevant for spell reflect type abilities that only reflect spells but not ranged physical such as hunters
["RaidCooldown"] = true,
["RemovePoison"] = true,--from ally
["RemoveDisease"] = true,--from ally
["RemoveEnrage"] = true,--Unused, no one can remove enrage anymore, returning in classic/8.x!
["RemoveCurse"] = true,--from ally
["MagicDispeller"] = true--from ENEMY, not debuffs on players. use "Healer" for ally magic dispels. ALL healers can do that.
["HasInterrupt"] = true,--Has an interrupt that is 24 seconds or less CD that is BASELINE (not a talent)
["HasImmunity"] = true,--Has an immunity that can prevent or remove a spell effect (not just one that reduces damage like turtle or dispursion)
}]]
local specRoleTable = {
[62] = { --Arcane Mage
["Dps"] = true,
["Ranged"] = true,
["RangedDps"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["CasterDps"] = true,
["MagicDispeller"] = true,
["HasInterrupt"] = true,
["HasImmunity"] = true,
},
[65] = { --Holy Paladin
["Healer"] = true,
["Ranged"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["RaidCooldown"] = true,--Devotion Aura
["RemovePoison"] = true,
["RemoveDisease"] = true,
["HasImmunity"] = true,
},
[66] = { --Protection Paladin
["Tank"] = true,
["Melee"] = true,
["ManaUser"] = true,
["Physical"] = true,
["RemovePoison"] = true,
["RemoveDisease"] = true,
["HasInterrupt"] = true,
["HasImmunity"] = true,
},
[70] = { --Retribution Paladin
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["ManaUser"] = true,
["Physical"] = true,
["RemovePoison"] = true,
["RemoveDisease"] = true,
["HasInterrupt"] = true,
["HasImmunity"] = true,
},
[71] = { --Arms Warrior
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["RaidCooldown"] = true,--Rallying Cry
["Physical"] = true,
["HasInterrupt"] = true,
},
[73] = { --Protection Warrior
["Tank"] = true,
["Melee"] = true,
["Physical"] = true,
["HasInterrupt"] = true,
--["RaidCooldown"] = true,--Rallying Cry (in 8.x)
},
[102] = { --Balance Druid
["Dps"] = true,
["Ranged"] = true,
["RangedDps"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["CasterDps"] = true,
["RemoveCurse"] = true,
["RemovePoison"] = true,
},
[103] = { --Feral Druid
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["Physical"] = true,
["RemoveCurse"] = true,
["RemovePoison"] = true,
["HasInterrupt"] = true,
},
[104] = { --Guardian Druid
["Tank"] = true,
["Melee"] = true,
["Physical"] = true,
["RemoveCurse"] = true,
["RemovePoison"] = true,
["HasInterrupt"] = true,
},
[105] = { -- Restoration Druid
["Healer"] = true,
["Ranged"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["RaidCooldown"] = true,--Tranquility
["RemoveCurse"] = true,
["RemovePoison"] = true,
},
[250] = { --Blood DK
["Tank"] = true,
["Melee"] = true,
["Physical"] = true,
["HasInterrupt"] = true,
},
[251] = { --Frost DK
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["Physical"] = true,
["HasInterrupt"] = true,
},
[253] = { --Beastmaster Hunter
["Dps"] = true,
["Ranged"] = true,
["RangedDps"] = true,
["Physical"] = true,
["HasInterrupt"] = true,
},
[255] = { --Survival Hunter (Legion)
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["Physical"] = true,
["HasInterrupt"] = true,
},
[256] = { --Discipline Priest
["Healer"] = true,
["Ranged"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["CasterDps"] = true,--Iffy. Technically yes, but this can't be used to determine eligable target for dps only debuffs
["RaidCooldown"] = true,--Power Word: Barrier(Discipline) / Divine Hymn (Holy)
["RemoveDisease"] = true,
["MagicDispeller"] = true,
},
[258] = { --Shadow Priest
["Dps"] = true,
["Ranged"] = true,
["RangedDps"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["CasterDps"] = true,
["MagicDispeller"] = true,
},
[259] = { --Assassination Rogue
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["Physical"] = true,
["HasInterrupt"] = true,
["HasImmunity"] = true,
},
[262] = { --Elemental Shaman
["Dps"] = true,
["Ranged"] = true,
["RangedDps"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["CasterDps"] = true,
["RemoveCurse"] = true,
["MagicDispeller"] = true,
["HasInterrupt"] = true,
},
[263] = { --Enhancement Shaman
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["Physical"] = true,
["RemoveCurse"] = true,
["MagicDispeller"] = true,
["HasInterrupt"] = true,
},
[264] = { --Restoration Shaman
["Healer"] = true,
["Ranged"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["RaidCooldown"] = true,--Spirit Link Totem
["RemoveCurse"] = true,
["MagicDispeller"] = true,
["HasInterrupt"] = true,
},
[265] = { --Affliction Warlock
["Dps"] = true,
["Ranged"] = true,
["RangedDps"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["CasterDps"] = true,
},
[268] = { --Brewmaster Monk
["Tank"] = true,
["Melee"] = true,
["Physical"] = true,
["RemovePoison"] = true,
["RemoveDisease"] = true,
["HasInterrupt"] = true,
},
[269] = { --Windwalker Monk
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["Physical"] = true,
["RemovePoison"] = true,
["RemoveDisease"] = true,
["HasInterrupt"] = true,
},
[270] = { --Mistweaver Monk
["Healer"] = true,
["Melee"] = true,
["Ranged"] = true,
["ManaUser"] = true,
["SpellCaster"] = true,
["RaidCooldown"] = true,--Revival
["RemovePoison"] = true,
["RemoveDisease"] = true,
},
[577] = { --Havok Demon Hunter
["Dps"] = true,
["Melee"] = true,
["MeleeDps"] = true,
["Physical"] = true,
["HasInterrupt"] = true,
},
[581] = { --Vengeance Demon Hunter
["Tank"] = true,
["Melee"] = true,
["Physical"] = true,
["HasInterrupt"] = true,
},
}
specRoleTable[63] = specRoleTable[62]--Frost Mage same as arcane
specRoleTable[64] = specRoleTable[62]--Fire Mage same as arcane
specRoleTable[72] = specRoleTable[71]--Fury Warrior same as Arms
specRoleTable[252] = specRoleTable[251]--Unholy DK same as frost
specRoleTable[254] = specRoleTable[253]--Markmanship Hunter same as beast
specRoleTable[257] = specRoleTable[256]--Holy Priest same as disc
specRoleTable[260] = specRoleTable[259]--Combat Rogue same as Assassination
specRoleTable[261] = specRoleTable[259]--Subtlety Rogue same as Assassination
specRoleTable[266] = specRoleTable[265]--Demonology Warlock same as Affliction
specRoleTable[267] = specRoleTable[265]--Destruction Warlock same as Affliction
--[[function bossModPrototype:GetRoleFlagValue(flag)
if not flag then return false end
local flags = {strsplit("|", flag)}
for i = 1, #flags do
local flagText = flags[i]
flagText = flagText:gsub("-", "")
if not specFlags[flagText] then
print("bad flag found : "..flagText)
end
end
self:GetRoleFlagValue2(flag)
end]]
--to check flag is correct, remove comment block specFlags table and GetRoleFlagValue function, change this to GetRoleFlagValue2
--disable flag check normally because double flag check comsumes more cpu on mod load.
function bossModPrototype:GetRoleFlagValue(flag)
if not flag then return false end
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
local flags = {strsplit("|", flag)}
for i = 1, #flags do
local flagText = flags[i]
if flagText:match("^-") then
flagText = flagText:gsub("-", "")
if not specRoleTable[currentSpecID][flagText] then
return true
end
else
if specRoleTable[currentSpecID][flagText] then
return true
end
end
end
return false
end
function bossModPrototype:IsMeleeDps(uId)
if uId then--This version includes ONLY melee dps
local role = UnitGroupRolesAssigned(uId)
if role == "HEALER" or role == "TANK" then--Auto filter healer from dps check
return false
end
local _, class = UnitClass(uId)
if class == "WARRIOR" or class == "ROGUE" or class == "DEATHKNIGHT" then
return true
end
--Inspect throttle exists, so have to do it this way
if class == "DRUID" or class == "SHAMAN" or class == "PALADIN" or class == "MONK" or class == "HUNTER" then
local unitMaxPower = UnitPowerMax(uId)
--Mark and beast have 120 base focus, survival has 100 base focus. Not sure if this is best way to do it or if it breaks with talent/artifact weapon
--Elemental shaman have 100 unit power base, while enhancement have 150 power base, so a shaman with > 150 but less tha 35000 is the melee one
if (unitMaxPower < 101 and class == "HUNTER") or (unitMaxPower >= 150 and class == "SHAMAN" and unitMaxPower < 35000) or unitMaxPower < 35000 then
return true
end
end
return false
end
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
if specRoleTable[currentSpecID]["MeleeDps"] then
return true
else
return false
end
end
function bossModPrototype:IsMelee(uId)
if uId then--This version includes monk healers as melee and tanks as melee
local _, class = UnitClass(uId)
if class == "WARRIOR" or class == "ROGUE" or class == "DEATHKNIGHT" or class == "MONK" then
return true
end
--Inspect throttle exists, so have to do it this way
if class == "DRUID" or class == "SHAMAN" or class == "PALADIN" then
if UnitPowerMax(uId) < 35000 then
return true
end
end
return false
end
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
if specRoleTable[currentSpecID]["Melee"] then
return true
else
return false
end
end
function bossModPrototype:IsRanged()
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
if specRoleTable[currentSpecID]["Ranged"] then
return true
else
return false
end
end
function bossModPrototype:IsSpellCaster()
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
if specRoleTable[currentSpecID]["SpellCaster"] then
return true
else
return false
end
end
function bossModPrototype:IsMagicDispeller()
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
if specRoleTable[currentSpecID]["MagicDispeller"] then
return true
else
return false
end
end
end
function bossModPrototype:UnitClass(uId)
if uId then--Return unit requested
local _, class = UnitClass(uId)
return class
end
return playerClass--else return "player"
end
function bossModPrototype:IsTank()
--IsTanking already handles external calls, no need here.
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
local _, _, _, _, role = GetSpecializationInfoByID(currentSpecID)
if role == "TANK" then
return true
else
return false
end
end
function bossModPrototype:IsDps(uId)
if uId then--External unit call.
if UnitGroupRolesAssigned(uId) == "DAMAGER" then
return true
end
return false
end
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
local _, _, _, _, role = GetSpecializationInfoByID(currentSpecID)
if role == "DAMAGER" then
return true
else
return false
end
end
function bossModPrototype:IsHealer(uId)
if uId then--External unit call.
if UnitGroupRolesAssigned(uId) == "HEALER" then
return true
end
return false
end
if not currentSpecID then
DBM:SetCurrentSpecInfo()
end
local _, _, _, _, role = GetSpecializationInfoByID(currentSpecID)
if role == "HEALER" then
return true
else
return false
end
end
function bossModPrototype:IsTanking(unit, boss, isName, onlyRequested)
if isName then--Passed combat log name, so pull unit ID
unit = DBM:GetRaidUnitId(unit)
end
if not unit then
DBM:Debug("IsTanking passed with invalid unit", 2)
return false
end
--Prefer threat target first
if boss then--Only checking one bossID as requested
local tanking, status = UnitDetailedThreatSituation(unit, boss)
if tanking or (status == 3) then
return true
end
else--Check all of them if one isn't defined
for i = 1, 5 do
--if UnitExists("boss"..i) then
local tanking, status = UnitDetailedThreatSituation(unit, "boss"..i)
if tanking or (status == 3) then
return true
end
--end
end
end
if not onlyRequested then
--Use these as fallback if threat target not found
if GetPartyAssignment("MAINTANK", unit, 1) then
return true
end
if UnitGroupRolesAssigned(unit) == "TANK" then
return true
end
end
return false
end
function bossModPrototype:GetNumAliveTanks()
if not IsInGroup() then return 1 end--Solo raid, you're the "tank"
local count = 0
local uId = (IsInRaid() and "raid") or "party"
for i = 1, DBM:GetNumRealGroupMembers() do
if UnitGroupRolesAssigned(uId..i) == "TANK" and not UnitIsDeadOrGhost(uId..i) then
count = count + 1
end
end
return count
end
----------------------------
-- Boss Health Function --
----------------------------
function DBM:GetBossHP(cId)
local uId = bossHealthuIdCache[cId] or "target"
if self:GetCIDFromGUID(UnitGUID(uId)) == cId and UnitHealthMax(uId) ~= 0 then
if bossHealth[cId] and (UnitHealth(uId) == 0 and not UnitIsDead(uId)) then return bossHealth[cId], uId, UnitName(uId) end--Return last non 0 value if value is 0, since it's last valid value we had.
local hp = UnitHealth(uId) / UnitHealthMax(uId) * 100
bossHealth[cId] = hp
return hp, uId, UnitName(uId)
elseif self:GetCIDFromGUID(UnitGUID("focus")) == cId and UnitHealthMax("focus") ~= 0 then
if bossHealth[cId] and (UnitHealth("focus") == 0 and not UnitIsDead("focus")) then return bossHealth[cId], "focus", UnitName("focus") end--Return last non 0 value if value is 0, since it's last valid value we had.
local hp = UnitHealth("focus") / UnitHealthMax("focus") * 100
bossHealth[cId] = hp
return hp, "focus", UnitName("focus")
else
for i = 1, 5 do
local unitID = "boss"..i
local guid = UnitGUID(unitID)
if self:GetCIDFromGUID(guid) == cId and UnitHealthMax(unitID) ~= 0 then
if bossHealth[cId] and (UnitHealth(unitID) == 0 and not UnitIsDead(unitID)) then return bossHealth[cId], unitID, UnitName(unitID) end--Return last non 0 value if value is 0, since it's last valid value we had.
local hp = UnitHealth(unitID) / UnitHealthMax(unitID) * 100
bossHealth[cId] = hp
bossHealthuIdCache[cId] = unitID
return hp, unitID, UnitName(unitID)
end
end
local idType = (IsInRaid() and "raid") or "party"
for i = 0, GetNumGroupMembers() do
local unitId = ((i == 0) and "target") or idType..i.."target"
local guid = UnitGUID(unitId)
if self:GetCIDFromGUID(guid) == cId and UnitHealthMax(unitId) ~= 0 then
if bossHealth[cId] and (UnitHealth(unitId) == 0 and not UnitIsDead(unitId)) then return bossHealth[cId], unitId, UnitName(unitId) end--Return last non 0 value if value is 0, since it's last valid value we had.
local hp = UnitHealth(unitId) / UnitHealthMax(unitId) * 100
bossHealth[cId] = hp
bossHealthuIdCache[cId] = unitId
return hp, unitId, UnitName(unitId)
end
end
end
return nil
end
function DBM:GetBossHPByGUID(guid)
local uId = bossHealthuIdCache[guid] or "target"
if UnitGUID(uId) == guid and UnitHealthMax(uId) ~= 0 then
if bossHealth[guid] and (UnitHealth(uId) == 0 and not UnitIsDead(uId)) then return bossHealth[guid], uId, UnitName(uId) end--Return last non 0 value if value is 0, since it's last valid value we had.
local hp = UnitHealth(uId) / UnitHealthMax(uId) * 100
bossHealth[guid] = hp
return hp, uId, UnitName(uId)
elseif UnitGUID("focus") == guid and UnitHealthMax("focus") ~= 0 then
if bossHealth[guid] and (UnitHealth("focus") == 0 and not UnitIsDead("focus")) then return bossHealth[guid], "focus", UnitName("focus") end--Return last non 0 value if value is 0, since it's last valid value we had.
local hp = UnitHealth("focus") / UnitHealthMax("focus") * 100
bossHealth[guid] = hp
return hp, "focus", UnitName("focus")
else
for i = 1, 5 do
local unitID = "boss"..i
local guid2 = UnitGUID(unitID)
if guid == guid2 and UnitHealthMax(unitID) ~= 0 then
if bossHealth[guid] and (UnitHealth(unitID) == 0 and not UnitIsDead(unitID)) then return bossHealth[guid], unitID, UnitName(unitID) end--Return last non 0 value if value is 0, since it's last valid value we had.
local hp = UnitHealth(unitID) / UnitHealthMax(unitID) * 100
bossHealth[guid] = hp
bossHealthuIdCache[guid] = unitID
return hp, unitID, UnitName(unitID)
end
end
local idType = (IsInRaid() and "raid") or "party"
for i = 0, GetNumGroupMembers() do
local unitId = ((i == 0) and "target") or idType..i.."target"
local guid2 = UnitGUID(unitId)
if guid == guid2 and UnitHealthMax(unitId) ~= 0 then
if bossHealth[guid] and (UnitHealth(unitId) == 0 and not UnitIsDead(unitId)) then return bossHealth[guid], unitId, UnitName(unitId) end--Return last non 0 value if value is 0, since it's last valid value we had.
local hp = UnitHealth(unitId) / UnitHealthMax(unitId) * 100
bossHealth[guid] = hp
bossHealthuIdCache[guid] = unitId
return hp, unitId, UnitName(unitId)
end
end
end
return nil
end
function DBM:GetBossHPByUnitID(uId)
if UnitHealthMax(uId) ~= 0 then
local hp = UnitHealth(uId) / UnitHealthMax(uId) * 100
bossHealth[uId] = hp
return hp, uId, UnitName(uId)
end
return nil
end
function bossModPrototype:SetMainBossID(cid)
self.mainBoss = cid
end
function bossModPrototype:SetBossHPInfoToHighest(numBoss)
if numBoss ~= false then
self.numBoss = numBoss or (self.multiMobPullDetection and #self.multiMobPullDetection)
end
self.highesthealth = true
end
function bossModPrototype:GetHighestBossHealth()
local hp
if not self.multiMobPullDetection or self.mainBoss then
hp = bossHealth[self.mainBoss or self.combatInfo.mob or -1]
if hp and (hp > 100 or hp <= 0) then
hp = nil
end
else
for _, mob in ipairs(self.multiMobPullDetection) do
if (bossHealth[mob] or 0) > (hp or 0) and (bossHealth[mob] or 0) < 100 then-- ignore full health.
hp = bossHealth[mob]
end
end
end
return hp
end
function bossModPrototype:GetLowestBossHealth()
local hp
if not self.multiMobPullDetection or self.mainBoss then
hp = bossHealth[self.mainBoss or self.combatInfo.mob or -1]
if hp and (hp > 100 or hp <= 0) then
hp = nil
end
else
for _, mob in ipairs(self.multiMobPullDetection) do
if (bossHealth[mob] or 100) < (hp or 100) and (bossHealth[mob] or 100) > 0 then-- ignore zero health.
hp = bossHealth[mob]
end
end
end
return hp
end
bossModPrototype.GetBossHP = DBM.GetBossHP
bossModPrototype.GetBossHPByGUID = DBM.GetBossHPByGUID
-----------------------
-- Announce Object --
-----------------------
do
local frame = CreateFrame("Frame", "DBMWarning", UIParent)
local font1u = CreateFrame("Frame", "DBMWarning1Updater", UIParent)
local font2u = CreateFrame("Frame", "DBMWarning2Updater", UIParent)
local font3u = CreateFrame("Frame", "DBMWarning3Updater", UIParent)
local font1 = frame:CreateFontString("DBMWarning1", "OVERLAY", "GameFontNormal")
font1:SetWidth(1024)
font1:SetHeight(0)
font1:SetPoint("TOP", 0, 0)
local font2 = frame:CreateFontString("DBMWarning2", "OVERLAY", "GameFontNormal")
font2:SetWidth(1024)
font2:SetHeight(0)
font2:SetPoint("TOP", font1, "BOTTOM", 0, 0)
local font3 = frame:CreateFontString("DBMWarning3", "OVERLAY", "GameFontNormal")
font3:SetWidth(1024)
font3:SetHeight(0)
font3:SetPoint("TOP", font2, "BOTTOM", 0, 0)
frame:SetMovable(1)
frame:SetWidth(1)
frame:SetHeight(1)
frame:SetFrameStrata("HIGH")
frame:SetClampedToScreen()
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 300)
font1u:Hide()
font2u:Hide()
font3u:Hide()
local font1elapsed, font2elapsed, font3elapsed, moving
local function fontHide1()
local duration = DBM.Options.WarningDuration2
if font1elapsed > duration * 1.3 then
font1u:Hide()
font1:Hide()
if frame.font1ticker then
frame.font1ticker:Cancel()
frame.font1ticker = nil
end
elseif font1elapsed > duration then
font1elapsed = font1elapsed + 0.05
local alpha = 1 - (font1elapsed - duration) / (duration * 0.3)
font1:SetAlpha(alpha > 0 and alpha or 0)
else
font1elapsed = font1elapsed + 0.05
font1:SetAlpha(1)
end
end
local function fontHide2()
local duration = DBM.Options.WarningDuration2
if font2elapsed > duration * 1.3 then
font2u:Hide()
font2:Hide()
if frame.font2ticker then
frame.font2ticker:Cancel()
frame.font2ticker = nil
end
elseif font2elapsed > duration then
font2elapsed = font2elapsed + 0.05
local alpha = 1 - (font2elapsed - duration) / (duration * 0.3)
font2:SetAlpha(alpha > 0 and alpha or 0)
else
font2elapsed = font2elapsed + 0.05
font2:SetAlpha(1)
end
end
local function fontHide3()
local duration = DBM.Options.WarningDuration2
if font3elapsed > duration * 1.3 then
font3u:Hide()
font3:Hide()
if frame.font3ticker then
frame.font3ticker:Cancel()
frame.font3ticker = nil
end
elseif font3elapsed > duration then
font3elapsed = font3elapsed + 0.05
local alpha = 1 - (font3elapsed - duration) / (duration * 0.3)
font3:SetAlpha(alpha > 0 and alpha or 0)
else
font3elapsed = font3elapsed + 0.05
font3:SetAlpha(1)
end
end
font1u:SetScript("OnUpdate", function(self)
local diff = GetTime() - font1.lastUpdate
local origSize = DBM.Options.WarningFontSize
if diff > 0.4 then
font1:SetTextHeight(origSize)
self:Hide()
elseif diff > 0.2 then
font1:SetTextHeight(origSize * (1.5 - (diff-0.2) * 2.5))
else
font1:SetTextHeight(origSize * (1 + diff * 2.5))
end
end)
font2u:SetScript("OnUpdate", function(self)
local diff = GetTime() - font2.lastUpdate
local origSize = DBM.Options.WarningFontSize
if diff > 0.4 then
font2:SetTextHeight(origSize)
self:Hide()
elseif diff > 0.2 then
font2:SetTextHeight(origSize * (1.5 - (diff-0.2) * 2.5))
else
font2:SetTextHeight(origSize * (1 + diff * 2.5))
end
end)
font3u:SetScript("OnUpdate", function(self)
local diff = GetTime() - font3.lastUpdate
local origSize = DBM.Options.WarningFontSize
if diff > 0.4 then
font3:SetTextHeight(origSize)
self:Hide()
elseif diff > 0.2 then
font3:SetTextHeight(origSize * (1.5 - (diff-0.2) * 2.5))
else
font3:SetTextHeight(origSize * (1 + diff * 2.5))
end
end)
function DBM:UpdateWarningOptions()
frame:ClearAllPoints()
frame:SetPoint(self.Options.WarningPoint, UIParent, self.Options.WarningPoint, self.Options.WarningX, self.Options.WarningY)
font1:SetFont(self.Options.WarningFont, self.Options.WarningFontSize, self.Options.WarningFontStyle == "None" and nil or self.Options.WarningFontStyle)
font2:SetFont(self.Options.WarningFont, self.Options.WarningFontSize, self.Options.WarningFontStyle == "None" and nil or self.Options.WarningFontStyle)
font3:SetFont(self.Options.WarningFont, self.Options.WarningFontSize, self.Options.WarningFontStyle == "None" and nil or self.Options.WarningFontStyle)
if self.Options.WarningFontShadow then
font1:SetShadowOffset(1, -1)
font2:SetShadowOffset(1, -1)
font3:SetShadowOffset(1, -1)
else
font1:SetShadowOffset(0, 0)
font2:SetShadowOffset(0, 0)
font3:SetShadowOffset(0, 0)
end
end
function DBM:AddWarning(text, force)
local added = false
if not frame.font1ticker then
font1elapsed = 0
font1.lastUpdate = GetTime()
font1:SetText(text)
font1:Show()
font1u:Show()
added = true
frame.font1ticker = frame.font1ticker or C_TimerNewTicker(0.05, fontHide1)
elseif not frame.font2ticker then
font2elapsed = 0
font2.lastUpdate = GetTime()
font2:SetText(text)
font2:Show()
font2u:Show()
added = true
frame.font2ticker = frame.font2ticker or C_TimerNewTicker(0.05, fontHide2)
elseif not frame.font3ticker or force then
font3elapsed = 0
font3.lastUpdate = GetTime()
font3:SetText(text)
font3:Show()
font3u:Show()
fontHide3()
added = true
frame.font3ticker = frame.font3ticker or C_TimerNewTicker(0.05, fontHide3)
end
if not added then
local prevText1 = font2:GetText()
local prevText2 = font3:GetText()
font1:SetText(prevText1)
font1elapsed = font2elapsed
font2:SetText(prevText2)
font2elapsed = font3elapsed
self:AddWarning(text, true)
end
end
do
local anchorFrame
local function moveEnd(self)
moving = false
anchorFrame:Hide()
if anchorFrame.ticker then
anchorFrame.ticker:Cancel()
anchorFrame.ticker = nil
end
font1elapsed = self.Options.WarningDuration2
font2elapsed = self.Options.WarningDuration2
font3elapsed = self.Options.WarningDuration2
frame:SetFrameStrata("HIGH")
self:Unschedule(moveEnd)
self.Bars:CancelBar(DBM_CORE_MOVE_WARNING_BAR)
end
function DBM:MoveWarning()
if not anchorFrame then
anchorFrame = CreateFrame("Frame", nil, frame)
anchorFrame:SetWidth(32)
anchorFrame:SetHeight(32)
anchorFrame:EnableMouse(true)
anchorFrame:SetPoint("TOP", frame, "TOP", 0, 32)
anchorFrame:RegisterForDrag("LeftButton")
anchorFrame:SetClampedToScreen()
anchorFrame:Hide()
local texture = anchorFrame:CreateTexture()
texture:SetTexture("Interface\\Addons\\DBM-GUI\\textures\\dot.blp")
texture:SetPoint("CENTER", anchorFrame, "CENTER", 0, 0)
texture:SetWidth(32)
texture:SetHeight(32)
anchorFrame:SetScript("OnDragStart", function()
frame:StartMoving()
self:Unschedule(moveEnd)
self.Bars:CancelBar(DBM_CORE_MOVE_WARNING_BAR)
end)
anchorFrame:SetScript("OnDragStop", function()
frame:StopMovingOrSizing()
local point, _, _, xOfs, yOfs = frame:GetPoint(1)
self.Options.WarningPoint = point
self.Options.WarningX = xOfs
self.Options.WarningY = yOfs
self:Schedule(15, moveEnd, self)
self.Bars:CreateBar(15, DBM_CORE_MOVE_WARNING_BAR)
end)
end
if anchorFrame:IsShown() then
moveEnd(self)
else
moving = true
anchorFrame:Show()
anchorFrame.ticker = anchorFrame.ticker or C_TimerNewTicker(5, function() self:AddWarning(DBM_CORE_MOVE_WARNING_MESSAGE) end)
self:AddWarning(DBM_CORE_MOVE_WARNING_MESSAGE)
self:Schedule(15, moveEnd, self)
self.Bars:CreateBar(15, DBM_CORE_MOVE_WARNING_BAR)
frame:Show()
frame:SetFrameStrata("TOOLTIP")
frame:SetAlpha(1)
end
end
end
local textureCode = " |T%s:12:12|t "
local textureExp = " |T(%S+......%S+):12:12|t "--Fix texture file including blank not strips(example: Interface\\Icons\\Spell_Frost_Ring of Frost). But this have limitations. Since I'm poor at regular expressions, this is not good fix. Do you have another good regular expression, tandanu?
local announcePrototype = {}
local mt = {__index = announcePrototype}
-- TODO: is there a good reason that this is a weak table?
local cachedColorFunctions = setmetatable({}, {__mode = "kv"})
local function setText(announceType, spellId, castTime, preWarnTime)
local spellName
if type(spellId) == "string" and spellId:match("ej%d+") then
spellId = string.sub(spellId, 3)
spellName = DBM:EJ_GetSectionInfo(spellId) or DBM_CORE_UNKNOWN
else
spellName = DBM:GetSpellInfo(spellId) or DBM_CORE_UNKNOWN
end
local text
if announceType == "cast" then
local spellHaste = select(4, DBM:GetSpellInfo(53142)) / 10000 -- 53142 = Dalaran Portal, should have 10000 ms cast time
local timer = (select(4, DBM:GetSpellInfo(spellId)) or 1000) / spellHaste
text = DBM_CORE_AUTO_ANNOUNCE_TEXTS[announceType]:format(spellName, castTime or (timer / 1000))
elseif announceType == "prewarn" then
if type(preWarnTime) == "string" then
text = DBM_CORE_AUTO_ANNOUNCE_TEXTS[announceType]:format(spellName, preWarnTime)
else
text = DBM_CORE_AUTO_ANNOUNCE_TEXTS[announceType]:format(spellName, DBM_CORE_SEC_FMT:format(tostring(preWarnTime or 5)))
end
elseif announceType == "stage" or announceType == "prestage" then
text = DBM_CORE_AUTO_ANNOUNCE_TEXTS[announceType]:format(tostring(spellId))
elseif announceType == "stagechange" then
text = DBM_CORE_AUTO_ANNOUNCE_TEXTS.spell
else
text = DBM_CORE_AUTO_ANNOUNCE_TEXTS[announceType]:format(spellName)
end
return text, spellName
end
-- TODO: this function is an abomination, it needs to be rewritten. Also: check if these work-arounds are still necessary
function announcePrototype:Show(...) -- todo: reduce amount of unneeded strings
if not self.option or self.mod.Options[self.option] then
if DBM.Options.DontShowBossAnnounces then return end -- don't show the announces if the spam filter option is set
if DBM.Options.DontShowTargetAnnouncements and (self.announceType == "target" or self.announceType == "targetcount") and not self.noFilter then return end--don't show announces that are generic target announces
local argTable = {...}
local colorCode = ("|cff%.2x%.2x%.2x"):format(self.color.r * 255, self.color.g * 255, self.color.b * 255)
if #self.combinedtext > 0 then
--Throttle spam.
if DBM.Options.WarningAlphabetical then
tsort(self.combinedtext)
end
local combinedText = tconcat(self.combinedtext, "<, >")
if self.combinedcount == 1 then
combinedText = combinedText.." "..DBM_CORE_GENERIC_WARNING_OTHERS
elseif self.combinedcount > 1 then
combinedText = combinedText.." "..DBM_CORE_GENERIC_WARNING_OTHERS2:format(self.combinedcount)
end
--Process
for i = 1, #argTable do
if type(argTable[i]) == "string" then
argTable[i] = combinedText
end
end
end
local message = pformat(self.text, unpack(argTable))
local text = ("%s%s%s|r%s"):format(
(DBM.Options.WarningIconLeft and self.icon and textureCode:format(self.icon)) or "",
colorCode,
message,
(DBM.Options.WarningIconRight and self.icon and textureCode:format(self.icon)) or ""
)
self.combinedcount = 0
self.combinedtext = {}
if not cachedColorFunctions[self.color] then
local color = self.color -- upvalue for the function to colorize names, accessing self in the colorize closure is not safe as the color of the announce object might change (it would also prevent the announce from being garbage-collected but announce objects are never destroyed)
cachedColorFunctions[color] = function(cap)
cap = cap:sub(2, -2)
local noStrip = cap:match("noStrip ")
if not noStrip then
local name = cap
if DBM.Options.StripServerName then
cap = Ambiguate(cap, "short")
end
local playerColor = RAID_CLASS_COLORS[DBM:GetRaidClass(name)] or color
if playerColor then
cap = ("|r|cff%.2x%.2x%.2x%s|r|cff%.2x%.2x%.2x"):format(playerColor.r * 255, playerColor.g * 255, playerColor.b * 255, cap, color.r * 255, color.g * 255, color.b * 255)
end
else
cap = cap:sub(9)
end
return cap
end
end
text = text:gsub(">.-<", cachedColorFunctions[self.color])
DBM:AddWarning(text)
if DBM.Options.ShowWarningsInChat then
if not DBM.Options.WarningIconChat then
text = text:gsub(textureExp, "") -- textures @ chat frame can (and will) distort the font if using certain combinations of UI scale, resolution and font size TODO: is this still true as of cataclysm?
end
self.mod:AddMsg(text, nil)
end
if self.sound > 0 then
if self.sound > 1 and DBM.Options.ChosenVoicePack ~= "None" and self.sound <= SWFilterDisabed then return end
if not self.option or self.mod.Options[self.option.."SWSound"] ~= "None" then
DBM:PlaySoundFile(DBM.Options.RaidWarningSound)
end
end
--Message: Full message text
--Icon: Texture path for icon
--Type: Announce type
--SpellId: Raw spell or encounter journal Id if available.
--Mod ID: Encounter ID as string, or a generic string for mods that don't have encounter ID (such as trash, dummy/test mods)
fireEvent("DBM_Announce", message, self.icon, self.type, self.spellId, self.mod.id)
else
self.combinedcount = 0
self.combinedtext = {}
end
end
function announcePrototype:CombinedShow(delay, ...)
if self.option and not self.mod.Options[self.option] then return end
if DBM.Options.DontShowBossAnnounces then return end -- don't show the announces if the spam filter option is set
if DBM.Options.DontShowTargetAnnouncements and (self.announceType == "target" or self.announceType == "targetcount") and not self.noFilter then return end--don't show announces that are generic target announces
local argTable = {...}
for i = 1, #argTable do
if type(argTable[i]) == "string" then
if #self.combinedtext < 8 then--Throttle spam. We may not need more than 9 targets..
if not checkEntry(self.combinedtext, argTable[i]) then
self.combinedtext[#self.combinedtext + 1] = argTable[i]
end
else
self.combinedcount = self.combinedcount + 1
end
end
end
unschedule(self.Show, self.mod, self)
schedule(delay or 0.5, self.Show, self.mod, self, ...)
end
function announcePrototype:Schedule(t, ...)
return schedule(t, self.Show, self.mod, self, ...)
end
function announcePrototype:Countdown(time, numAnnounces, ...)
scheduleCountdown(time, numAnnounces, self.Show, self.mod, self, ...)
end
function announcePrototype:Cancel(...)
return unschedule(self.Show, self.mod, self, ...)
end
function announcePrototype:Play(name, customPath)
local voice = DBM.Options.ChosenVoicePack
if voice == "None" then return end
local always = DBM.Options.AlwaysPlayVoice
if DBM.Options.DontShowTargetAnnouncements and (self.announceType == "target" or self.announceType == "targetcount") and not self.noFilter and not always then return end--don't show announces that are generic target announces
if not DBM.Options.DontShowBossAnnounces and (not self.option or self.mod.Options[self.option]) or always then
--Filter tank specific voice alerts for non tanks if tank filter enabled
--But still allow AlwaysPlayVoice to play as well.
if (name == "changemt" or name == "tauntboss") and DBM.Options.FilterTankSpec and not self.mod:IsTank() and not always then return end
local path = customPath or "Interface\\AddOns\\DBM-VP"..voice.."\\"..name..".ogg"
DBM:PlaySoundFile(path)
end
end
function announcePrototype:ScheduleVoice(t, ...)
if DBM.Options.ChosenVoicePack == "None" then return end
return schedule(t, self.Play, self.mod, self, ...)
end
function announcePrototype:CancelVoice(...)
if DBM.Options.ChosenVoicePack == "None" then return end
return unschedule(self.Play, self.mod, self, ...)
end
-- old constructor (no auto-localize)
function bossModPrototype:NewAnnounce(text, color, icon, optionDefault, optionName, soundOption)
if not text then
error("NewAnnounce: you must provide announce text", 2)
return
end
if type(optionName) == "number" then
DBM:Debug("Non auto localized optionNames cannot be numbers, fix this for "..text)
optionName = nil
end
if soundOption and type(soundOption) == "boolean" then
soundOption = 0--No Sound
end
local obj = setmetatable(
{
text = self.localization.warnings[text],
combinedtext = {},
combinedcount = 0,
color = DBM.Options.WarningColors[color or 1] or DBM.Options.WarningColors[1],
sound = soundOption or 1,
mod = self,
icon = (type(icon) == "string" and icon:match("ej%d+") and select(4, DBM:EJ_GetSectionInfo(string.sub(icon, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(icon, 3)))) or (type(icon) == "number" and GetSpellTexture(icon)) or icon or "Interface\\Icons\\Spell_Nature_WispSplode",
},
mt
)
if optionName then
obj.option = optionName
self:AddBoolOption(obj.option, optionDefault, "announce")
elseif not (optionName == false) then
obj.option = text
self:AddBoolOption(obj.option, optionDefault, "announce")
end
tinsert(self.announces, obj)
return obj
end
-- new constructor (partially auto-localized warnings and options, yay!)
local function newAnnounce(self, announceType, spellId, color, icon, optionDefault, optionName, castTime, preWarnTime, soundOption, noFilter)
if not spellId then
error("newAnnounce: you must provide spellId", 2)
return
end
local optionVersion
if type(optionName) == "number" then
optionVersion = optionName
optionName = nil
end
if soundOption and type(soundOption) == "boolean" then
soundOption = 0--No Sound
end
if type(spellId) == "string" and spellId:match("OptionVersion") then
print("newAnnounce for "..color.." is using OptionVersion hack. this is depricated")
return
end
local text, spellName = setText(announceType, spellId, icon, castTime, preWarnTime)
icon = icon or spellId
local obj = setmetatable( -- todo: fix duplicate code
{
text = text,
combinedtext = {},
combinedcount = 0,
announceType = announceType,
color = DBM.Options.WarningColors[color or 1] or DBM.Options.WarningColors[1],
mod = self,
icon = (type(icon) == "string" and icon:match("ej%d+") and select(4, DBM:EJ_GetSectionInfo(string.sub(icon, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(icon, 3)))) or (type(icon) == "number" and GetSpellTexture(icon)) or icon or "Interface\\Icons\\Spell_Nature_WispSplode",
sound = soundOption or 1,
type = announceType,
spellId = spellId,
spellName = spellName,
noFilter = noFilter,
castTime = castTime,
preWarnTime = preWarnTime,
},
mt
)
local catType = "announce"--Default to General announce
--Change if Personal or Other
if announceType == "target" or announceType == "targetcount" or announceType == "stack" then
catType = "announceother"
end
if optionName then
obj.option = optionName
self:AddBoolOption(obj.option, optionDefault, catType)
elseif not (optionName == false) then
obj.option = catType..spellId..announceType..(optionVersion or "")
self:AddBoolOption(obj.option, optionDefault, catType)
self.localization.options[obj.option] = DBM_CORE_AUTO_ANNOUNCE_OPTIONS[announceType]:format(spellId)
end
tinsert(self.announces, obj)
return obj
end
function bossModPrototype:NewYouAnnounce(spellId, color, ...)
return newAnnounce(self, "you", spellId, color or 1, ...)
end
function bossModPrototype:NewTargetNoFilterAnnounce(spellId, color, icon, optionDefault, optionName, castTime, preWarnTime, noSound, noFilter)
return newAnnounce(self, "target", spellId, color or 3, icon, optionDefault, optionName, castTime, preWarnTime, noSound, true)
end
function bossModPrototype:NewTargetAnnounce(spellId, color, ...)
return newAnnounce(self, "target", spellId, color or 3, ...)
end
function bossModPrototype:NewTargetCountAnnounce(spellId, color, ...)
return newAnnounce(self, "targetcount", spellId, color or 3, ...)
end
function bossModPrototype:NewSpellAnnounce(spellId, color, ...)
return newAnnounce(self, "spell", spellId, color or 2, ...)
end
function bossModPrototype:NewEndAnnounce(spellId, color, ...)
return newAnnounce(self, "ends", spellId, color or 2, ...)
end
function bossModPrototype:NewEndTargetAnnounce(spellId, color, ...)
return newAnnounce(self, "endtarget", spellId, color or 2, ...)
end
function bossModPrototype:NewFadesAnnounce(spellId, color, ...)
return newAnnounce(self, "fades", spellId, color or 2, ...)
end
function bossModPrototype:NewAddsLeftAnnounce(spellId, color, ...)
return newAnnounce(self, "adds", spellId, color or 3, ...)
end
function bossModPrototype:NewCountAnnounce(spellId, color, ...)
return newAnnounce(self, "count", spellId, color or 2, ...)
end
function bossModPrototype:NewStackAnnounce(spellId, color, ...)
return newAnnounce(self, "stack", spellId, color or 2, ...)
end
function bossModPrototype:NewCastAnnounce(spellId, color, castTime, icon, optionDefault, optionName, noArg, noSound)
local optionVersion
if type(optionName) == "number" then
optionVersion = optionName
optionName = nil
end
if type(spellId) == "string" and spellId:match("OptionVersion") then--LEGACY hack, remove when new DBM core and other mods released
print("NewCastAnnounce is using OptionVersion and this is depricated for "..color)
return
end
return newAnnounce(self, "cast", spellId, color or 3, icon, optionDefault, optionName, castTime, nil, noSound)
end
function bossModPrototype:NewSoonAnnounce(spellId, color, ...)
return newAnnounce(self, "soon", spellId, color or 1, ...)
end
function bossModPrototype:NewPreWarnAnnounce(spellId, time, color, icon, optionDefault, optionName, noArg, noSound)
local optionVersion
if type(optionName) == "number" then
optionVersion = optionName
optionName = nil
end
if type(spellId) == "string" and spellId:match("OptionVersion") then--LEGACY hack, remove when new DBM core and other mods released
print("NewCastAnnounce is using OptionVersion and this is depricated for "..color)
return
end
return newAnnounce(self, "prewarn", spellId, color or 1, icon, optionDefault, optionName, nil, time, noSound)
end
function bossModPrototype:NewPhaseAnnounce(stage, color, icon, ...)
return newAnnounce(self, "stage", stage, color or 1, icon or "Interface\\Icons\\Spell_Nature_WispSplode", ...)
end
function bossModPrototype:NewPhaseChangeAnnounce(color, icon, ...)
return newAnnounce(self, "stagechange", 0, color or 1, icon or "Interface\\Icons\\Spell_Nature_WispSplode", ...)
end
function bossModPrototype:NewPrePhaseAnnounce(stage, color, icon, ...)
return newAnnounce(self, "prestage", stage, color or 1, icon or "Interface\\Icons\\Spell_Nature_WispSplode", ...)
end
end
--------------------
-- Sound Object --
--------------------
do
--Sound Object (basically only used by countdown now)
local soundPrototype = {}
local mt = { __index = soundPrototype }
function bossModPrototype:NewSound(spellId, optionDefault, optionName)
if not (optionName == false) then--Basically, all mods still using NewSound.
-- Because there are going to be users who update core and not old mods, we need to check and alert
--I'll try to avoid this as much as possible by removing NewSound from all old mods in advance of dbm core update
-- print("Error, NewSound depricated. Update your old DBM mods to remove this error") --bf@178.com
return
end
self.numSounds = self.numSounds and self.numSounds + 1 or 1
local obj = setmetatable(
{
mod = self,
},
mt
)
return obj
end
function soundPrototype:Play(file)
DBM:PlaySoundFile(file)
end
function soundPrototype:Schedule(t, ...)
return schedule(t, self.Play, self.mod, self, ...)
end
function soundPrototype:Cancel(...)
return unschedule(self.Play, self.mod, self, ...)
end
--Voice Object
--Individual options still generated in case a person likes to enable voice, but not for ALL warnings (they can pick and choose what is enabled/disabled"
local soundPrototype2 = {}
local mt = { __index = soundPrototype2 }
function bossModPrototype:NewVoice(spellId, optionDefault, optionName, optionVersion)
if not spellId and not optionName then
print("NewVoice: you must provide either spellId or optionName", 2)
return
end
if type(spellId) == "string" and spellId:match("OptionVersion") then
print("NewVoice for "..optionDefault.." is using OptionVersion hack. this is not needed, this only has 4 args, do this properly")
return
end
self.numSounds = self.numSounds and self.numSounds + 1 or 1
local obj = setmetatable(
{
mod = self,
},
mt
)
if #DBM.Voices < 2 then optionName = false end--Hide options if no voice packs are installed
if optionName then
if spellId then--Still need to use spell ID for voice pack filter if one is provided
obj.option = "Voice"..spellId..(optionVersion or "")
self:AddBoolOption(obj.option, optionDefault, "sound")
self.localization.options[obj.option] = optionName
else
obj.option = optionName
self:AddBoolOption(obj.option, optionDefault, "sound")
end
elseif not (optionName == false) then
obj.option = "Voice"..spellId..(optionVersion or "")
self:AddBoolOption(obj.option, optionDefault, "sound")
self.localization.options[obj.option] = DBM_CORE_AUTO_VOICE_OPTION_TEXT:format(spellId)
end
return obj
end
--If no file at path, it should silenty fail. However, I want to try to only add NewVoice to mods for files that already exist.
function soundPrototype2:Play(name, customPath)
local voice = DBM.Options.ChosenVoicePack
if voice == "None" then return end
local always = DBM.Options.AlwaysPlayVoice
if not self.option or self.mod.Options[self.option] or always then
--Filter tank specific voice alerts for non tanks if tank filter enabled
--But still allow AlwaysPlayVoice to play as well.
if (name == "changemt" or name == "tauntboss") and DBM.Options.FilterTankSpec and not self.mod:IsTank() and not always then return end
local path = customPath or "Interface\\AddOns\\DBM-VP"..voice.."\\"..name..".ogg"
DBM:PlaySoundFile(path)
end
end
function soundPrototype2:Schedule(t, ...)
if DBM.Options.ChosenVoicePack == "None" then return end
return schedule(t, self.Play, self.mod, self, ...)
end
function soundPrototype2:Cancel(...)
if DBM.Options.ChosenVoicePack == "None" then return end
return unschedule(self.Play, self.mod, self, ...)
end
end
--Old Voice Object, by Mini_Dragon
do
local soundPrototype3 = {}
local mt3 = { __index = soundPrototype3 }
function bossModPrototype:SoundMM(SoundMMtag, SoundMMoption)
self.numSounds = self.numSounds and self.numSounds + 1 or 1
if (soundMMoption == nil) then
soundMMoption = true
end
local obj3 = setmetatable(
{
mod = self,
},
mt3
)
self:AddBoolOption(SoundMMtag, SoundMMoption, "misc")
return obj3
end
function soundPrototype3:Play(name)
if soundMMoption then
if DBM.Options.UseMasterVolume then
PlaySoundFile("Interface\\AddOns\\DBM-VP"..DBM.Options.ChosenVoicePack.."\\"..name..".ogg", "Master")
else
PlaySoundFile("Interface\\AddOns\\DBM-VP"..DBM.Options.ChosenVoicePack.."\\"..name..".ogg")
end
end
end
function soundPrototype3:Schedule(t, ...)
if soundMMoption then
return schedule(t, self.Play, self.mod, self, ...)
end
end
function soundPrototype3:Cancel(...)
if soundMMoption then
return unschedule(self.Play, self.mod, self, ...)
end
end
end
-- bf@178.com 10
----------------------------
-- Countdown/out object --
----------------------------
do
local countdownProtoType = {}
local voice1, voice2, voice3 = nil, nil, nil
local voice1max, voice2max, voice3max = 5, 5, 5
local path1, path2, path3 = nil, nil, nil
local mt = {__index = countdownProtoType}
function DBM:BuildVoiceCountdownCache()
voice1 = self.Options.CountdownVoice
voice2 = self.Options.CountdownVoice2
voice3 = self.Options.CountdownVoice3v2
local voicesFound = 0
for i = 1, #self.Counts do
local curVoice = self.Counts[i]
if curVoice.value == voice1 then
path1 = curVoice.path
voice1max = curVoice.max
end
if curVoice.value == voice2 then
path2 = curVoice.path
voice2max = curVoice.max
end
if curVoice.value == voice3 then
path3 = curVoice.path
voice3max = curVoice.max
end
end
end
function countdownProtoType:Start(timer, count)
if not self.option or self.mod.Options[self.option] then
timer = timer or self.timer or 10
timer = timer < 2 and self.timer or timer
count = count or self.count or 5
if timer <= count then count = floor(timer) end
if DBM.Options.DontPlayCountdowns then return end
if not path1 or not path2 or not path3 then
DBM:Debug("Voice cache not built at time of countdownProtoType:Start. On fly caching.", 3)
DBM:BuildVoiceCountdownCache()
end
local voice, maxCount, path
if self.alternateVoice == 2 then
voice = voice2 or DBM.DefaultOptions.CountdownVoice2
maxCount = voice2max or 10
path = path2 or "Interface\\AddOns\\DBM-Core\\Sounds\\Kolt\\"
elseif self.alternateVoice == 3 then
voice = voice3 or DBM.DefaultOptions.CountdownVoice3v2
maxCount = voice3max or 5
path = path3 or "Interface\\AddOns\\DBM-Core\\Sounds\\Heroes\\Necromancer\\"
else
voice = voice1 or DBM.DefaultOptions.CountdownVoice
maxCount = voice1max or 10
path = path1 or "Interface\\AddOns\\DBM-Core\\Sounds\\Corsica\\"
end
if not path then--Should not happen but apparently it does somehow
DBM:Debug("Voice path failed in countdownProtoType:Start.")
return
end
if self.type == "Countout" then
for i = 1, timer do
if i < maxCount then
self.sound5:Schedule(i, path..i..".ogg")
end
end
else
for i = count, 1, -1 do
if i <= maxCount then
self.sound5:Schedule(timer-i, path..i..".ogg")
end
end
end
end
end
countdownProtoType.Show = countdownProtoType.Start
function countdownProtoType:Schedule(t)
return schedule(t, self.Start, self.mod, self)
end
function countdownProtoType:Cancel()
self.mod:Unschedule(self.Start, self)
self.sound5:Cancel()
end
countdownProtoType.Stop = countdownProtoType.Cancel
local function newCountdown(self, countdownType, timer, spellId, optionDefault, optionName, count, textDisabled, altVoice)
if not spellId and not optionName then
print("NewCountdown: you must provide either spellId or optionName", 2)
return
end
if type(timer) == "string" and timer:match("OptionVersion") then
print("OptionVersion depricated for newCountdown :"..optionDefault)
return
end
local optionVersion
if type(optionName) == "number" then
optionVersion = optionName
optionName = nil
end
if altVoice == true then altVoice = 2 end--Compat
if type(timer) == "string" then
if timer:match("AltTwo") then
altVoice = 3
timer = tonumber(string.sub(timer, 7))
elseif timer:match("Alt") then
altVoice = 2
timer = tonumber(string.sub(timer, 4))
end
end
--TODO, maybe make this not use an entire sound object?
local sound5 = self:NewSound(5, true, false)
timer = timer or 10
count = count or 4
spellId = spellId or 39505
local obj = setmetatable(
{
id = optionName or countdownType..spellId..(optionVersion or ""),
type = countdownType,
sound5 = sound5,
timer = timer,
count = count,
textDisabled = textDisabled,
alternateVoice = altVoice,
mod = self
},
mt
)
if optionName then
obj.option = obj.id
self:AddBoolOption(obj.option, optionDefault, "sound")
elseif not (optionName == false) then
obj.option = obj.id
self:AddBoolOption(obj.option, optionDefault, "sound")
if countdownType == "Countdown" then
self.localization.options[obj.option] = DBM_CORE_AUTO_COUNTDOWN_OPTION_TEXT:format(spellId)
elseif countdownType == "CountdownFades" then
self.localization.options[obj.option] = DBM_CORE_AUTO_COUNTDOWN_OPTION_TEXT2:format(spellId)
elseif countdownType == "Countout" then
self.localization.options[obj.option] = DBM_CORE_AUTO_COUNTOUT_OPTION_TEXT:format(spellId)
end
end
tinsert(self.countdowns, obj)
return obj
end
function bossModPrototype:NewCountdown(...)
return newCountdown(self, "Countdown", ...)
end
function bossModPrototype:NewCountdownFades(...)
return newCountdown(self, "CountdownFades", ...)
end
function bossModPrototype:NewCountout(...)
return newCountdown(self, "Countout", ...)
end
end
--------------------
-- Yell Object --
--------------------
do
local voidForm = GetSpellInfo(194249)
local yellPrototype = {}
local mt = { __index = yellPrototype }
local function newYell(self, yellType, spellId, yellText, optionDefault, optionName, chatType)
if not spellId and not yellText then
error("NewYell: you must provide either spellId or yellText", 2)
return
end
if type(spellId) == "string" and spellId:match("OptionVersion") then
print("newYell for: "..yellText.." is using OptionVersion hack. This is depricated")
return
end
local optionVersion
if type(optionName) == "number" then
optionVersion = optionName
optionName = nil
end
local displayText
if not yellText then
if type(spellId) == "string" and spellId:match("ej%d+") then
displayText = DBM_CORE_AUTO_YELL_ANNOUNCE_TEXT[yellType]:format(DBM:EJ_GetSectionInfo(string.sub(spellId, 3)) or DBM_CORE_UNKNOWN)
else
displayText = DBM_CORE_AUTO_YELL_ANNOUNCE_TEXT[yellType]:format(DBM:GetSpellInfo(spellId) or DBM_CORE_UNKNOWN)
end
end
--Passed spellid as yellText.
--Auto localize spelltext using yellText instead
if yellText and type(yellText) == "number" then
displayText = DBM_CORE_AUTO_YELL_ANNOUNCE_TEXT[yellType]:format(DBM:GetSpellInfo(yellText) or DBM_CORE_UNKNOWN)
end
local obj = setmetatable(
{
text = displayText or yellText,
mod = self,
chatType = chatType,
yellType = yellType
},
mt
)
if optionName then
obj.option = optionName
self:AddBoolOption(obj.option, optionDefault, "misc")
elseif not (optionName == false) then
obj.option = "Yell"..(spellId or yellText)..(yellType ~= "yell" and yellType or "")..(optionVersion or "")
self:AddBoolOption(obj.option, optionDefault, "misc")
self.localization.options[obj.option] = DBM_CORE_AUTO_YELL_OPTION_TEXT[yellType]:format(spellId)
end
return obj
end
function yellPrototype:Yell(...)
if DBM.Options.DontSendYells or self.yellType and self.yellType == "position" and DBM:UnitBuff("player", voidForm) then return end
if not self.option or self.mod.Options[self.option] then
if self.yellType == "combo" then
SendChatMessage(pformat(self.text, ...), self.chatType or "YELL")
else
SendChatMessage(pformat(self.text, ...), self.chatType or "SAY")
end
end
end
yellPrototype.Show = yellPrototype.Yell
function yellPrototype:Schedule(t, ...)
return schedule(t, self.Yell, self.mod, self, ...)
end
function yellPrototype:Countdown(time, numAnnounces, ...)
scheduleCountdown(time, numAnnounces, self.Yell, self.mod, self, ...)
end
function yellPrototype:Cancel(...)
return unschedule(self.Yell, self.mod, self, ...)
end
function bossModPrototype:NewYell(...)
return newYell(self, "yell", ...)
end
function bossModPrototype:NewShortYell(...)
return newYell(self, "shortyell", ...)
end
function bossModPrototype:NewCountYell(...)
return newYell(self, "count", ...)
end
function bossModPrototype:NewFadesYell(...)
return newYell(self, "fade", ...)
end
function bossModPrototype:NewShortFadesYell(...)
return newYell(self, "shortfade", ...)
end
function bossModPrototype:NewIconFadesYell(...)
return newYell(self, "iconfade", ...)
end
function bossModPrototype:NewPosYell(...)
return newYell(self, "position", ...)
end
function bossModPrototype:NewComboYell(...)
return newYell(self, "combo", ...)
end
end
------------------------------
-- Special Warning Object --
------------------------------
do
local frame = CreateFrame("Frame", "DBMSpecialWarning", UIParent)
local font1 = frame:CreateFontString("DBMSpecialWarning1", "OVERLAY", "ZoneTextFont")
font1:SetWidth(1024)
font1:SetHeight(0)
font1:SetPoint("TOP", 0, 0)
local font2 = frame:CreateFontString("DBMSpecialWarning2", "OVERLAY", "ZoneTextFont")
font2:SetWidth(1024)
font2:SetHeight(0)
font2:SetPoint("TOP", font1, "BOTTOM", 0, 0)
frame:SetMovable(1)
frame:SetWidth(1)
frame:SetHeight(1)
frame:SetFrameStrata("HIGH")
frame:SetClampedToScreen()
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
local font1elapsed, font2elapsed, moving
local function fontHide1()
local duration = DBM.Options.SpecialWarningDuration2
if font1elapsed > duration * 1.3 then
font1:Hide()
if frame.font1ticker then
frame.font1ticker:Cancel()
frame.font1ticker = nil
end
elseif font1elapsed > duration then
font1elapsed = font1elapsed + 0.05
local alpha = 1 - (font1elapsed - duration) / (duration * 0.3)
font1:SetAlpha(alpha > 0 and alpha or 0)
else
font1elapsed = font1elapsed + 0.05
font1:SetAlpha(1)
end
end
local function fontHide2()
local duration = DBM.Options.SpecialWarningDuration2
if font2elapsed > duration * 1.3 then
font2:Hide()
if frame.font2ticker then
frame.font2ticker:Cancel()
frame.font2ticker = nil
end
elseif font2elapsed > duration then
font2elapsed = font2elapsed + 0.05
local alpha = 1 - (font2elapsed - duration) / (duration * 0.3)
font2:SetAlpha(alpha > 0 and alpha or 0)
else
font2elapsed = font2elapsed + 0.05
font2:SetAlpha(1)
end
end
function DBM:UpdateSpecialWarningOptions()
frame:ClearAllPoints()
frame:SetPoint(self.Options.SpecialWarningPoint, UIParent, self.Options.SpecialWarningPoint, self.Options.SpecialWarningX, self.Options.SpecialWarningY)
font1:SetFont(self.Options.SpecialWarningFont, self.Options.SpecialWarningFontSize2, self.Options.SpecialWarningFontStyle == "None" and nil or self.Options.SpecialWarningFontStyle)
font2:SetFont(self.Options.SpecialWarningFont, self.Options.SpecialWarningFontSize2, self.Options.SpecialWarningFontStyle == "None" and nil or self.Options.SpecialWarningFontStyle)
font1:SetTextColor(unpack(self.Options.SpecialWarningFontCol))
font2:SetTextColor(unpack(self.Options.SpecialWarningFontCol))
if self.Options.SpecialWarningFontShadow then
font1:SetShadowOffset(1, -1)
font2:SetShadowOffset(1, -1)
else
font1:SetShadowOffset(0, 0)
font2:SetShadowOffset(0, 0)
end
end
function DBM:AddSpecialWarning(text, force)
local added = false
if not frame.font1ticker then
font1elapsed = 0
font1.lastUpdate = GetTime()
font1:SetText(text)
font1:Show()
added = true
frame.font1ticker = frame.font1ticker or C_TimerNewTicker(0.05, fontHide1)
elseif not frame.font2ticker or force then
font2elapsed = 0
font2.lastUpdate = GetTime()
font2:SetText(text)
font2:Show()
added = true
frame.font2ticker = frame.font2ticker or C_TimerNewTicker(0.05, fontHide2)
end
if not added then
local prevText1 = font2:GetText()
font1:SetText(prevText1)
font1elapsed = font2elapsed
self:AddSpecialWarning(text, true)
end
end
do
local anchorFrame
local function moveEnd(self)
moving = false
anchorFrame:Hide()
font1elapsed = self.Options.SpecialWarningDuration2
font2elapsed = self.Options.SpecialWarningDuration2
frame:SetFrameStrata("HIGH")
self:Unschedule(moveEnd)
self.Bars:CancelBar(DBM_CORE_MOVE_SPECIAL_WARNING_BAR)
end
function DBM:MoveSpecialWarning()
if not anchorFrame then
anchorFrame = CreateFrame("Frame", nil, frame)
anchorFrame:SetWidth(32)
anchorFrame:SetHeight(32)
anchorFrame:EnableMouse(true)
anchorFrame:SetPoint("TOP", frame, "TOP", 0, 32)
anchorFrame:RegisterForDrag("LeftButton")
anchorFrame:SetClampedToScreen()
anchorFrame:Hide()
local texture = anchorFrame:CreateTexture()
texture:SetTexture("Interface\\Addons\\DBM-GUI\\textures\\dot.blp")
texture:SetPoint("CENTER", anchorFrame, "CENTER", 0, 0)
texture:SetWidth(32)
texture:SetHeight(32)
anchorFrame:SetScript("OnDragStart", function()
frame:StartMoving()
self:Unschedule(moveEnd)
self.Bars:CancelBar(DBM_CORE_MOVE_SPECIAL_WARNING_BAR)
end)
anchorFrame:SetScript("OnDragStop", function()
frame:StopMovingOrSizing()
local point, _, _, xOfs, yOfs = frame:GetPoint(1)
self.Options.SpecialWarningPoint = point
self.Options.SpecialWarningX = xOfs
self.Options.SpecialWarningY = yOfs
self:Schedule(15, moveEnd, self)
self.Bars:CreateBar(15, DBM_CORE_MOVE_SPECIAL_WARNING_BAR)
end)
end
if anchorFrame:IsShown() then
moveEnd(self)
else
moving = true
anchorFrame:Show()
DBM:AddSpecialWarning(DBM_CORE_MOVE_SPECIAL_WARNING_TEXT)
DBM:AddSpecialWarning(DBM_CORE_MOVE_SPECIAL_WARNING_TEXT)
self:Schedule(15, moveEnd, self)
self.Bars:CreateBar(15, DBM_CORE_MOVE_SPECIAL_WARNING_BAR)
frame:Show()
frame:SetFrameStrata("TOOLTIP")
frame:SetAlpha(1)
end
end
end
local specialWarningPrototype = {}
local mt = {__index = specialWarningPrototype}
local function classColoringFunction(cap)
cap = cap:sub(2, -2)
local noStrip = cap:match("noStrip ")
if not noStrip then
local name = cap
if DBM.Options.StripServerName then
cap = Ambiguate(cap, "short")
end
if DBM.Options.SWarnClassColor then
local playerColor = RAID_CLASS_COLORS[DBM:GetRaidClass(name)]
if playerColor then
cap = ("|r|cff%.2x%.2x%.2x%s|r|cff%.2x%.2x%.2x"):format(playerColor.r * 255, playerColor.g * 255, playerColor.b * 255, cap, DBM.Options.SpecialWarningFontCol[1] * 255, DBM.Options.SpecialWarningFontCol[2] * 255, DBM.Options.SpecialWarningFontCol[3] * 255)
end
end
else
cap = cap:sub(9)
end
return cap
end
local textureCode = " |T%s:12:12|t "
local function setText(announceType, spellId, stacks)
local text, spellName
if type(spellId) == "string" and spellId:match("ej%d+") then
spellName = DBM:EJ_GetSectionInfo(string.sub(spellId, 3)) or DBM_CORE_UNKNOWN
else
spellName = DBM:GetSpellInfo(spellId) or DBM_CORE_UNKNOWN
end
if announceType == "prewarn" then
if type(stacks) == "string" then
text = DBM_CORE_AUTO_SPEC_WARN_TEXTS[announceType]:format(spellName, stacks)
else
text = DBM_CORE_AUTO_SPEC_WARN_TEXTS[announceType]:format(spellName, DBM_CORE_SEC_FMT:format(tostring(stacks or 5)))
end
else
text = DBM_CORE_AUTO_SPEC_WARN_TEXTS[announceType]:format(spellName)
end
return text, spellName
end
function specialWarningPrototype:Show(...)
if not DBM.Options.DontShowSpecialWarnings and not DBM.Options.DontShowSpecialWarningText and (not self.option or self.mod.Options[self.option]) and not moving and frame then
if self.announceType == "taunt" and DBM.Options.FilterTankSpec and not self.mod:IsTank() then return end--Don't tell non tanks to taunt, ever.
local argTable = {...}
-- add a default parameter for move away warnings
if self.announceType == "gtfo" then
if #argTable == 0 then
argTable[1] = DBM_CORE_BAD
end
end
if #self.combinedtext > 0 then
--Throttle spam.
if DBM.Options.SWarningAlphabetical then
tsort(self.combinedtext)
end
local combinedText = tconcat(self.combinedtext, "<, >")
if self.combinedcount == 1 then
combinedText = combinedText.." "..DBM_CORE_GENERIC_WARNING_OTHERS
elseif self.combinedcount > 1 then
combinedText = combinedText.." "..DBM_CORE_GENERIC_WARNING_OTHERS2:format(self.combinedcount)
end
--Process
for i = 1, #argTable do
if type(argTable[i]) == "string" then
argTable[i] = combinedText
end
end
end
local message = pformat(self.text, unpack(argTable))
local text = ("%s%s%s"):format(
(DBM.Options.SpecialWarningIcon and self.icon and textureCode:format(self.icon)) or "",
message,
(DBM.Options.SpecialWarningIcon and self.icon and textureCode:format(self.icon)) or ""
)
local noteHasName = false
if self.option then
local noteText = self.mod.Options[self.option .. "SWNote"]
if noteText and type(noteText) == "string" and noteText ~= "" then--Filter false bool and empty strings
local count1 = self.announceType == "count" or self.announceType == "switchcount" or self.announceType == "targetcount"
local count2 = self.announceType == "interruptcount"
if count1 or count2 then--Counts support different note for EACH count
local noteCount
local notesTable = {string.split("/", noteText)}
if count1 then
noteCount = argTable[1]--Count should be first arg in table
elseif count2 then
noteCount = argTable[2]--Count should be second arg in table
end
if type(noteCount) == "string" then
--Probably a hypehnated double count like inferno slice or marked for death
local mainCount = string.split("-", noteCount)
noteCount = tonumber(mainCount)
end
noteText = notesTable[noteCount]
if noteText and type(noteText) == "string" and noteText ~= "" then--Refilter after string split to make sure a note for this count exists
local hasPlayerName = noteText:find(playerName)
if DBM.Options.SWarnNameInNote and hasPlayerName then
noteHasName = 5
end
--Terminate special warning, it's an interrupt count warning without player name and filter enabled
if count2 and DBM.Options.FilterInterruptNoteName and not hasPlayerName then return end
noteText = " ("..noteText..")"
text = text..noteText
end
else--Non count warnings will have one note, period
if DBM.Options.SWarnNameInNote and noteText:find(playerName) then
noteHasName = 5
end
if self.announceType and self.announceType:find("switch") then
noteText = noteText:gsub(">.-<", classColoringFunction)--Class color note text before combining with warning text.
end
noteText = " ("..noteText..")"
text = text..noteText
end
end
end
--No stripping on switch warnings, ever. They will NEVER have player name, but often have adds with "-" in name
if self.announceType and not self.announceType:find("switch") then
text = text:gsub(">.-<", classColoringFunction)
end
DBM:AddSpecialWarning(text)
self.combinedcount = 0
self.combinedtext = {}
if DBM.Options.ShowSWarningsInChat then
local colorCode = ("|cff%.2x%.2x%.2x"):format(DBM.Options.SpecialWarningFontCol[1] * 255, DBM.Options.SpecialWarningFontCol[2] * 255, DBM.Options.SpecialWarningFontCol[3] * 255)
self.mod:AddMsg(colorCode.."["..DBM_CORE_MOVE_SPECIAL_WARNING_TEXT.."] "..text.."|r", nil)
end
if not UnitIsDeadOrGhost("player") and DBM.Options.ShowFlashFrame then
if noteHasName then
local repeatCount = DBM.Options.SpecialWarningFlashRepeat5 and DBM.Options.SpecialWarningFlashRepeatAmount or 0
DBM.Flash:Show(DBM.Options.SpecialWarningFlashCol5[1],DBM.Options.SpecialWarningFlashCol5[2], DBM.Options.SpecialWarningFlashCol5[3], DBM.Options.SpecialWarningFlashDura5, DBM.Options.SpecialWarningFlashAlph5, repeatCount)
else
local number = self.flash
local repeatCount = DBM.Options["SpecialWarningFlashRepeat"..number] and DBM.Options.SpecialWarningFlashRepeatAmount or 0
local flashcolor = DBM.Options["SpecialWarningFlashCol"..number]
DBM.Flash:Show(flashcolor[1], flashcolor[2], flashcolor[3], DBM.Options["SpecialWarningFlashDura"..number], DBM.Options["SpecialWarningFlashAlph"..number], repeatCount)
end
end
--Text: Full message text
--Type: Announce type
--SpellId: Raw spell or encounter journal Id if available.
--Mod ID: Encounter ID as string, or a generic string for mods that don't have encounter ID (such as trash, dummy/test mods)
fireEvent("DBM_Announce", text, self.type, self.spellId, self.mod.id)
if self.sound then
local soundId = self.option and self.mod.Options[self.option .. "SWSound"] or self.flash
if noteHasName and type(soundId) == "number" then soundId = noteHasName end--Change number to 5 if it's not a custom sound, else, do nothing with it
if self.hasVoice and DBM.Options.ChosenVoicePack ~= "None" and self.hasVoice <= SWFilterDisabed and (type(soundId) == "number" and soundId < 5 and DBM.Options.VoiceOverSpecW2 == "DefaultOnly" or DBM.Options.VoiceOverSpecW2 == "All") then return end
if not self.option or self.mod.Options[self.option.."SWSound"] ~= "None" then
DBM:PlaySpecialWarningSound(soundId or 1)
end
end
else
self.combinedcount = 0
self.combinedtext = {}
end
end
function specialWarningPrototype:CombinedShow(delay, ...)
if DBM.Options.DontShowSpecialWarnings or DBM.Options.DontShowSpecialWarningText then return end
if self.option and not self.mod.Options[self.option] then return end
local argTable = {...}
for i = 1, #argTable do
if type(argTable[i]) == "string" then
if #self.combinedtext < 8 then--Throttle spam. We may not need more than 9 targets..
if not checkEntry(self.combinedtext, argTable[i]) then
self.combinedtext[#self.combinedtext + 1] = argTable[i]
end
else
self.combinedcount = self.combinedcount + 1
end
end
end
unschedule(self.Show, self.mod, self)
schedule(delay or 0.5, self.Show, self.mod, self, ...)
end
function specialWarningPrototype:DelayedShow(delay, ...)
unschedule(self.Show, self.mod, self, ...)
schedule(delay or 0.5, self.Show, self.mod, self, ...)
end
function specialWarningPrototype:Schedule(t, ...)
return schedule(t, self.Show, self.mod, self, ...)
end
function specialWarningPrototype:Countdown(time, numAnnounces, ...)
scheduleCountdown(time, numAnnounces, self.Show, self.mod, self, ...)
end
function specialWarningPrototype:Cancel(t, ...)
return unschedule(self.Show, self.mod, self, ...)
end
function specialWarningPrototype:Play(name, customPath)
local always = DBM.Options.AlwaysPlayVoice
local voice = DBM.Options.ChosenVoicePack
if voice == "None" then return end
if not DBM.Options.DontShowSpecialWarnings and (not self.option or self.mod.Options[self.option]) or always then
--Filter tank specific voice alerts for non tanks if tank filter enabled
--But still allow AlwaysPlayVoice to play as well.
if (name == "changemt" or name == "tauntboss") and DBM.Options.FilterTankSpec and not self.mod:IsTank() and not always then return end
local path = customPath or "Interface\\AddOns\\DBM-VP"..voice.."\\"..name..".ogg"
DBM:PlaySoundFile(path)
end
end
function specialWarningPrototype:ScheduleVoice(t, ...)
if DBM.Options.ChosenVoicePack == "None" then return end
return schedule(t, self.Play, self.mod, self, ...)
end
function specialWarningPrototype:CancelVoice(...)
if DBM.Options.ChosenVoicePack == "None" then return end
return unschedule(self.Play, self.mod, self, ...)
end
function bossModPrototype:NewSpecialWarning(text, optionDefault, optionName, optionVersion, runSound, hasVoice)
if not text then
error("NewSpecialWarning: you must provide special warning text", 2)
return
end
if type(text) == "string" and text:match("OptionVersion") then
print("NewSpecialWarning: you must provide remove optionversion hack for "..optionDefault)
return
end
if runSound == true then
runSound = 2
elseif not runSound then
runSound = 1
end
if hasVoice == true then--if not a number, set it to 2, old mods that don't use new numbered system
hasVoice = 2
end
local obj = setmetatable(
{
text = self.localization.warnings[text],
combinedtext = {},
combinedcount = 0,
mod = self,
sound = runSound>0,
flash = runSound,--Set flash color to hard coded runsound (even if user sets custom sounds)
hasVoice = hasVoice,
},
mt
)
local optionId = optionName or optionName ~= false and text
if optionId then
obj.voiceOptionId = hasVoice and "Voice"..optionId or nil
obj.option = optionId..(optionVersion or "")
self:AddSpecialWarningOption(optionId, optionDefault, runSound, "announce")
end
tinsert(self.specwarns, obj)
return obj
end
local function newSpecialWarning(self, announceType, spellId, stacks, optionDefault, optionName, optionVersion, runSound, hasVoice)
if not spellId then
error("newSpecialWarning: you must provide spellId", 2)
return
end
if runSound == true then
runSound = 2
elseif not runSound then
runSound = 1
end
if hasVoice == true then--if not a number, set it to 2, old mods that don't use new numbered system
hasVoice = 2
end
local text, spellName = setText(announceType, spellId, stacks)
local obj = setmetatable( -- todo: fix duplicate code
{
text = text,
combinedtext = {},
combinedcount = 0,
announceType = announceType,
mod = self,
sound = runSound>0,
flash = runSound,--Set flash color to hard coded runsound (even if user sets custom sounds)
hasVoice = hasVoice,
type = announceType,
spellId = spellId,
spellName = spellName,
stacks = stacks,
icon = (type(spellId) == "string" and spellId:match("ej%d+") and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3)))) or (type(spellId) == "number" and GetSpellTexture(spellId)) or nil
},
mt
)
if optionName then
obj.option = optionName
elseif not (optionName == false) then
obj.option = "SpecWarn"..spellId..announceType..(optionVersion or "")
if announceType == "stack" then
self.localization.options[obj.option] = DBM_CORE_AUTO_SPEC_WARN_OPTIONS[announceType]:format(stacks or 3, spellId)
elseif announceType == "prewarn" then
self.localization.options[obj.option] = DBM_CORE_AUTO_SPEC_WARN_OPTIONS[announceType]:format(tostring(stacks or 5), spellId)
else
self.localization.options[obj.option] = DBM_CORE_AUTO_SPEC_WARN_OPTIONS[announceType]:format(spellId)
end
end
if obj.option then
local catType = "announce"--Default to General announce
--Directly affects another target (boss or player) that you need to know about
if announceType == "target" or announceType == "targetcount" or announceType == "close" or announceType == "reflect" then
catType = "announceother"
--Directly affects you
elseif announceType == "you" or announceType == "youcount" or announceType == "youpos" or announceType == "move" or announceType == "dodge" or announceType == "moveaway" or announceType == "run" or announceType == "stack" or announceType == "moveto" or announceType == "soakpos" then
catType = "announcepersonal"
--Things you have to do to fulfil your role
elseif announceType == "taunt" or announceType == "dispel" or announceType == "interrupt" or announceType == "interruptcount" or announceType == "switch" or announceType == "switchcount" then
catType = "announcerole"
end
self:AddSpecialWarningOption(obj.option, optionDefault, runSound, catType)
end
obj.voiceOptionId = hasVoice and "Voice"..spellId or nil
tinsert(self.specwarns, obj)
return obj
end
function bossModPrototype:NewSpecialWarningSpell(text, optionDefault, ...)
return newSpecialWarning(self, "spell", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningEnd(text, optionDefault, ...)
return newSpecialWarning(self, "ends", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningFades(text, optionDefault, ...)
return newSpecialWarning(self, "fades", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningSoon(text, optionDefault, ...)
return newSpecialWarning(self, "soon", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningDispel(text, optionDefault, ...)
return newSpecialWarning(self, "dispel", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningInterrupt(text, optionDefault, ...)
return newSpecialWarning(self, "interrupt", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningInterruptCount(text, optionDefault, ...)
return newSpecialWarning(self, "interruptcount", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningYou(text, optionDefault, ...)
return newSpecialWarning(self, "you", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningYouCount(text, optionDefault, ...)
return newSpecialWarning(self, "youcount", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningYouPos(text, optionDefault, ...)
return newSpecialWarning(self, "youpos", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningSoakPos(text, optionDefault, ...)
return newSpecialWarning(self, "soakpos", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningTarget(text, optionDefault, ...)
return newSpecialWarning(self, "target", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningTargetCount(text, optionDefault, ...)
return newSpecialWarning(self, "targetcount", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningDefensive(text, optionDefault, ...)
return newSpecialWarning(self, "defensive", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningTaunt(text, optionDefault, ...)
return newSpecialWarning(self, "taunt", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningClose(text, optionDefault, ...)
return newSpecialWarning(self, "close", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningMove(text, optionDefault, ...)
return newSpecialWarning(self, "move", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningGTFO(text, optionDefault, ...)
return newSpecialWarning(self, "gtfo", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningDodge(text, optionDefault, ...)
return newSpecialWarning(self, "dodge", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningDodgeLoc(text, optionDefault, ...)
return newSpecialWarning(self, "dodgeloc", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningMoveAway(text, optionDefault, ...)
return newSpecialWarning(self, "moveaway", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningMoveTo(text, optionDefault, ...)
return newSpecialWarning(self, "moveto", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningJump(text, optionDefault, ...)
return newSpecialWarning(self, "jump", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningRun(text, optionDefault, ...)
return newSpecialWarning(self, "run", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningCast(text, optionDefault, ...)
return newSpecialWarning(self, "cast", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningLookAway(text, optionDefault, ...)
return newSpecialWarning(self, "lookaway", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningReflect(text, optionDefault, ...)
return newSpecialWarning(self, "reflect", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningCount(text, optionDefault, ...)
return newSpecialWarning(self, "count", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningStack(text, optionDefault, stacks, ...)
if type(text) == "string" and text:match("OptionVersion") then
print("NewSpecialWarning: you must provide remove optionversion hack for "..optionDefault)
end
return newSpecialWarning(self, "stack", text, stacks, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningSwitch(text, optionDefault, ...)
return newSpecialWarning(self, "switch", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningSwitchCount(text, optionDefault, ...)
return newSpecialWarning(self, "switchcount", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningAdds(text, optionDefault, ...)
return newSpecialWarning(self, "Adds", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningAddsCustom(text, optionDefault, ...)
return newSpecialWarning(self, "Addscustom", text, nil, optionDefault, ...)
end
function bossModPrototype:NewSpecialWarningPreWarn(text, optionDefault, time, ...)
if type(text) == "string" and text:match("OptionVersion") then
print("NewSpecialWarning: you must provide remove optionversion hack for "..optionDefault)
end
return newSpecialWarning(self, "prewarn", text, time, optionDefault, ...)
end
function DBM:PlayCountSound(number, forceVoice)
if number > 10 then return end
local voice
if forceVoice then--For options example
voice = forceVoice
else
voice = self.Options.CountdownVoice
end
local path
local maxCount = 5
for i = 1, #self.Counts do
if self.Counts[i].value == voice then
path = self.Counts[i].path
maxCount = self.Counts[i].max
break
end
end
if not path or (number > maxCount) then return end
self:PlaySoundFile(path..number..".ogg")
end
function DBM:RegisterCountSound(t, v, p, m)
--Prevent duplicate insert
for i = 1, #self.Counts do
if self.Counts[i].value == v then return end
end
--Insert into counts table.
if t and v and p and m then
tinsert(self.Counts, { text = t, value = v, path = p, max = m })
end
end
function DBM:CheckVoicePackVersion(value)
local activeVP = self.Options.ChosenVoicePack
--Check if voice pack out of date
if activeVP ~= "None" and activeVP == value then
if self.VoiceVersions[value] < 7 then--Version will be bumped when new voice packs released that contain new voices.
if not self.Options.DontShowReminders then
self:AddMsg(DBM_CORE_VOICE_PACK_OUTDATED)
end
SWFilterDisabed = self.VoiceVersions[value]--Set disable to version on current voice pack
else
SWFilterDisabed = 7
end
end
end
function DBM:PlaySpecialWarningSound(soundId)
local sound = type(soundId) == "number" and self.Options["SpecialWarningSound" .. (soundId == 1 and "" or soundId)] or soundId or self.Options.SpecialWarningSound
self:PlaySoundFile(sound)
end
local function testWarningEnd()
frame:SetFrameStrata("HIGH")
end
function DBM:ShowTestSpecialWarning(text, number, noSound)
if moving then
return
end
self:AddSpecialWarning(DBM_CORE_MOVE_SPECIAL_WARNING_TEXT)
frame:SetFrameStrata("TOOLTIP")
self:Unschedule(testWarningEnd)
self:Schedule(self.Options.SpecialWarningDuration2 * 1.3, testWarningEnd)
if number and not noSound then
self:PlaySpecialWarningSound(number)
end
if self.Options.ShowFlashFrame and number then
local flashColor = self.Options["SpecialWarningFlashCol"..number]
local repeatCount = self.Options["SpecialWarningFlashRepeat"..number] and self.Options.SpecialWarningFlashRepeatAmount or 0
self.Flash:Show(flashColor[1], flashColor[2], flashColor[3], self.Options["SpecialWarningFlashDura"..number], self.Options["SpecialWarningFlashAlph"..number], repeatCount)
end
end
end
--------------------
-- Timer Object --
--------------------
do
local timerPrototype = {}
local mt = {__index = timerPrototype}
function timerPrototype:Start(timer, ...)
if DBM.Options.DontShowBossTimers then return end
if timer and type(timer) ~= "number" then
return self:Start(nil, timer, ...) -- first argument is optional!
end
if not self.option or self.mod.Options[self.option] then
if self.type and self.type:find("count") and not self.allowdouble then--cdcount, nextcount. remove previous timer.
for i = #self.startedTimers, 1, -1 do
if DBM.Options.AutoCorrectTimer or (DBM.Options.DebugMode and DBM.Options.DebugLevel > 1) then
local bar = DBM.Bars:GetBar(self.startedTimers[i])
if bar then
local remaining = ("%.1f"):format(bar.timer)
local ttext = _G[bar.frame:GetName().."BarName"]:GetText() or ""
ttext = ttext.."("..self.id..")"
if bar.timer > 0.2 then
if timer then
self.correctedCast = timer - bar.timer--Store what lowest timer is in timer object
self.correctedDiff = difficultyIndex--Store index of correction to ensure the change is only used in one difficulty (so a mythic timer doesn't alter heroic for example)
end
DBM:Debug("Timer "..ttext.. " refreshed before expired. Remaining time is : "..remaining, 2)
end
end
end
DBM.Bars:CancelBar(self.startedTimers[i])
fireEvent("DBM_TimerStop", self.startedTimers[i])
self.startedTimers[i] = nil
end
end
local timer = timer and ((timer > 0 and timer) or self.timer + timer) or self.timer
--AI timer api:
--Starting ai timer with (1) indicates it's a first timer after pull
--Starting timer with (2) or (3) indicates it's a stage 2 or stage 3 first timer
--Starting AI timer with anything above 3 indicarets it's a regular timer and to use shortest time in between two regular casts
if self.type == "ai" then--A learning timer
if not DBM.Options.AITimer then return end
if timer > 4 then--Normal behavior.
local newPhase = false
for i = 1, 4 do
--Check for any phase timers that are strings, if a string it means last cast of this ability was first case of a given stage
if self["phase"..i.."CastTimer"] and type(self["phase"..i.."CastTimer"]) == "string" then--This is first cast of spell, we need to generate self.firstPullTimer
self["phase"..i.."CastTimer"] = tonumber(self["phase"..i.."CastTimer"])
self["phase"..i.."CastTimer"] = GetTime() - self["phase"..i.."CastTimer"]--We have generated a self.phase1CastTimer! Next pull, DBM should know timer for first cast next pull. FANCY!
DBM:Debug("AI timer learned a first timer for current phase of "..self["phase"..i.."CastTimer"], 2)
newPhase = true
end
end
if self.lastCast and not newPhase then--We have a GetTime() on last cast and it's not affected by a phase change
local timeLastCast = GetTime() - self.lastCast--Get time between current cast and last cast
if timeLastCast > 4 then--Prevent infinite loop cpu hang. Plus anything shorter than 5 seconds doesn't need a timer
if not self.lowestSeenCast or (self.lowestSeenCast and self.lowestSeenCast > timeLastCast) then--Always use lowest seen cast for a timer
self.lowestSeenCast = timeLastCast
DBM:Debug("AI timer learned a new lowest timer of "..self.lowestSeenCast, 2)
end
end
end
self.lastCast = GetTime()
if self.lowestSeenCast then--Always use lowest seen cast for timer
timer = self.lowestSeenCast
else
return--Don't start the bogus timer shoved into timer field in the mod
end
else--AI timer passed with 4 or less is indicating phase change, with timer as phase number
if self["phase"..timer.."CastTimer"] and type(self["phase"..timer.."CastTimer"]) == "number" then
timer = self["phase"..timer.."CastTimer"]
else--No first pull timer generated yet, set it to GetTime, as a string
self["phase"..timer.."CastTimer"] = tostring(GetTime())
return--Don't start the x second timer
end
end
end
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
if DBM.Options.AutoCorrectTimer or (DBM.Options.DebugMode and DBM.Options.DebugLevel > 1) then
if not self.type or (self.type ~= "target" and self.type ~= "active" and self.type ~= "fades" and self.type ~= "ai") then
local bar = DBM.Bars:GetBar(id)
if bar then
local remaining = ("%.1f"):format(bar.timer)
local ttext = _G[bar.frame:GetName().."BarName"]:GetText() or ""
ttext = ttext.."("..self.id..")"
if bar.timer > 0.2 then
self.correctedCast = timer - bar.timer--Store what lowest timer is for advanced user feature
self.correctedDiff = difficultyIndex--Store index of correction to ensure the change is only used in one difficulty (so a mythic timer doesn't alter heroic for example
DBM:Debug("Timer "..ttext.. " refreshed before expired. Remaining time is : "..remaining, 2)
end
end
end
end
if DBM.Options.AutoCorrectTimer and self.correctedCast and self.correctedDiff and self.correctedDiff == difficultyIndex and self.correctedCast < timer then
local debugtemp = timer - self.correctedCast
DBM:Debug("Timer autocorrected by "..debugtemp, 2)
timer = self.correctedCast
end
local colorId = 0
if self.option then
colorId = self.mod.Options[self.option .. "TColor"]
elseif self.colorType and type(self.colorType) == "string" then--No option for specific timer, but another bool option given that tells us where to look for TColor
colorId = self.mod.Options[self.colorType .. "TColor"] or 0
end
local bar = DBM.Bars:CreateBar(timer, id, self.icon, nil, nil, nil, nil, colorId)
if not bar then
return false, "error" -- creating the timer failed somehow, maybe hit the hard-coded timer limit of 15
end
local msg = ""
if self.type and not self.text then
msg = pformat(self.mod:GetLocalizedTimerText(self.type, self.spellId, self.name), ...)
else
if type(self.text) == "number" then
msg = pformat(self.mod:GetLocalizedTimerText(self.type, self.text, self.name), ...)
else
msg = pformat(self.text, ...)
end
end
msg = msg:gsub(">.-<", stripServerName)
bar:SetText(msg, self.inlineIcon)
--ID: Internal DBM timer ID
--msg: Timer Text
--timer: Raw timer value (number).
--Icon: Texture Path for Icon
--type: Timer type (Cooldowns: cd, cdcount, nextcount, nextsource, cdspecial, nextspecial, stage, ai. Durations: target, active, fades, roleplay. Casting: cast)
--spellId: Raw spellid if available (most timers will have spellId or EJ ID unless it's a specific timer not tied to ability such as pull or combat start or rez timers. EJ id will be in format ej%d
--colorID: Type classification (1-Add, 2-Aoe, 3-targeted ability, 4-Interrupt, 5-Role, 6-Stage, 7-User(custom))
--Mod ID: Encounter ID as string, or a generic string for mods that don't have encounter ID (such as trash, dummy/test mods)
fireEvent("DBM_TimerStart", id, msg, timer, self.icon, self.type, self.spellId, colorId, self.mod.id)
tinsert(self.startedTimers, id)
self.mod:Unschedule(removeEntry, self.startedTimers, id)
self.mod:Schedule(timer, removeEntry, self.startedTimers, id)
return bar
else
return false, "disabled"
end
end
timerPrototype.Show = timerPrototype.Start
function timerPrototype:DelayedStart(delay, ...)
unschedule(self.Start, self.mod, self, ...)
schedule(delay or 0.5, self.Start, self.mod, self, ...)
end
timerPrototype.DelayedShow = timerPrototype.DelayedStart
function timerPrototype:Schedule(t, ...)
return schedule(t, self.Start, self.mod, self, ...)
end
function timerPrototype:Unschedule(...)
return unschedule(self.Start, self.mod, self, ...)
end
function timerPrototype:Stop(...)
if select("#", ...) == 0 then
for i = #self.startedTimers, 1, -1 do
fireEvent("DBM_TimerStop", self.startedTimers[i])
DBM.Bars:CancelBar(self.startedTimers[i])
self.startedTimers[i] = nil
end
else
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
for i = #self.startedTimers, 1, -1 do
if self.startedTimers[i] == id then
fireEvent("DBM_TimerStop", id)
DBM.Bars:CancelBar(id)
tremove(self.startedTimers, i)
end
end
end
if self.type == "ai" then--A learning timer
if not DBM.Options.AITimer then return end
for i = 1, 4 do
--Check for any phase timers that are strings and never got a chance to become AI timers, then wipe them
if self["phase"..i.."CastTimer"] and type(self["phase"..i.."CastTimer"]) == "string" then
self["phase"..i.."CastTimer"] = nil
DBM:Debug("Wiping incomplete new timer of stage "..i, 2)
end
end
end
end
function timerPrototype:Cancel(...)
self:Stop(...)
self:Unschedule(...)
end
function timerPrototype:GetTime(...)
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
local bar = DBM.Bars:GetBar(id)
return bar and (bar.totalTime - bar.timer) or 0, (bar and bar.totalTime) or 0
end
function timerPrototype:GetRemaining(...)
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
local bar = DBM.Bars:GetBar(id)
return bar and bar.timer or 0
end
function timerPrototype:IsStarted(...)
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
local bar = DBM.Bars:GetBar(id)
return bar and true
end
function timerPrototype:SetTimer(timer)
self.timer = timer
end
function timerPrototype:Update(elapsed, totalTime, ...)
if DBM.Options.DontShowBossTimers then return end
if self:GetTime(...) == 0 then
self:Start(totalTime, ...)
end
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
fireEvent("DBM_TimerUpdate", id, elapsed, totalTime)
return DBM.Bars:UpdateBar(id, elapsed, totalTime)
end
function timerPrototype:AddTime(extendAmount, ...)
if DBM.Options.DontShowBossTimers then return end
if self:GetTime(...) == 0 then
return self:Start(extendAmount, ...)
else
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
local bar = DBM.Bars:GetBar(id)
if bar then
local elapsed, total = (bar.totalTime - bar.timer), bar.totalTime
if elapsed and total then
fireEvent("DBM_TimerUpdate", id, elapsed, total+extendAmount)
return DBM.Bars:UpdateBar(id, elapsed, total+extendAmount)
end
end
end
end
function timerPrototype:UpdateIcon(icon, ...)
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
local bar = DBM.Bars:GetBar(id)
if bar then
return bar:SetIcon((type(icon) == "string" and icon:match("ej%d+") and select(4, DBM:EJ_GetSectionInfo(string.sub(icon, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(icon, 3)))) or (type(icon) == "number" and GetSpellTexture(icon)) or icon or "Interface\\Icons\\Spell_Nature_WispSplode")
end
end
function timerPrototype:UpdateName(name, ...)
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
local bar = DBM.Bars:GetBar(id)
if bar then
return bar:SetText(name, self.inlineIcon)
end
end
function timerPrototype:SetColor(c, ...)
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
local bar = DBM.Bars:GetBar(id)
if bar then
return bar:SetColor(c)
end
end
function timerPrototype:DisableEnlarge(...)
local id = self.id..pformat((("\t%s"):rep(select("#", ...))), ...)
local bar = DBM.Bars:GetBar(id)
if bar then
bar.small = true
end
end
function timerPrototype:AddOption(optionDefault, optionName, colorType)
if optionName ~= false then
self.option = optionName or self.id
self.mod:AddBoolOption(self.option, optionDefault, "timer", nil, colorType)
end
end
function bossModPrototype:NewTimer(timer, name, icon, optionDefault, optionName, colorType, inlineIcon, r, g, b)
if r and type(r) == "string" then
DBM:Debug("|cffff0000r probably has inline icon in it and needs to be fixed for |r"..name..r)
r = nil--Fix it for users
end
if inlineIcon and type(inlineIcon) == "number" then
DBM:Debug("|cffff0000spellID texture path or colorType is in inlineIcon field and needs to be fixed for |r"..name..inlineIcon)
inlineIcon = nil--Fix it for users
end
local icon = (type(icon) == "string" and icon:match("ej%d+") and select(4, DBM:EJ_GetSectionInfo(string.sub(icon, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(icon, 3)))) or (type(icon) == "number" and GetSpellTexture(icon)) or icon or "Interface\\Icons\\Spell_Nature_WispSplode"
local obj = setmetatable(
{
text = self.localization.timers[name],
timer = timer,
id = name,
icon = icon,
colorType = colorType,
inlineIcon = inlineIcon,
r = r,
g = g,
b = b,
startedTimers = {},
mod = self,
},
mt
)
obj:AddOption(optionDefault, optionName, colorType)
tinsert(self.timers, obj)
return obj
end
-- new constructor for the new auto-localized timer types
-- note that the function might look unclear because it needs to handle different timer types, especially achievement timers need special treatment
local function newTimer(self, timerType, timer, spellId, timerText, optionDefault, optionName, colorType, texture, inlineIcon, r, g, b)
if type(timer) == "string" and timer:match("OptionVersion") then
DBM:Debug("|cffff0000OptionVersion hack depricated, remove it from: |r"..spellId)
return
end
if type(colorType) == "number" and colorType > 6 then
DBM:Debug("|cffff0000texture is in the colorType arg for: |r"..spellId)
end
--Use option optionName for optionVersion as well, no reason to split.
--This ensures that remaining arg positions match for auto generated and regular NewTimer
local optionVersion
if type(optionName) == "number" then
optionVersion = optionName
optionName = nil
end
local allowdouble
if type(timer) == "string" and timer:match("d%d+") then
allowdouble = true
timer = tonumber(string.sub(timer, 2))
end
local spellName, icon
local unparsedId = spellId
if timerType == "achievement" then
spellName = select(2, GetAchievementInfo(spellId))
icon = type(texture) == "number" and select(10, GetAchievementInfo(texture)) or texture or spellId and select(10, GetAchievementInfo(spellId))
elseif timerType == "cdspecial" or timerType == "nextspecial" or timerType == "stage" then
icon = type(texture) == "number" and GetSpellTexture(texture) or texture or type(spellId) == "string" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) or (type(spellId) == "number" and GetSpellTexture(spellId)) or "Interface\\Icons\\Spell_Nature_WispSplode"
if timerType == "stage" then
colorType = 6
end
elseif timerType == "roleplay" then
icon = type(texture) == "number" and GetSpellTexture(texture) or texture or type(spellId) == "string" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) or (type(spellId) == "number" and GetSpellTexture(spellId)) or "Interface\\Icons\\Spell_Holy_BorrowedTime"
colorType = 6
elseif timerType == "adds" or timerType == "addscustom" then
icon = type(texture) == "number" and GetSpellTexture(texture) or texture or type(spellId) == "string" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) or (type(spellId) == "number" and GetSpellTexture(spellId)) or "Interface\\Icons\\Spell_Nature_WispSplode"
colorType = 1
else
if type(spellId) == "string" and spellId:match("ej%d+") then
spellName = DBM:EJ_GetSectionInfo(string.sub(spellId, 3)) or ""
else
spellName = DBM:GetSpellInfo(spellId or 0)
end
if spellName then
icon = type(texture) == "number" and GetSpellTexture(texture) or texture or type(spellId) == "string" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) ~= "" and select(4, DBM:EJ_GetSectionInfo(string.sub(spellId, 3))) or (type(spellId) == "number" and GetSpellTexture(spellId))
else
icon = nil
end
end
spellName = spellName or tostring(spellId)
local timerTextValue
--If timertext is a number, accept it as a secondary auto translate spellid
if timerText and type(timerText) == "number" and DBM.Options.ShortTimerText then
timerTextValue = timerText
else
timerTextValue = self.localization.timers[timerText]
end
local id = "Timer"..(spellId or 0)..timerType..(optionVersion or "")
local obj = setmetatable(
{
text = timerTextValue,
type = timerType,
spellId = spellId,
name = spellName,
timer = timer,
id = id,
icon = icon,
colorType = colorType,
inlineIcon = inlineIcon,
r = r,
g = g,
b = b,
allowdouble = allowdouble,
startedTimers = {},
mod = self,
},
mt
)
obj:AddOption(optionDefault, optionName, colorType)
tinsert(self.timers, obj)
-- todo: move the string creation to the GUI with SetFormattedString...
if timerType == "achievement" then
self.localization.options[id] = DBM_CORE_AUTO_TIMER_OPTIONS[timerType]:format(GetAchievementLink(spellId):gsub("%[(.+)%]", "%1"))
elseif timerType == "cdspecial" or timerType == "nextspecial" or timerType == "stage" or timerType == "roleplay" then--Timers without spellid, generic
self.localization.options[id] = DBM_CORE_AUTO_TIMER_OPTIONS[timerType]--Using more than 1 stage timer or more than 1 special timer will break this, fortunately you should NEVER use more than 1 of either in a mod
else
self.localization.options[id] = DBM_CORE_AUTO_TIMER_OPTIONS[timerType]:format(unparsedId)
end
return obj
end
function bossModPrototype:NewTargetTimer(...)
return newTimer(self, "target", ...)
end
function bossModPrototype:NewBuffActiveTimer(...)
return newTimer(self, "active", ...)
end
function bossModPrototype:NewBuffFadesTimer(...)
return newTimer(self, "fades", ...)
end
function bossModPrototype:NewCastTimer(timer, ...)
if tonumber(timer) and timer > 1000 then -- hehe :) best hack in DBM. This makes the first argument optional, so we can omit it to use the cast time from the spell id ;)
local spellId = timer
timer = select(4, DBM:GetSpellInfo(spellId)) or 1000 -- GetSpellInfo takes YOUR spell haste into account...WTF?
local spellHaste = select(4, DBM:GetSpellInfo(53142)) / 10000 -- 53142 = Dalaran Portal, should have 10000 ms cast time
timer = timer / spellHaste -- calculate the real cast time of the spell...
return self:NewCastTimer(timer / 1000, spellId, ...)
end
return newTimer(self, "cast", timer, ...)
end
function bossModPrototype:NewCastSourceTimer(timer, ...)
if tonumber(timer) and timer > 1000 then -- hehe :) best hack in DBM. This makes the first argument optional, so we can omit it to use the cast time from the spell id ;)
local spellId = timer
timer = select(4, DBM:GetSpellInfo(spellId)) or 1000 -- GetSpellInfo takes YOUR spell haste into account...WTF?
local spellHaste = select(4, DBM:GetSpellInfo(53142)) / 10000 -- 53142 = Dalaran Portal, should have 10000 ms cast time
timer = timer / spellHaste -- calculate the real cast time of the spell...
return self:NewCastSourceTimer(timer / 1000, spellId, ...)
end
return newTimer(self, "castsource", timer, ...)
end
function bossModPrototype:NewCDTimer(...)
return newTimer(self, "cd", ...)
end
function bossModPrototype:NewCDCountTimer(...)
return newTimer(self, "cdcount", ...)
end
function bossModPrototype:NewCDSourceTimer(...)
return newTimer(self, "cdsource", ...)
end
function bossModPrototype:NewNextTimer(...)
return newTimer(self, "next", ...)
end
function bossModPrototype:NewNextCountTimer(...)
return newTimer(self, "nextcount", ...)
end
function bossModPrototype:NewNextSourceTimer(...)
return newTimer(self, "nextsource", ...)
end
function bossModPrototype:NewAchievementTimer(...)
return newTimer(self, "achievement", ...)
end
function bossModPrototype:NewCDSpecialTimer(...)
return newTimer(self, "cdspecial", ...)
end
function bossModPrototype:NewNextSpecialTimer(...)
return newTimer(self, "nextspecial", ...)
end
function bossModPrototype:NewPhaseTimer(...)
return newTimer(self, "stage", ...)
end
function bossModPrototype:NewRPTimer(...)
return newTimer(self, "roleplay", ...)
end
function bossModPrototype:NewAddsTimer(...)
return newTimer(self, "adds", ...)
end
function bossModPrototype:NewAddsCustomTimer(...)
return newTimer(self, "addscustom", ...)
end
function bossModPrototype:NewAITimer(...)
return newTimer(self, "ai", ...)
end
function bossModPrototype:GetLocalizedTimerText(timerType, spellId, Name)
local spellName
if Name then
spellName = Name--Pull from name stored in object
elseif spellId then
DBM:Debug("|cffff0000GetLocalizedTimerText fallback, this should not happen and is a bug. this fallback should be deleted if this message is never seen after async code is live|r")
if timerType == "achievement" then
spellName = select(2, GetAchievementInfo(spellId))
elseif type(spellId) == "string" and spellId:match("ej%d+") then
spellName = DBM:EJ_GetSectionInfo(string.sub(spellId, 3))
else
spellName = DBM:GetSpellInfo(spellId)
end
end
return pformat(DBM_CORE_AUTO_TIMER_TEXTS[timerType], spellName)
end
end
------------------------------
-- Berserk/Combat Objects --
------------------------------
do
local enragePrototype = {}
local mt = {__index = enragePrototype}
function enragePrototype:Start(timer)
timer = timer or self.timer or 600
timer = timer <= 0 and self.timer - timer or timer
self.bar:SetTimer(timer)
self.bar:Start()
if self.warning1 then
if timer > 660 then self.warning1:Schedule(timer - 600, 10, DBM_CORE_MIN) end
if timer > 300 then self.warning1:Schedule(timer - 300, 5, DBM_CORE_MIN) end
if timer > 180 then self.warning2:Schedule(timer - 180, 3, DBM_CORE_MIN) end
end
if self.warning2 then
if timer > 60 then self.warning2:Schedule(timer - 60, 1, DBM_CORE_MIN) end
if timer > 30 then self.warning2:Schedule(timer - 30, 30, DBM_CORE_SEC) end
if timer > 10 then self.warning2:Schedule(timer - 10, 10, DBM_CORE_SEC) end
end
if self.countdown then
if not DBM.Options.DontPlayPTCountdown then
self.countdown:Start(timer)
end
end
end
function enragePrototype:Schedule(t)
return self.owner:Schedule(t, self.Start, self)
end
function enragePrototype:Cancel()
self.owner:Unschedule(self.Start, self)
if self.warning1 then
self.warning1:Cancel()
end
if self.warning2 then
self.warning2:Cancel()
end
if self.countdown then
self.countdown:Cancel()
end
self.bar:Stop()
end
enragePrototype.Stop = enragePrototype.Cancel
function bossModPrototype:NewBerserkTimer(timer, text, barText, barIcon)
timer = timer or 600
local warning1 = self:NewAnnounce(text or DBM_CORE_GENERIC_WARNING_BERSERK, 1, nil, "warning_berserk", false)
local warning2 = self:NewAnnounce(text or DBM_CORE_GENERIC_WARNING_BERSERK, 4, nil, "warning_berserk", false)
local bar = self:NewTimer(timer, barText or DBM_CORE_GENERIC_TIMER_BERSERK, barIcon or 28131, nil, "timer_berserk")
local obj = setmetatable(
{
warning1 = warning1,
warning2 = warning2,
bar = bar,
timer = timer,
owner = self
},
mt
)
return obj
end
function bossModPrototype:NewCombatTimer(timer, text, barText, barIcon)
timer = timer or 10
local bar = self:NewTimer(timer, barText or DBM_CORE_GENERIC_TIMER_COMBAT, barIcon or "Interface\\Icons\\ability_warrior_offensivestance", nil, "timer_combat")
local countdown = self:NewCountdown(0, 0, nil, false, nil, true)
local obj = setmetatable(
{
bar = bar,
timer = timer,
countdown = countdown,
owner = self
},
mt
)
return obj
end
end
---------------
-- Options --
---------------
function bossModPrototype:AddBoolOption(name, default, cat, func, extraOption)
cat = cat or "misc"
self.DefaultOptions[name] = (default == nil) or default
if cat == "timer" then
self.DefaultOptions[name.."TColor"] = extraOption or 0
end
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options[name] = (default == nil) or default
if cat == "timer" then
self.Options[name.."TColor"] = extraOption or 0
end
self:SetOptionCategory(name, cat)
if func then
self.optionFuncs = self.optionFuncs or {}
self.optionFuncs[name] = func
end
end
function bossModPrototype:AddSpecialWarningOption(name, default, defaultSound, cat)
cat = cat or "misc"
self.DefaultOptions[name] = (default == nil) or default
self.DefaultOptions[name.."SWSound"] = defaultSound or 1
self.DefaultOptions[name.."SWNote"] = true
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options[name] = (default == nil) or default
self.Options[name.."SWSound"] = defaultSound or 1
self.Options[name.."SWNote"] = true
self:SetOptionCategory(name, cat)
end
function bossModPrototype:AddSetIconOption(name, spellId, default, isHostile)
self.DefaultOptions[name] = (default == nil) or default
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options[name] = (default == nil) or default
self:SetOptionCategory(name, "misc")
if isHostile then
if not self.findFastestComputer then
self.findFastestComputer = {}
end
self.findFastestComputer[#self.findFastestComputer + 1] = name
self.localization.options[name] = DBM_CORE_AUTO_ICONS_OPTION_TEXT2:format(spellId)
else
self.localization.options[name] = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(spellId)
end
end
function bossModPrototype:AddArrowOption(name, spellId, default, isRunTo)
if isRunTo == true then isRunTo = 2 end--Support legacy
self.DefaultOptions[name] = (default == nil) or default
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options[name] = (default == nil) or default
self:SetOptionCategory(name, "misc")
if isRunTo == 2 then
self.localization.options[name] = DBM_CORE_AUTO_ARROW_OPTION_TEXT:format(spellId)
elseif isRunTo == 3 then
self.localization.options[name] = DBM_CORE_AUTO_ARROW_OPTION_TEXT3:format(spellId)
else
self.localization.options[name] = DBM_CORE_AUTO_ARROW_OPTION_TEXT2:format(spellId)
end
end
function bossModPrototype:AddRangeFrameOption(range, spellId, default)
self.DefaultOptions["RangeFrame"] = (default == nil) or default
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options["RangeFrame"] = (default == nil) or default
self:SetOptionCategory("RangeFrame", "misc")
if spellId then
self.localization.options["RangeFrame"] = DBM_CORE_AUTO_RANGE_OPTION_TEXT:format(range, spellId)
else
self.localization.options["RangeFrame"] = DBM_CORE_AUTO_RANGE_OPTION_TEXT_SHORT:format(range)
end
end
function bossModPrototype:AddHudMapOption(name, spellId, default)
self.DefaultOptions[name] = (default == nil) or default
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options[name] = (default == nil) or default
self:SetOptionCategory(name, "misc")
if spellId then
self.localization.options[name] = DBM_CORE_AUTO_HUD_OPTION_TEXT:format(spellId)
else
self.localization.options[name] = DBM_CORE_AUTO_HUD_OPTION_TEXT_MULTI
end
end
function bossModPrototype:AddNamePlateOption(name, spellId, default)
if not spellId then
error("AddNamePlateOption must provide valid spellId", 2)
end
self.DefaultOptions[name] = (default == nil) or default
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options[name] = (default == nil) or default
self:SetOptionCategory(name, "misc")
self.localization.options[name] = DBM_CORE_AUTO_NAMEPLATE_OPTION_TEXT:format(spellId)
end
function bossModPrototype:AddInfoFrameOption(spellId, default)
self.DefaultOptions["InfoFrame"] = (default == nil) or default
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options["InfoFrame"] = (default == nil) or default
self:SetOptionCategory("InfoFrame", "misc")
if spellId then
self.localization.options["InfoFrame"] = DBM_CORE_AUTO_INFO_FRAME_OPTION_TEXT:format(spellId)
else
self.localization.options["InfoFrame"] = DBM_CORE_AUTO_INFO_FRAME_OPTION_TEXT2
end
end
function bossModPrototype:AddReadyCheckOption(questId, default)
self.readyCheckQuestId = questId
self.DefaultOptions["ReadyCheck"] = (default == nil) or default
if default and type(default) == "string" then
default = self:GetRoleFlagValue(default)
end
self.Options["ReadyCheck"] = (default == nil) or default
self.localization.options["ReadyCheck"] = DBM_CORE_AUTO_READY_CHECK_OPTION_TEXT
self:SetOptionCategory("ReadyCheck", "misc")
end
function bossModPrototype:AddSliderOption(name, minValue, maxValue, valueStep, default, cat, func)
cat = cat or "misc"
self.DefaultOptions[name] = {type = "slider", value = default or 0}
self.Options[name] = default or 0
self:SetOptionCategory(name, cat)
self.sliders = self.sliders or {}
self.sliders[name] = {
minValue = minValue,
maxValue = maxValue,
valueStep = valueStep,
}
if func then
self.optionFuncs = self.optionFuncs or {}
self.optionFuncs[name] = func
end
end
function bossModPrototype:AddButton(name, onClick, cat, func)
cat = cat or "misc"
self:SetOptionCategory(name, cat)
self.buttons = self.buttons or {}
self.buttons[name] = onClick
if func then
self.optionFuncs = self.optionFuncs or {}
self.optionFuncs[name] = func
end
end
-- FIXME: this function does not reset any settings to default if you remove an option in a later revision and a user has selected this option in an earlier revision were it still was available
-- this will be fixed as soon as it is necessary due to removed options ;-)
function bossModPrototype:AddDropdownOption(name, options, default, cat, func)
cat = cat or "misc"
self.DefaultOptions[name] = {type = "dropdown", value = default}
self.Options[name] = default
self:SetOptionCategory(name, cat)
self.dropdowns = self.dropdowns or {}
self.dropdowns[name] = options
if func then
self.optionFuncs = self.optionFuncs or {}
self.optionFuncs[name] = func
end
end
function bossModPrototype:AddOptionSpacer(cat)
cat = cat or "misc"
if self.optionCategories[cat] then
tinsert(self.optionCategories[cat], DBM_OPTION_SPACER)
end
end
function bossModPrototype:AddOptionLine(text, cat)
cat = cat or "misc"
if not self.optionCategories[cat] then
self.optionCategories[cat] = {}
end
if self.optionCategories[cat] then
tinsert(self.optionCategories[cat], {line = true, text = text})
end
end
function bossModPrototype:AddAnnounceSpacer()
return self:AddOptionSpacer("announce")
end
function bossModPrototype:AddTimerSpacer()
return self:AddOptionSpacer("timer")
end
function bossModPrototype:AddAnnounceLine(text)
return self:AddOptionLine(text, "announce")
end
function bossModPrototype:AddTimerLine(text)
return self:AddOptionLine(text, "timer")
end
function bossModPrototype:AddMiscLine(text)
return self:AddOptionLine(text, "misc")
end
function bossModPrototype:RemoveOption(name)
self.Options[name] = nil
for i, options in pairs(self.optionCategories) do
removeEntry(options, name)
if #options == 0 then
self.optionCategories[i] = nil
end
end
if self.optionFuncs then
self.optionFuncs[name] = nil
end
end
function bossModPrototype:SetOptionCategory(name, cat)
for _, options in pairs(self.optionCategories) do
removeEntry(options, name)
end
if not self.optionCategories[cat] then
self.optionCategories[cat] = {}
end
tinsert(self.optionCategories[cat], name)
end
--------------
-- Combat --
--------------
function bossModPrototype:RegisterCombat(cType, ...)
if cType then
cType = cType:lower()
end
local info = {
type = cType,
mob = self.creatureId,
eId = self.encounterId,
name = self.localization.general.name or self.id,
msgs = (cType ~= "combat") and {...},
mod = self
}
if self.multiMobPullDetection then
info.multiMobPullDetection = self.multiMobPullDetection
end
if self.multiEncounterPullDetection then
info.multiEncounterPullDetection = self.multiEncounterPullDetection
end
if self.noESDetection then
info.noESDetection = self.noESDetection
end
if self.noEEDetection then
info.noEEDetection = self.noEEDetection
end
if self.noRegenDetection then
info.noRegenDetection = self.noRegenDetection
end
if self.noWBEsync then
info.noWBEsync = self.noWBEsync
end
-- use pull-mobs as kill mobs by default, can be overriden by RegisterKill
if self.multiMobPullDetection then
for i, v in ipairs(self.multiMobPullDetection) do
info.killMobs = info.killMobs or {}
info.killMobs[v] = true
end
end
self.combatInfo = info
if not self.zones then return end
for v in pairs(self.zones) do
combatInfo[v] = combatInfo[v] or {}
tinsert(combatInfo[v], info)
end
end
-- needs to be called _AFTER_ RegisterCombat
function bossModPrototype:RegisterKill(msgType, ...)
if not self.combatInfo then
error("mod.combatInfo not yet initialized, use mod:RegisterCombat before using this method", 2)
end
if msgType == "kill" then
if select("#", ...) > 0 then -- calling this method with 0 IDs means "use the values from SetCreatureID", this is already done by RegisterCombat as calling RegisterKill should be optional --> mod:RegisterKill("kill") with no IDs is never necessary
self.combatInfo.killMobs = {}
for i = 1, select("#", ...) do
local v = select(i, ...)
if type(v) == "number" then
self.combatInfo.killMobs[v] = true
end
end
end
else
self.combatInfo.killType = msgType
self.combatInfo.killMsgs = {}
for i = 1, select("#", ...) do
local v = select(i, ...)
self.combatInfo.killMsgs[v] = true
end
end
end
function bossModPrototype:SetDetectCombatInVehicle(flag)
if not self.combatInfo then
error("mod.combatInfo not yet initialized, use mod:RegisterCombat before using this method", 2)
end
self.combatInfo.noCombatInVehicle = not flag
end
function bossModPrototype:SetCreatureID(...)
self.creatureId = ...
if select("#", ...) > 1 then
self.multiMobPullDetection = {...}
if self.combatInfo then
self.combatInfo.multiMobPullDetection = self.multiMobPullDetection
if self.inCombat then
--Called mid combat, fix some variables
self.numBoss = #self.multiMobPullDetection
self.vb.bossLeft = self.numBoss
end
end
for i = 1, select("#", ...) do
local cId = select(i, ...)
bossIds[cId] = true
end
else
local cId = ...
bossIds[cId] = true
end
end
function bossModPrototype:SetEncounterID(...)
self.encounterId = ...
if select("#", ...) > 1 then
self.multiEncounterPullDetection = {...}
if self.combatInfo then
self.combatInfo.multiEncounterPullDetection = self.multiEncounterPullDetection
end
end
end
function bossModPrototype:DisableESCombatDetection()
self.noESDetection = true
if self.combatInfo then
self.combatInfo.noESDetection = true
end
end
function bossModPrototype:DisableEEKillDetection()
self.noEEDetection = true
if self.combatInfo then
self.combatInfo.noEEDetection = true
end
end
function bossModPrototype:DisableRegenDetection()
self.noRegenDetection = true
if self.combatInfo then
self.combatInfo.noRegenDetection = true
end
end
function bossModPrototype:DisableWBEngageSync()
self.noWBEsync = true
if self.combatInfo then
self.combatInfo.noWBEsync = true
end
end
function bossModPrototype:IsInCombat()
return self.inCombat
end
function bossModPrototype:IsAlive()
return not UnitIsDeadOrGhost("player")
end
function bossModPrototype:SetMinCombatTime(t)
self.minCombatTime = t
end
-- needs to be called after RegisterCombat
function bossModPrototype:SetWipeTime(t)
if not self.combatInfo then
error("mod.combatInfo not yet initialized, use mod:RegisterCombat before using this method", 2)
end
self.combatInfo.wipeTimer = t
end
-- fix for LFR ToES Tsulong combat detection bug after killed.
function bossModPrototype:SetReCombatTime(t, t2)--T1, after kill. T2 after wipe
self.reCombatTime = t
self.reCombatTime2 = t2
end
function bossModPrototype:SetOOCBWComms()
tinsert(oocBWComms, self)
end
-----------------------
-- Synchronization --
-----------------------
function bossModPrototype:SendSync(event, ...)
event = event or ""
local arg = select("#", ...) > 0 and strjoin("\t", tostringall(...)) or ""
local str = ("%s\t%s\t%s\t%s"):format(self.id, self.revision or 0, event, arg)
local spamId = self.id .. event .. arg -- *not* the same as the sync string, as it doesn't use the revision information
local time = GetTime()
--Mod syncs are more strict and enforce latency threshold always.
--Do not put latency check in main sendSync local function (line 313) though as we still want to get version information, etc from these users.
if not modSyncSpam[spamId] or (time - modSyncSpam[spamId]) > 8 then
self:ReceiveSync(event, nil, self.revision or 0, tostringall(...))
sendSync("M", str)
end
end
function bossModPrototype:SendBigWigsSync(msg, extra)
msg = "B^".. msg
if extra then
msg = msg .."^".. extra
end
if IsInGroup() then
SendAddonMessage("BigWigs", msg, IsInGroup(2) and "INSTANCE_CHAT" or "RAID")
end
end
function bossModPrototype:ReceiveSync(event, sender, revision, ...)
local spamId = self.id .. event .. strjoin("\t", ...)
local time = GetTime()
if (not modSyncSpam[spamId] or (time - modSyncSpam[spamId]) > self.SyncThreshold) and self.OnSync and (not (self.blockSyncs and sender)) and (not sender or (not self.minSyncRevision or revision >= self.minSyncRevision)) then
modSyncSpam[spamId] = time
-- we have to use the sender as last argument for compatibility reasons (stupid old API...)
-- avoid table allocations for frequently used number of arguments
if select("#", ...) <= 1 then
-- syncs with no arguments have an empty argument (also for compatibility reasons)
self:OnSync(event, ... or "", sender)
elseif select("#", ...) == 2 then
self:OnSync(event, ..., select(2, ...), sender)
else
local tmp = { ... }
tmp[#tmp + 1] = sender
self:OnSync(event, unpack(tmp))
end
end
end
function bossModPrototype:SetRevision(revision)
revision = tonumber(revision or "")
if not revision then
-- bad revision: either forgot the svn keyword or using git svn
revision = DBM.Revision
end
self.revision = revision
end
function bossModPrototype:SetMinSyncRevision(revision)
self.minSyncRevision = revision
end
function bossModPrototype:SetHotfixNoticeRev(revision)
self.hotfixNoticeRev = revision
end
-----------------
-- Scheduler --
-----------------
function bossModPrototype:Schedule(t, f, ...)
return schedule(t, f, self, ...)
end
function bossModPrototype:Unschedule(f, ...)
return unschedule(f, self, ...)
end
function bossModPrototype:ScheduleMethod(t, method, ...)
if not self[method] then
error(("Method %s does not exist"):format(tostring(method)), 2)
end
return self:Schedule(t, self[method], self, ...)
end
bossModPrototype.ScheduleEvent = bossModPrototype.ScheduleMethod
function bossModPrototype:UnscheduleMethod(method, ...)
if not self[method] then
error(("Method %s does not exist"):format(tostring(method)), 2)
end
return self:Unschedule(self[method], self, ...)
end
bossModPrototype.UnscheduleEvent = bossModPrototype.UnscheduleMethod
-------------
-- Icons --
-------------
do
local scanExpires = {}
local addsIcon = {}
local addsIconSet = {}
function bossModPrototype:SetIcon(target, icon, timer)
if not target then return end--Fix a rare bug where target becomes nil at last second (end combat fires and clears targets)
if DBM.Options.DontSetIcons or not enableIcons or DBM:GetRaidRank(playerName) == 0 then
return
end
self:UnscheduleMethod("SetIcon", target)
if type(icon) ~= "number" or type(target) ~= "string" then--icon/target probably backwards.
DBM:Debug("|cffff0000SetIcon is being used impropperly. Check icon/target order|r")
return--Fail silently instead of spamming icon lua errors if we screw up
end
icon = icon and icon >= 0 and icon <= 8 and icon or 8
local uId = DBM:GetRaidUnitId(target)
if uId and UnitIsUnit(uId, "player") and DBM:GetNumRealGroupMembers() < 2 then return end--Solo raid, no reason to put icon on yourself.
if uId or UnitExists(target) then--target accepts uid, unitname both.
uId = uId or target
--save previous icon into a table.
local oldIcon = self:GetIcon(uId) or 0
if not self.iconRestore[uId] then
self.iconRestore[uId] = oldIcon
end
--set icon
if oldIcon ~= icon then--Don't set icon if it's already set to what we're setting it to
SetRaidTarget(uId, self.iconRestore[uId] and icon == 0 and self.iconRestore[uId] or icon)
end
--schedule restoring old icon if timer enabled.
if timer then
self:ScheduleMethod(timer, "SetIcon", target, 0)
end
end
end
do
local iconSortTable = {}
local iconSet = 0
local function sort_by_group(v1, v2)
return DBM:GetRaidSubgroup(DBM:GetUnitFullName(v1)) < DBM:GetRaidSubgroup(DBM:GetUnitFullName(v2))
end
local function clearSortTable()
twipe(iconSortTable)
iconSet = 0
end
function bossModPrototype:SetIconByAlphaTable(returnFunc)
tsort(iconSortTable)--Sorted alphabetically
for i = 1, #iconSortTable do
local target = iconSortTable[i]
if i > 8 then
DBM:Debug("|cffff0000Too many players to set icons, reconsider where using icons|r", 2)
return
end
if not self.iconRestore[target] then
local oldIcon = self:GetIcon(target) or 0
self.iconRestore[target] = oldIcon
end
SetRaidTarget(target, i)--Icons match number in table in alpha sort
if returnFunc then
self[returnFunc](self, target, i)--Send icon and target to returnFunc. (Generally used by announce icon targets to raid chat feature)
end
end
C_TimerAfter(1.5, clearSortTable)--Table wipe delay so if icons go out too early do to low fps or bad latency, when they get new target on table, resort and reapplying should auto correct teh icon within .2-.4 seconds at most.
end
function bossModPrototype:SetAlphaIcon(delay, target, maxIcon, returnFunc)
if not target then return end
if DBM.Options.DontSetIcons or not enableIcons or DBM:GetRaidRank(playerName) == 0 then
return
end
local uId = DBM:GetRaidUnitId(target)
if uId or UnitExists(target) then--target accepts uid, unitname both.
uId = uId or target
local foundDuplicate = false
for i = #iconSortTable, 1, -1 do
if iconSortTable[i] == uId then
foundDuplicate = true
break
end
end
if not foundDuplicate then
iconSet = iconSet + 1
tinsert(iconSortTable, uId)
end
self:UnscheduleMethod("SetIconByAlphaTable")
if maxIcon and iconSet == maxIcon then
self:SetIconByAlphaTable(returnFunc)
elseif self:LatencyCheck() then--lag can fail the icons so we check it before allowing.
self:ScheduleMethod(delay or 0.5, "SetIconByAlphaTable", returnFunc)
end
end
end
function bossModPrototype:SetIconBySortedTable(startIcon, reverseIcon, returnFunc)
tsort(iconSortTable, sort_by_group)
local icon = startIcon or 1
for i, v in ipairs(iconSortTable) do
if not self.iconRestore[v] then
local oldIcon = self:GetIcon(v) or 0
self.iconRestore[v] = oldIcon
end
SetRaidTarget(v, icon)--do not use SetIcon function again. It already checked in SetSortedIcon function.
if reverseIcon then
icon = icon - 1
else
icon = icon + 1
end
if returnFunc then
self[returnFunc](self, v, icon)--Send icon and target to returnFunc. (Generally used by announce icon targets to raid chat feature)
end
end
C_TimerAfter(1.5, clearSortTable)--Table wipe delay so if icons go out too early do to low fps or bad latency, when they get new target on table, resort and reapplying should auto correct teh icon within .2-.4 seconds at most.
end
function bossModPrototype:SetSortedIcon(delay, target, startIcon, maxIcon, reverseIcon, returnFunc)
if not target then return end
if DBM.Options.DontSetIcons or not enableIcons or DBM:GetRaidRank(playerName) == 0 then
return
end
if not startIcon then startIcon = 1 end
startIcon = startIcon and startIcon >= 0 and startIcon <= 8 and startIcon or 8
local uId = DBM:GetRaidUnitId(target)
if uId or UnitExists(target) then--target accepts uid, unitname both.
uId = uId or target
local foundDuplicate = false
for i = #iconSortTable, 1, -1 do
if iconSortTable[i] == uId then
foundDuplicate = true
break
end
end
if not foundDuplicate then
iconSet = iconSet + 1
tinsert(iconSortTable, uId)
end
self:UnscheduleMethod("SetIconBySortedTable")
if maxIcon and iconSet == maxIcon then
self:SetIconBySortedTable(startIcon, reverseIcon, returnFunc)
elseif self:LatencyCheck() then--lag can fail the icons so we check it before allowing.
self:ScheduleMethod(delay or 0.5, "SetIconBySortedTable", startIcon, reverseIcon, returnFunc)
end
end
end
end
function bossModPrototype:GetIcon(uId)
return UnitExists(uId) and GetRaidTargetIndex(uId)
end
function bossModPrototype:RemoveIcon(target)
return self:SetIcon(target, 0)
end
function bossModPrototype:ClearIcons()
if IsInRaid() then
for i = 1, GetNumGroupMembers() do
if UnitExists("raid"..i) and GetRaidTargetIndex("raid"..i) then
SetRaidTarget("raid"..i, 0)
end
end
else
for i = 1, GetNumSubgroupMembers() do
if UnitExists("party"..i) and GetRaidTargetIndex("party"..i) then
SetRaidTarget("party"..i, 0)
end
end
end
end
function bossModPrototype:CanSetIcon(optionName)
if canSetIcons[optionName] then
return true
end
return false
end
local mobUids = {"mouseover", "target", "boss1", "boss2", "boss3", "boss4", "boss5"}
function bossModPrototype:ScanForMobs(creatureID, iconSetMethod, mobIcon, maxIcon, scanInterval, scanningTime, optionName, isFriendly, secondCreatureID, skipMarked)
if not optionName then optionName = self.findFastestComputer[1] end
if canSetIcons[optionName] then
--Declare variables.
local timeNow = GetTime()
local creatureID = creatureID--This function must not be used to boss, so remove self.creatureId. Accepts cid, guid and cid table
local iconSetMethod = iconSetMethod or 0--Set IconSetMethod -- 0: Descending / 1:Ascending / 2: Force Set / 9:Force Stop
--With different scanID, this function can support multi scanning same time. Required for Nazgrim.
local scanID = 0
if type(creatureID) == "number" then
scanID = creatureID --guid and table no not supports multi scanning. only cid supports multi scanning
end
if iconSetMethod == 9 then--Force stop scanning
--clear variables
scanExpires[scanID] = nil
addsIcon[scanID] = nil
addsIconSet[scanID] = nil
return
end
if not addsIcon[scanID] then addsIcon[scanID] = mobIcon or 8 end
if not addsIconSet[scanID] then addsIconSet[scanID] = 0 end
if not scanExpires[scanID] then scanExpires[scanID] = timeNow + scanningTime end
local maxIcon = maxIcon or 8 --We only have 8 icons.
local isFriendly = isFriendly or false
local secondCreatureID = secondCreatureID or 0
local scanInterval = scanInterval or 0.2
local scanningTime = scanningTime or 8
--DO SCAN NOW
for _, unitid2 in ipairs(mobUids) do
local guid2 = UnitGUID(unitid2)
local cid2 = self:GetCIDFromGUID(guid2)
local isEnemy = UnitIsEnemy("player", unitid2) or true--If api returns nil, assume it's an enemy
local isFiltered = false
if (not isFriendly and not isEnemy) or (skipMarked and not GetRaidTargetIndex(unitid2)) then
isFiltered = true
DBM:Debug("ScanForMobs aborting because filtered mob", 2)
end
if not isFiltered then
if guid2 and type(creatureID) == "table" and creatureID[cid2] and not addsGUIDs[guid2] then
DBM:Debug("Match found, SHOULD be setting icon", 2)
if type(creatureID[cid2]) == "number" then
SetRaidTarget(unitid2, creatureID[cid2])
else
SetRaidTarget(unitid2, addsIcon[scanID])
if iconSetMethod == 1 then
addsIcon[scanID] = addsIcon[scanID] + 1
else
addsIcon[scanID] = addsIcon[scanID] - 1
end
end
addsGUIDs[guid2] = true
addsIconSet[scanID] = addsIconSet[scanID] + 1
if addsIconSet[scanID] >= maxIcon then--stop scan immediately to save cpu
--clear variables
scanExpires[scanID] = nil
addsIcon[scanID] = nil
addsIconSet[scanID] = nil
return
end
elseif guid2 and (guid2 == creatureID or cid2 == creatureID or cid2 == secondCreatureID) and not addsGUIDs[guid2] then
DBM:Debug("Match found, SHOULD be setting icon", 2)
if iconSetMethod == 2 then
SetRaidTarget(unitid2, mobIcon)
else
SetRaidTarget(unitid2, addsIcon[scanID])
if iconSetMethod == 1 then
addsIcon[scanID] = addsIcon[scanID] + 1
else
addsIcon[scanID] = addsIcon[scanID] - 1
end
end
addsGUIDs[guid2] = true
addsIconSet[scanID] = addsIconSet[scanID] + 1
if addsIconSet[scanID] >= maxIcon then--stop scan immediately to save cpu
--clear variables
scanExpires[scanID] = nil
addsIcon[scanID] = nil
addsIconSet[scanID] = nil
return
end
end
end
end
for uId in DBM:GetGroupMembers() do
local unitid = uId.."target"
local guid = UnitGUID(unitid)
local cid = self:GetCIDFromGUID(guid)
local isEnemy = UnitIsEnemy("player", unitid) or true--If api returns nil, assume it's an enemy
local isFiltered = false
if (not isFriendly and not isEnemy) or (skipMarked and not GetRaidTargetIndex(unitid)) then
isFiltered = true
DBM:Debug("ScanForMobs aborting because filtered mob", 2)
end
if not isFiltered then
if guid and type(creatureID) == "table" and creatureID[cid] and not addsGUIDs[guid] then
DBM:Debug("Match found, SHOULD be setting icon", 2)
if type(creatureID[cid]) == "number" then
SetRaidTarget(unitid, creatureID[cid])
else
SetRaidTarget(unitid, addsIcon[scanID])
if iconSetMethod == 1 then
addsIcon[scanID] = addsIcon[scanID] + 1
else
addsIcon[scanID] = addsIcon[scanID] - 1
end
end
addsGUIDs[guid] = true
addsIconSet[scanID] = addsIconSet[scanID] + 1
if addsIconSet[scanID] >= maxIcon then--stop scan immediately to save cpu
--clear variables
scanExpires[scanID] = nil
addsIcon[scanID] = nil
addsIconSet[scanID] = nil
return
end
elseif guid and (guid == creatureID or cid == creatureID or cid == secondCreatureID) and not addsGUIDs[guid] then
DBM:Debug("Match found, SHOULD be setting icon", 2)
if iconSetMethod == 2 then
SetRaidTarget(unitid, mobIcon)
else
SetRaidTarget(unitid, addsIcon[scanID])
if iconSetMethod == 1 then
addsIcon[scanID] = addsIcon[scanID] + 1
else
addsIcon[scanID] = addsIcon[scanID] - 1
end
end
addsGUIDs[guid] = true
addsIconSet[scanID] = addsIconSet[scanID] + 1
if addsIconSet[scanID] >= maxIcon then--stop scan immediately to save cpu
--clear variables
scanExpires[scanID] = nil
addsIcon[scanID] = nil
addsIconSet[scanID] = nil
return
end
end
end
end
if timeNow < scanExpires[scanID] then--scan for limited times.
self:ScheduleMethod(scanInterval, "ScanForMobs", creatureID, iconSetMethod, mobIcon, maxIcon, scanInterval, scanningTime, optionName, isFriendly, secondCreatureID)
else
DBM:Debug("Stopping ScanForMobs for: "..(optionName or "nil"), 2)
--clear variables
scanExpires[scanID] = nil
addsIcon[scanID] = nil
addsIconSet[scanID] = nil
--Do not wipe adds GUID table here, it's wiped by :Stop() which is called by EndCombat
end
else
DBM:Debug("Not elected to set icons for "..(optionName or "nil"), 2)
end
end
end
-----------------------
-- Model Functions --
-----------------------
function bossModPrototype:SetModelScale(scale)
self.modelScale = scale
end
function bossModPrototype:SetModelOffset(x, y, z)
self.modelOffsetX = x
self.modelOffsetY = y
self.modelOffsetZ = z
end
function bossModPrototype:SetModelRotation(r)
self.modelRotation = r
end
function bossModPrototype:SetModelMoveSpeed(v)
self.modelMoveSpeed = v
end
function bossModPrototype:SetModelID(id)
self.modelId = id
end
function bossModPrototype:SetModelSound(long, short)--PlaySoundFile prototype for model viewer, long is long sound, short is a short clip, configurable in UI, both sound paths defined in boss mods.
self.modelSoundLong = long
self.modelSoundShort = short
end
function bossModPrototype:EnableModel()
self.modelEnabled = true
end
function bossModPrototype:DisableModel()
self.modelEnabled = nil
end
--------------------
-- Localization --
--------------------
function bossModPrototype:GetLocalizedStrings()
self.localization.miscStrings.name = self.localization.general.name
return self.localization.miscStrings
end
-- Not really good, needs a few updates
do
local modLocalizations = {}
local modLocalizationPrototype = {}
local mt = {__index = modLocalizationPrototype}
local returnKey = {__index = function(t, k) return k end}
local defaultCatLocalization = {
__index = setmetatable({
timer = DBM_CORE_OPTION_CATEGORY_TIMERS,
announce = DBM_CORE_OPTION_CATEGORY_WARNINGS,
announceother = DBM_CORE_OPTION_CATEGORY_WARNINGS_OTHER,
announcepersonal = DBM_CORE_OPTION_CATEGORY_WARNINGS_YOU,
announcerole = DBM_CORE_OPTION_CATEGORY_WARNINGS_ROLE,
sound = DBM_CORE_OPTION_CATEGORY_SOUNDS,
misc = MISCELLANEOUS
}, returnKey)
}
local defaultTimerLocalization = {
__index = setmetatable({
timer_berserk = DBM_CORE_GENERIC_TIMER_BERSERK,
timer_combat = DBM_CORE_GENERIC_TIMER_COMBAT
}, returnKey)
}
local defaultAnnounceLocalization = {
__index = setmetatable({
warning_berserk = DBM_CORE_GENERIC_WARNING_BERSERK
}, returnKey)
}
local defaultOptionLocalization = {
__index = setmetatable({
timer_berserk = DBM_CORE_OPTION_TIMER_BERSERK,
timer_combat = DBM_CORE_OPTION_TIMER_COMBAT,
}, returnKey)
}
local defaultMiscLocalization = {
__index = {}
}
function modLocalizationPrototype:SetGeneralLocalization(t)
for i, v in pairs(t) do
self.general[i] = v
end
end
function modLocalizationPrototype:SetWarningLocalization(t)
for i, v in pairs(t) do
self.warnings[i] = v
end
end
function modLocalizationPrototype:SetTimerLocalization(t)
for i, v in pairs(t) do
self.timers[i] = v
end
end
function modLocalizationPrototype:SetOptionLocalization(t)
for i, v in pairs(t) do
self.options[i] = v
end
end
function modLocalizationPrototype:SetOptionCatLocalization(t)
for i, v in pairs(t) do
self.cats[i] = v
end
end
function modLocalizationPrototype:SetMiscLocalization(t)
for i, v in pairs(t) do
self.miscStrings[i] = v
end
end
function DBM:CreateModLocalization(name)
name = tostring(name)
local obj = {
general = setmetatable({}, returnKey),
warnings = setmetatable({}, defaultAnnounceLocalization),
options = setmetatable({}, defaultOptionLocalization),
timers = setmetatable({}, defaultTimerLocalization),
miscStrings = setmetatable({}, defaultMiscLocalization),
cats = setmetatable({}, defaultCatLocalization),
}
setmetatable(obj, mt)
modLocalizations[name] = obj
return obj
end
function DBM:GetModLocalization(name)
name = tostring(name)
return modLocalizations[name] or self:CreateModLocalization(name)
end
end
| mit |
Telewild/telewild | plugins/wiki.lua | 20 | 4376 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^[!/][Ww]iki(%w+) (search) (.+)$",
"^[!/][Ww]iki (search) ?(.*)$",
"^[!/][Ww]iki(%w+) (.+)$",
"^[!/][Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
masoudre11/RaHabot | plugins/moderation.lua | 5 | 7280 | -- Moderation for Liberbot groups.
-- The bot must be made an admin.
-- Put this near the top, after blacklist.
-- If you want to enable antisquig, put that at the top, before blacklist.
local triggers = {
'^/modhelp[@'..bot.username..']*$',
'^/modlist[@'..bot.username..']*$',
'^/modcast[@'..bot.username..']*',
'^/modadd[@'..bot.username..']*$',
'^/modrem[@'..bot.username..']*$',
'^/modprom[@'..bot.username..']*$',
'^/moddem[@'..bot.username..']*',
'^/modkick[@'..bot.username..']*',
'^/modban[@'..bot.username..']*',
}
local commands = {
['^/modhelp[@'..bot.username..']*$'] = function(msg)
local moddat = load_data('moderation.json')
if not moddat[msg.chat.id_str] then
return config.errors.moderation
end
local message = [[
/modlist - List the moderators and administrators of this group.
Moderator commands:
/modkick - Kick a user from this group.
/modban - Ban a user from this group.
Administrator commands:
/add - Add this group to the moderation system.
/remove - Remove this group from the moderation system.
/promote - Promote a user to a moderator.
/demote - Demote a moderator to a user.
/modcast - Send a broadcast to every moderated group.
]]
return message
end,
['^/modlist[@'..bot.username..']*$'] = function(msg)
local moddat = load_data('moderation.json')
if not moddat[msg.chat.id_str] then
return config.errors.moderation
end
local message = ''
for k,v in pairs(moddat[msg.chat.id_str]) do
message = message .. ' - ' .. v .. ' (' .. k .. ')\n'
end
if message ~= '' then
message = 'Moderators for ' .. msg.chat.title .. ':\n' .. message .. '\n'
end
message = message .. 'Administrators for ' .. config.moderation.realm_name .. ':\n'
for k,v in pairs(config.moderation.admins) do
message = message .. ' - ' .. v .. ' (' .. k .. ')\n'
end
return message
end,
['^/modcast[@'..bot.username..']*'] = function(msg)
local message = msg.text:input()
if not message then
return 'You must include a message.'
end
if msg.chat.id ~= config.moderation.admin_group then
return 'This command must be run in the administration group.'
end
if not config.moderation.admins[msg.from.id_str] then
return config.errors.not_admin
end
local moddat = load_data('moderation.json')
for k,v in pairs(moddat) do
sendMessage(k, message)
end
return 'Your broadcast has been sent.'
end,
['^/modadd[@'..bot.username..']*$'] = function(msg)
if not config.moderation.admins[msg.from.id_str] then
return config.errors.not_admin
end
local moddat = load_data('moderation.json')
if moddat[msg.chat.id_str] then
return 'I am already moderating this group.'
end
moddat[msg.chat.id_str] = {}
save_data('moderation.json', moddat)
return 'I am now moderating this group.'
end,
['^/modrem[@'..bot.username..']*$'] = function(msg)
if not config.moderation.admins[msg.from.id_str] then
return config.errors.not_admin
end
local moddat = load_data('moderation.json')
if not moddat[msg.chat.id_str] then
return config.errors.moderation
end
moddat[msg.chat.id_str] = nil
save_data('moderation.json', moddat)
return 'I am no longer moderating this group.'
end,
['^/modprom[@'..bot.username..']*$'] = function(msg)
local moddat = load_data('moderation.json')
if not moddat[msg.chat.id_str] then
return config.errors.moderation
end
if not config.moderation.admins[msg.from.id_str] then
return config.errors.not_admin
end
if not msg.reply_to_message then
return 'Promotions must be done via reply.'
end
local modid = tostring(msg.reply_to_message.from.id)
local modname = msg.reply_to_message.from.first_name
if config.moderation.admins[modid] then
return modname .. ' is already an administrator.'
end
if moddat[msg.chat.id_str][modid] then
return modname .. ' is already a moderator.'
end
moddat[msg.chat.id_str][modid] = modname
save_data('moderation.json', moddat)
return modname .. ' is now a moderator.'
end,
['^/moddem[@'..bot.username..']*'] = function(msg)
local moddat = load_data('moderation.json')
if not moddat[msg.chat.id_str] then
return config.errors.moderation
end
if not config.moderation.admins[msg.from.id_str] then
return config.errors.not_admin
end
local modid = msg.text:input()
if not modid then
if msg.reply_to_message then
modid = tostring(msg.reply_to_message.from.id)
else
return 'Demotions must be done via reply or specification of a moderator\'s ID.'
end
end
if config.moderation.admins[modid] then
return config.moderation.admins[modid] .. ' is an administrator.'
end
if not moddat[msg.chat.id_str][modid] then
return 'User is not a moderator.'
end
local modname = moddat[msg.chat.id_str][modid]
moddat[msg.chat.id_str][modid] = nil
save_data('moderation.json', moddat)
return modname .. ' is no longer a moderator.'
end,
['/modkick[@'..bot.username..']*'] = function(msg)
local moddat = load_data('moderation.json')
if not moddat[msg.chat.id_str] then
return config.errors.moderation
end
if not moddat[msg.chat.id_str][msg.from.id_str] then
if not config.moderation.admins[msg.from.id_str] then
return config.errors.not_mod
end
end
local userid = msg.text:input()
local usernm = userid
if msg.reply_to_message then
userid = tostring(msg.reply_to_message.from.id)
usernm = msg.reply_to_message.from.first_name
end
if not userid then
return 'Kicks must be done via reply or specification of a user/bot\'s ID or username.'
end
if moddat[msg.chat.id_str][userid] or config.moderation.admins[userid] then
return 'You cannot kick a moderator.'
end
sendMessage(config.moderation.admin_group, '/kick ' .. userid .. ' from ' .. math.abs(msg.chat.id))
sendMessage(config.moderation.admin_group, usernm .. ' kicked from ' .. msg.chat.title .. ' by ' .. msg.from.first_name .. '.')
end,
['^/modban[@'..bot.username..']*'] = function(msg)
local moddat = load_data('moderation.json')
if not moddat[msg.chat.id_str] then
return config.errors.moderation
end
if not moddat[msg.chat.id_str][msg.from.id_str] then
if not config.moderation.admins[msg.from.id_str] then
return config.errors.not_mod
end
end
local userid = msg.text:input()
local usernm = userid
if msg.reply_to_message then
userid = tostring(msg.reply_to_message.from.id)
usernm = msg.reply_to_message.from.first_name
end
if not userid then
return 'Kicks must be done via reply or specification of a user/bot\'s ID or username.'
end
if moddat[msg.chat.id_str][userid] or config.moderation.admins[userid] then
return 'You cannot ban a moderator.'
end
sendMessage(config.moderation.admin_group, '/ban ' .. userid .. ' from ' .. math.abs(msg.chat.id))
sendMessage(config.moderation.admin_group, usernm .. ' banned from ' .. msg.chat.title .. ' by ' .. msg.from.first_name .. '.')
end
}
local action = function(msg)
for k,v in pairs(commands) do
if string.match(msg.text_lower, k) then
local output = v(msg)
if output then
sendReply(msg, output)
end
return
end
end
end
return {
action = action,
triggers = triggers
}
| gpl-2.0 |
dromozoa/dromozoa-commons | test/test_xml.lua | 3 | 1078 | -- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com>
--
-- This file is part of dromozoa-commons.
--
-- dromozoa-commons 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 3 of the License, or
-- (at your option) any later version.
--
-- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>.
local xml = require "dromozoa.commons.xml"
local a, b = xml.escape("<>&\"'")
assert(a == "<>&"'")
assert(b == nil)
assert(xml.escape(42) == "42")
assert(xml.escape("[foo]", "%W") == "[foo]")
assert(xml.escape("\t\r\n ") == "\t\r\n ")
assert(xml.escape("\0\127") == "�")
| gpl-3.0 |
bb010g/otouto | otouto/plugins/urbandictionary.lua | 1 | 1954 | --[[
urbandictionary.lua
Returns the top Urban Dictionary entry for a given query.
Copyright 2016 topkecleon <drew@otou.to>
This code is licensed under the GNU AGPLv3. See /LICENSE for details.
]]--
local HTTP = require('socket.http')
local URL = require('socket.url')
local JSON = require('dkjson')
local utilities = require('otouto.utilities')
local urbandictionary = {name = 'urbandictionary'}
function urbandictionary:init()
urbandictionary.command = 'urbandictionary <query>'
urbandictionary.base_url = 'http://api.urbandictionary.com/v0/define?term='
urbandictionary.triggers = utilities.triggers(self.info.username, self.config.cmd_pat):t('urbandictionary', true):t('ud', true):t('urban', true).table
urbandictionary.doc = [[/urbandictionary <query>
Returns a definition from Urban Dictionary.
Aliases: /ud, /urban]]
urbandictionary.doc = urbandictionary.doc:gsub('/', self.config.cmd_pat)
end
function urbandictionary:action(msg)
local input = utilities.input_from_msg(msg)
if not input then
utilities.send_reply(msg, urbandictionary.doc, 'html')
return
end
local url = urbandictionary.base_url .. URL.escape(input)
local old_timeout = HTTP.TIMEOUT
HTTP.TIMEOUT = 1
local jstr, code = HTTP.request(url)
HTTP.TIMEOUT = old_timeout
if code ~= 200 then
utilities.send_reply(msg, self.config.errors.connection)
return
end
local data = JSON.decode(jstr)
local output
if data.result_type == 'no_results' then
output = self.config.errors.results
else
output = string.format('<b>%s</b>\n\n%s\n\n<i>%s</i>',
utilities.html_escape(data.list[1].word),
utilities.trim(utilities.html_escape(data.list[1].definition)),
utilities.trim(utilities.html_escape(data.list[1].example or ''))
)
end
utilities.send_reply(msg, output, 'html')
end
return urbandictionary
| agpl-3.0 |
dromozoa/dromozoa-commons | dromozoa/commons/queue.lua | 2 | 1804 | -- Copyright (C) 2015,2017 Tomoyuki Fujimori <moyu@dromozoa.com>
--
-- This file is part of dromozoa-commons.
--
-- dromozoa-commons 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 3 of the License, or
-- (at your option) any later version.
--
-- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>.
local copy = require "dromozoa.commons.copy"
local push = require "dromozoa.commons.push"
local class = {}
function class.new()
return {
min = 1;
max = 0;
}
end
function class:front()
return self[self.min]
end
function class:back()
return self[self.max]
end
function class:push(...)
self.max = push(self, self.max, ...)
return self
end
function class:pop()
local n = self.min
local v = self[n]
self[n] = nil
self.min = n + 1
return v
end
function class:copy(that, i, j)
self.max = copy(self, self.max, that, i, j)
return self
end
function class:each()
return coroutine.wrap(function ()
for i = self.min, self.max do
coroutine.yield(self[i])
end
end)
end
class.metatable = {
__index = class;
}
function class.metatable:__pairs()
return coroutine.wrap(function ()
for i = self.min, self.max do
coroutine.yield(i, self[i])
end
end)
end
return setmetatable(class, {
__call = function ()
return setmetatable(class.new(), class.metatable)
end;
})
| gpl-3.0 |
MkNiz/Love2Crawl | maps/map001.lua | 1 | 29471 | return {
version = "1.1",
luaversion = "5.1",
tiledversion = "0.14.2",
orientation = "orthogonal",
renderorder = "right-down",
width = 30,
height = 30,
tilewidth = 16,
tileheight = 16,
nextobjectid = 50,
properties = {
["mapID"] = "001",
["mapName"] = "PUSTULE PALACE B1F",
["viewset"] = "template"
},
tilesets = {
{
name = "tiles1",
firstgid = 1,
filename = "tiles1.tsx",
tilewidth = 16,
tileheight = 16,
spacing = 0,
margin = 0,
image = "tiles1.png",
imagewidth = 128,
imageheight = 64,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 32,
tiles = {
{
id = 0,
properties = {
["down"] = "true",
["left"] = "false",
["right"] = "true",
["up"] = "false"
}
},
{
id = 1,
properties = {
["down"] = "false",
["left"] = "true",
["right"] = "true",
["up"] = "false"
}
},
{
id = 2,
properties = {
["down"] = "true",
["left"] = "true",
["right"] = "false",
["up"] = "false"
}
},
{
id = 3,
properties = {
["down"] = "false",
["left"] = "false",
["right"] = "false",
["up"] = "false"
}
},
{
id = 4,
properties = {
["down"] = "true",
["left"] = "false",
["right"] = "true",
["up"] = "false"
}
},
{
id = 5,
properties = {
["down"] = "true",
["left"] = "true",
["right"] = "true",
["up"] = "false"
}
},
{
id = 6,
properties = {
["down"] = "true",
["left"] = "true",
["right"] = "false",
["up"] = "false"
}
},
{
id = 8,
properties = {
["down"] = "true",
["left"] = "false",
["right"] = "false",
["up"] = "true"
}
},
{
id = 9,
properties = {
["down"] = "true",
["left"] = "true",
["right"] = "true",
["up"] = "true"
}
},
{
id = 10,
properties = {
["down"] = "true",
["left"] = "false",
["right"] = "false",
["up"] = "true"
}
},
{
id = 11,
properties = {
["down"] = "false",
["left"] = "false",
["right"] = "false",
["up"] = "false"
}
},
{
id = 12,
properties = {
["down"] = "true",
["left"] = "false",
["right"] = "true",
["up"] = "true"
}
},
{
id = 13,
properties = {
["down"] = "true",
["left"] = "true",
["right"] = "true",
["up"] = "true"
}
},
{
id = 14,
properties = {
["down"] = "true",
["left"] = "true",
["right"] = "false",
["up"] = "true"
}
},
{
id = 16,
properties = {
["down"] = "false",
["left"] = "false",
["right"] = "true",
["up"] = "true"
}
},
{
id = 17,
properties = {
["down"] = "false",
["left"] = "true",
["right"] = "true",
["up"] = "false"
}
},
{
id = 18,
properties = {
["down"] = "false",
["left"] = "true",
["right"] = "false",
["up"] = "true"
}
},
{
id = 19,
properties = {
["down"] = "false",
["left"] = "false",
["right"] = "false",
["up"] = "false"
}
},
{
id = 20,
properties = {
["down"] = "false",
["left"] = "false",
["right"] = "true",
["up"] = "true"
}
},
{
id = 21,
properties = {
["down"] = "false",
["left"] = "true",
["right"] = "true",
["up"] = "true"
}
},
{
id = 22,
properties = {
["down"] = "false",
["left"] = "true",
["right"] = "false",
["up"] = "true"
}
},
{
id = 24,
properties = {
["down"] = "false",
["left"] = "false",
["right"] = "false",
["up"] = "true"
}
},
{
id = 25,
properties = {
["down"] = "false",
["left"] = "true",
["right"] = "false",
["up"] = "false"
}
},
{
id = 26,
properties = {
["down"] = "true",
["left"] = "false",
["right"] = "false",
["up"] = "false"
}
},
{
id = 27,
properties = {
["down"] = "false",
["left"] = "false",
["right"] = "true",
["up"] = "false"
}
},
{
id = 28,
properties = {
["down"] = "true",
["left"] = "true",
["right"] = "true",
["up"] = "false"
}
},
{
id = 29,
properties = {
["down"] = "true",
["left"] = "true",
["right"] = "false",
["up"] = "true"
}
},
{
id = 30,
properties = {
["down"] = "false",
["left"] = "true",
["right"] = "true",
["up"] = "true"
}
},
{
id = 31,
properties = {
["down"] = "true",
["left"] = "false",
["right"] = "true",
["up"] = "true"
}
}
}
},
{
name = "tiles2",
firstgid = 33,
filename = "tiles2.tsx",
tilewidth = 16,
tileheight = 16,
spacing = 0,
margin = 0,
image = "tiles2.png",
imagewidth = 64,
imageheight = 64,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 16,
tiles = {
{
id = 0,
properties = {
["forwardDir"] = "all",
["overDir"] = "all",
["type"] = "door"
}
},
{
id = 1,
properties = {
["type"] = "interaction"
}
},
{
id = 2,
properties = {
["forwardDir"] = "all",
["overDir"] = "all",
["type"] = "door"
}
},
{
id = 4,
properties = {
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 5,
properties = {
["forwardDir"] = "down",
["overDir"] = "up",
["type"] = "door"
}
},
{
id = 6,
properties = {
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 7,
properties = {
["forwardDir"] = "down",
["overDir"] = "up",
["type"] = "door"
}
}
}
}
},
layers = {
{
type = "tilelayer",
name = "Tile Layer 1",
x = 0,
y = 0,
width = 30,
height = 30,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 27, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 11, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 6, 6, 7, 5, 7, 11, 5, 7, 5, 6, 6, 7, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 21, 14, 22, 23, 13, 14, 10, 14, 15, 21, 22, 14, 23, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 5, 6, 6, 14, 7, 1, 14, 15, 11, 13, 14, 3, 5, 14, 6, 6, 7, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 13, 14, 14, 14, 15, 9, 21, 23, 11, 21, 23, 11, 13, 14, 14, 14, 15, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 13, 14, 14, 14, 14, 19, 1, 2, 10, 2, 3, 17, 14, 14, 14, 14, 15, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 13, 14, 14, 22, 23, 5, 14, 7, 9, 5, 14, 7, 21, 22, 14, 14, 15, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 21, 14, 23, 1, 2, 14, 14, 15, 9, 13, 14, 14, 2, 3, 21, 14, 23, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 11, 5, 14, 7, 21, 14, 23, 25, 21, 14, 23, 5, 14, 7, 11, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 11, 13, 14, 15, 5, 14, 7, 27, 5, 14, 7, 13, 14, 15, 11, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 11, 13, 14, 14, 14, 14, 14, 10, 14, 14, 14, 14, 14, 15, 11, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 1, 19, 21, 22, 23, 21, 22, 23, 11, 21, 22, 23, 21, 22, 23, 17, 3, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 9, 1, 2, 29, 2, 2, 2, 2, 10, 2, 2, 2, 2, 29, 2, 3, 11, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 9, 9, 5, 14, 7, 5, 6, 7, 11, 5, 6, 7, 5, 14, 7, 11, 11, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 9, 9, 13, 14, 15, 13, 14, 14, 10, 14, 14, 15, 13, 14, 15, 11, 11, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 9, 9, 13, 14, 15, 21, 22, 23, 11, 21, 22, 23, 13, 14, 15, 11, 11, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 9, 9, 13, 14, 15, 5, 6, 6, 14, 6, 6, 7, 13, 14, 15, 11, 11, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 9, 9, 21, 22, 23, 21, 14, 22, 22, 22, 14, 23, 21, 22, 23, 11, 11, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 9, 17, 2, 2, 2, 2, 31, 2, 29, 2, 31, 2, 2, 2, 2, 19, 11, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 5, 6, 7, 9, 5, 6, 6, 7, 5, 6, 7, 11, 5, 6, 7, 5, 6, 6, 7, 11, 5, 6, 7, 4, 4, 4,
4, 4, 4, 4, 13, 14, 14, 19, 13, 14, 14, 14, 14, 14, 14, 10, 14, 14, 14, 14, 14, 14, 15, 17, 14, 14, 15, 4, 4, 4,
4, 4, 4, 4, 21, 22, 23, 4, 21, 22, 22, 23, 21, 22, 23, 25, 21, 22, 23, 21, 22, 22, 23, 4, 21, 22, 23, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
}
},
{
type = "objectgroup",
name = "Interactions",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
objects = {
{
id = 2,
name = "",
type = "",
shape = "rectangle",
x = 256,
y = 432,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 3,
name = "",
type = "",
shape = "rectangle",
x = 240,
y = 400,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 4,
name = "",
type = "",
shape = "rectangle",
x = 160,
y = 320,
width = 16,
height = 16,
rotation = 0,
gid = 38,
visible = true,
properties = {
["filename"] = "updown",
["forwardDir"] = "down",
["overDir"] = "up",
["type"] = "door"
}
},
{
id = 8,
name = "",
type = "",
shape = "rectangle",
x = 176,
y = 432,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 9,
name = "",
type = "",
shape = "rectangle",
x = 304,
y = 432,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 10,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 384,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 11,
name = "",
type = "",
shape = "rectangle",
x = 272,
y = 384,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 12,
name = "",
type = "",
shape = "rectangle",
x = 320,
y = 320,
width = 16,
height = 16,
rotation = 0,
gid = 38,
visible = true,
properties = {
["filename"] = "updown",
["forwardDir"] = "down",
["overDir"] = "up",
["type"] = "door"
}
},
{
id = 13,
name = "",
type = "",
shape = "rectangle",
x = 224,
y = 432,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 14,
name = "",
type = "",
shape = "rectangle",
x = 224,
y = 336,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 15,
name = "",
type = "",
shape = "rectangle",
x = 256,
y = 336,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 16,
name = "",
type = "",
shape = "rectangle",
x = 240,
y = 288,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 17,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 304,
width = 16,
height = 16,
rotation = 0,
gid = 35,
visible = true,
properties = {
["filename"] = "all-h",
["forwardDir"] = "all",
["overDir"] = "all",
["type"] = "door"
}
},
{
id = 23,
name = "",
type = "",
shape = "rectangle",
x = 272,
y = 304,
width = 16,
height = 16,
rotation = 0,
gid = 35,
visible = true,
properties = {
["filename"] = "all-h",
["forwardDir"] = "all",
["overDir"] = "all",
["type"] = "door"
}
},
{
id = 24,
name = "",
type = "",
shape = "rectangle",
x = 224,
y = 272,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 25,
name = "",
type = "",
shape = "rectangle",
x = 176,
y = 272,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 26,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 240,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 27,
name = "",
type = "",
shape = "rectangle",
x = 192,
y = 224,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 28,
name = "",
type = "",
shape = "rectangle",
x = 160,
y = 240,
width = 16,
height = 16,
rotation = 0,
gid = 38,
visible = true,
properties = {
["filename"] = "updown",
["forwardDir"] = "down",
["overDir"] = "up",
["type"] = "door"
}
},
{
id = 29,
name = "",
type = "",
shape = "rectangle",
x = 320,
y = 240,
width = 16,
height = 16,
rotation = 0,
gid = 38,
visible = true,
properties = {
["filename"] = "updown",
["forwardDir"] = "down",
["overDir"] = "up",
["type"] = "door"
}
},
{
id = 30,
name = "",
type = "",
shape = "rectangle",
x = 256,
y = 272,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 31,
name = "",
type = "",
shape = "rectangle",
x = 272,
y = 240,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 32,
name = "",
type = "",
shape = "rectangle",
x = 304,
y = 272,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 33,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 208,
width = 16,
height = 16,
rotation = 0,
gid = 38,
visible = true,
properties = {
["filename"] = "updown",
["forwardDir"] = "down",
["overDir"] = "up",
["type"] = "door"
}
},
{
id = 34,
name = "",
type = "",
shape = "rectangle",
x = 272,
y = 208,
width = 16,
height = 16,
rotation = 0,
gid = 38,
visible = true,
properties = {
["filename"] = "updown",
["forwardDir"] = "down",
["overDir"] = "up",
["type"] = "door"
}
},
{
id = 35,
name = "",
type = "",
shape = "rectangle",
x = 160,
y = 144,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 36,
name = "",
type = "",
shape = "rectangle",
x = 320,
y = 144,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 37,
name = "",
type = "",
shape = "rectangle",
x = 224,
y = 144,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 38,
name = "",
type = "",
shape = "rectangle",
x = 256,
y = 144,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 39,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 160,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 40,
name = "",
type = "",
shape = "rectangle",
x = 272,
y = 160,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 41,
name = "",
type = "",
shape = "rectangle",
x = 176,
y = 192,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 42,
name = "",
type = "",
shape = "rectangle",
x = 304,
y = 192,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 43,
name = "",
type = "",
shape = "rectangle",
x = 352,
y = 224,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 44,
name = "",
type = "",
shape = "rectangle",
x = 128,
y = 224,
width = 16,
height = 16,
rotation = 0,
gid = 40,
visible = true,
properties = {
["filename"] = "downup",
["forwardDir"] = "up",
["overDir"] = "down",
["type"] = "door"
}
},
{
id = 45,
name = "",
type = "",
shape = "rectangle",
x = 112,
y = 336,
width = 16,
height = 16,
rotation = 0,
gid = 33,
visible = true,
properties = {
["filename"] = "all-v",
["forwardDir"] = "all",
["overDir"] = "all",
["type"] = "door"
}
},
{
id = 46,
name = "",
type = "",
shape = "rectangle",
x = 368,
y = 336,
width = 16,
height = 16,
rotation = 0,
gid = 33,
visible = true,
properties = {
["filename"] = "all-v",
["forwardDir"] = "all",
["overDir"] = "all",
["type"] = "door"
}
},
{
id = 47,
name = "",
type = "",
shape = "rectangle",
x = 96,
y = 432,
width = 16,
height = 16,
rotation = 0,
gid = 39,
visible = true,
properties = {
["filename"] = "rightleft",
["forwardDir"] = "left",
["overDir"] = "right",
["type"] = "door"
}
},
{
id = 48,
name = "",
type = "",
shape = "rectangle",
x = 384,
y = 432,
width = 16,
height = 16,
rotation = 0,
gid = 37,
visible = true,
properties = {
["filename"] = "leftright",
["forwardDir"] = "right",
["overDir"] = "left",
["type"] = "door"
}
},
{
id = 49,
name = "",
type = "",
shape = "rectangle",
x = 240,
y = 128,
width = 16,
height = 16,
rotation = 0,
gid = 33,
visible = true,
properties = {
["filename"] = "all-v",
["forwardDir"] = "all",
["overDir"] = "all",
["type"] = "door"
}
}
}
}
}
}
| mit |
liruqi/bigfoot | Interface/AddOns/WorldQuestTracker/libs/DF/normal_bar.lua | 1 | 21799 |
local DF = _G ["DetailsFramework"]
if (not DF or not DetailsFrameworkCanLoad) then
return
end
local _
local _rawset = rawset --> lua locals
local _rawget = rawget --> lua locals
local _setmetatable = setmetatable --> lua locals
local _unpack = unpack --> lua locals
local _type = type --> lua locals
local _math_floor = math.floor --> lua locals
local SharedMedia = LibStub:GetLibrary ("LibSharedMedia-3.0")
local cleanfunction = function() end
local APIBarFunctions
do
local metaPrototype = {
WidgetType = "normal_bar",
SetHook = DF.SetHook,
RunHooksForWidget = DF.RunHooksForWidget,
}
_G [DF.GlobalWidgetControlNames ["normal_bar"]] = _G [DF.GlobalWidgetControlNames ["normal_bar"]] or metaPrototype
end
local BarMetaFunctions = _G [DF.GlobalWidgetControlNames ["normal_bar"]]
------------------------------------------------------------------------------------------------------------
--> metatables
BarMetaFunctions.__call = function (_table, value)
if (not value) then
return _table.statusbar:GetValue()
else
return _table.statusbar:SetValue (value)
end
end
BarMetaFunctions.__add = function (v1, v2)
if (_type (v1) == "table") then
local v = v1.statusbar:GetValue()
v = v + v2
v1.statusbar:SetValue (v)
else
local v = v2.statusbar:GetValue()
v = v + v1
v2.statusbar:SetValue (v)
end
end
BarMetaFunctions.__sub = function (v1, v2)
if (_type (v1) == "table") then
local v = v1.statusbar:GetValue()
v = v - v2
v1.statusbar:SetValue (v)
else
local v = v2.statusbar:GetValue()
v = v - v1
v2.statusbar:SetValue (v)
end
end
------------------------------------------------------------------------------------------------------------
--> members
--> tooltip
local function gmember_tooltip (_object)
return _object:GetTooltip()
end
--> shown
local gmember_shown = function (_object)
return _object.statusbar:IsShown()
end
--> frame width
local gmember_width = function (_object)
return _object.statusbar:GetWidth()
end
--> frame height
local gmember_height = function (_object)
return _object.statusbar:GetHeight()
end
--> value
local gmember_value = function (_object)
return _object.statusbar:GetValue()
end
--> right text
local gmember_rtext = function (_object)
return _object.textright:GetText()
end
--> left text
local gmember_ltext = function (_object)
return _object.textleft:GetText()
end
--> left color
local gmember_color = function (_object)
return _object._texture.original_colors
end
--> icon
local gmember_icon = function (_object)
return _object._icon:GetTexture()
end
--> texture
local gmember_texture = function (_object)
return _object._texture:GetTexture()
end
--> font size
local gmember_textsize = function (_object)
local _, fontsize = _object.textleft:GetFont()
return fontsize
end
--> font face
local gmember_textfont = function (_object)
local fontface = _object.textleft:GetFont()
return fontface
end
--> font color
local gmember_textcolor = function (_object)
return _object.textleft:GetTextColor()
end
BarMetaFunctions.GetMembers = BarMetaFunctions.GetMembers or {}
BarMetaFunctions.GetMembers ["tooltip"] = gmember_tooltip
BarMetaFunctions.GetMembers ["shown"] = gmember_shown
BarMetaFunctions.GetMembers ["width"] = gmember_width
BarMetaFunctions.GetMembers ["height"] = gmember_height
BarMetaFunctions.GetMembers ["value"] = gmember_value
BarMetaFunctions.GetMembers ["lefttext"] = gmember_ltext
BarMetaFunctions.GetMembers ["righttext"] = gmember_rtext
BarMetaFunctions.GetMembers ["color"] = gmember_color
BarMetaFunctions.GetMembers ["icon"] = gmember_icon
BarMetaFunctions.GetMembers ["texture"] = gmember_texture
BarMetaFunctions.GetMembers ["fontsize"] = gmember_textsize
BarMetaFunctions.GetMembers ["fontface"] = gmember_textfont
BarMetaFunctions.GetMembers ["fontcolor"] = gmember_textcolor
BarMetaFunctions.GetMembers ["textsize"] = gmember_textsize --alias
BarMetaFunctions.GetMembers ["textfont"] = gmember_textfont --alias
BarMetaFunctions.GetMembers ["textcolor"] = gmember_textcolor --alias
BarMetaFunctions.__index = function (_table, _member_requested)
local func = BarMetaFunctions.GetMembers [_member_requested]
if (func) then
return func (_table, _member_requested)
end
local fromMe = _rawget (_table, _member_requested)
if (fromMe) then
return fromMe
end
return BarMetaFunctions [_member_requested]
end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> tooltip
local smember_tooltip = function (_object, _value)
return _object:SetTooltip (_value)
end
--> show
local smember_shown = function (_object, _value)
if (_value) then
return _object:Show()
else
return _object:Hide()
end
end
--> hide
local smember_hide = function (_object, _value)
if (_value) then
return _object:Hide()
else
return _object:Show()
end
end
--> width
local smember_width = function (_object, _value)
return _object.statusbar:SetWidth (_value)
end
--> height
local smember_height = function (_object, _value)
return _object.statusbar:SetHeight (_value)
end
--> statusbar value
local smember_value = function (_object, _value)
_object.statusbar:SetValue (_value)
return _object.div:SetPoint ("left", _object.statusbar, "left", _value * (_object.statusbar:GetWidth()/100) - 16, 0)
end
--> right text
local smember_rtext = function (_object, _value)
return _object.textright:SetText (_value)
end
--> left text
local smember_ltext = function (_object, _value)
return _object.textleft:SetText (_value)
end
--> color
local smember_color = function (_object, _value)
local _value1, _value2, _value3, _value4 = DF:ParseColors (_value)
_object.statusbar:SetStatusBarColor (_value1, _value2, _value3, _value4)
_object._texture.original_colors = {_value1, _value2, _value3, _value4}
_object.timer_texture:SetVertexColor (_value1, _value2, _value3, _value4)
_object.timer_textureR:SetVertexColor (_value1, _value2, _value3, _value4)
return _object._texture:SetVertexColor (_value1, _value2, _value3, _value4)
end
--> icon
local smember_icon = function (_object, _value)
if (type (_value) == "table") then
local _value1, _value2 = _unpack (_value)
_object._icon:SetTexture (_value1)
if (_value2) then
_object._icon:SetTexCoord (_unpack (_value2))
end
else
_object._icon:SetTexture (_value)
end
return
end
--> texture
local smember_texture = function (_object, _value)
if (type (_value) == "table") then
local _value1, _value2 = _unpack (_value)
_object._texture:SetTexture (_value1)
_object.timer_texture:SetTexture (_value1)
_object.timer_textureR:SetTexture (_value1)
if (_value2) then
_object._texture:SetTexCoord (_unpack (_value2))
_object.timer_texture:SetTexCoord (_unpack (_value2))
_object.timer_textureR:SetTexCoord (_unpack (_value2))
end
else
if (_value:find ("\\")) then
_object._texture:SetTexture (_value)
else
local file = SharedMedia:Fetch ("statusbar", _value)
if (file) then
_object._texture:SetTexture (file)
_object.timer_texture:SetTexture (file)
_object.timer_textureR:SetTexture (file)
else
_object._texture:SetTexture (_value)
_object.timer_texture:SetTexture (_value)
_object.timer_textureR:SetTexture (_value)
end
end
end
return
end
--> font face
local smember_textfont = function (_object, _value)
DF:SetFontFace (_object.textleft, _value)
return DF:SetFontFace (_object.textright, _value)
end
--> font size
local smember_textsize = function (_object, _value)
DF:SetFontSize (_object.textleft, _value)
return DF:SetFontSize (_object.textright, _value)
end
--> font color
local smember_textcolor = function (_object, _value)
local _value1, _value2, _value3, _value4 = DF:ParseColors (_value)
_object.textleft:SetTextColor (_value1, _value2, _value3, _value4)
return _object.textright:SetTextColor (_value1, _value2, _value3, _value4)
end
--> outline (shadow)
local smember_outline = function (_object, _value)
DF:SetFontOutline (_object.textleft, _value)
return DF:SetFontOutline (_object.textright, _value)
end
BarMetaFunctions.SetMembers = BarMetaFunctions.SetMembers or {}
BarMetaFunctions.SetMembers["tooltip"] = smember_tooltip
BarMetaFunctions.SetMembers["shown"] = smember_shown
BarMetaFunctions.SetMembers["width"] = smember_width
BarMetaFunctions.SetMembers["height"] = smember_height
BarMetaFunctions.SetMembers["value"] = smember_value
BarMetaFunctions.SetMembers["righttext"] = smember_rtext
BarMetaFunctions.SetMembers["lefttext"] = smember_ltext
BarMetaFunctions.SetMembers["color"] = smember_color
BarMetaFunctions.SetMembers["icon"] = smember_icon
BarMetaFunctions.SetMembers["texture"] = smember_texture
BarMetaFunctions.SetMembers["fontsize"] = smember_textsize
BarMetaFunctions.SetMembers["fontface"] = smember_textfont
BarMetaFunctions.SetMembers["fontcolor"] = smember_textcolor
BarMetaFunctions.SetMembers["textsize"] = smember_textsize --alias
BarMetaFunctions.SetMembers["textfont"] = smember_textfont --alias
BarMetaFunctions.SetMembers["textcolor"] = smember_textcolor --alias
BarMetaFunctions.SetMembers["shadow"] = smember_outline
BarMetaFunctions.SetMembers["outline"] = smember_outline --alias
BarMetaFunctions.__newindex = function (_table, _key, _value)
local func = BarMetaFunctions.SetMembers [_key]
if (func) then
return func (_table, _value)
else
return _rawset (_table, _key, _value)
end
end
------------------------------------------------------------------------------------------------------------
--> methods
--> show & hide
function BarMetaFunctions:Show()
self.statusbar:Show()
end
function BarMetaFunctions:Hide()
self.statusbar:Hide()
end
--> set value (status bar)
function BarMetaFunctions:SetValue (value)
if (not value) then
value = 0
end
self.statusbar:SetValue (value)
self.div:SetPoint ("left", self.statusbar, "left", value * (self.statusbar:GetWidth()/100) - 16, 0)
end
--> set point
function BarMetaFunctions:SetPoint (v1, v2, v3, v4, v5)
v1, v2, v3, v4, v5 = DF:CheckPoints (v1, v2, v3, v4, v5, self)
if (not v1) then
print ("Invalid parameter for SetPoint")
return
end
return self.widget:SetPoint (v1, v2, v3, v4, v5)
end
--> set sizes
function BarMetaFunctions:SetSize (w, h)
if (w) then
self.statusbar:SetWidth (w)
end
if (h) then
self.statusbar:SetHeight (h)
end
end
--> set texture
function BarMetaFunctions:SetTexture (texture)
self._texture:SetTexture (texture)
end
--> set texts
function BarMetaFunctions:SetLeftText (text)
self.textleft:SetText (text)
end
function BarMetaFunctions:SetRightText (text)
self.textright:SetText (text)
end
--> set color
function BarMetaFunctions:SetColor (r, g, b, a)
r, g, b, a = DF:ParseColors (r, g, b, a)
self._texture:SetVertexColor (r, g, b, a)
self.statusbar:SetStatusBarColor (r, g, b, a)
self._texture.original_colors = {r, g, b, a}
end
--> set icons
function BarMetaFunctions:SetIcon (texture, ...)
self._icon:SetTexture (texture)
if (...) then
local L, R, U, D = _unpack (...)
self._icon:SetTexCoord (L, R, U, D)
end
end
--> show div
function BarMetaFunctions:ShowDiv (bool)
if (bool) then
self.div:Show()
else
self.div:Hide()
end
end
-- tooltip
function BarMetaFunctions:SetTooltip (tooltip)
if (tooltip) then
return _rawset (self, "have_tooltip", tooltip)
else
return _rawset (self, "have_tooltip", nil)
end
end
function BarMetaFunctions:GetTooltip()
return _rawget (self, "have_tooltip")
end
-- frame levels
function BarMetaFunctions:GetFrameLevel()
return self.statusbar:GetFrameLevel()
end
function BarMetaFunctions:SetFrameLevel (level, frame)
if (not frame) then
return self.statusbar:SetFrameLevel (level)
else
local framelevel = frame:GetFrameLevel (frame) + level
return self.statusbar:SetFrameLevel (framelevel)
end
end
-- frame stratas
function BarMetaFunctions:SetFrameStrata()
return self.statusbar:GetFrameStrata()
end
function BarMetaFunctions:SetFrameStrata (strata)
if (_type (strata) == "table") then
self.statusbar:SetFrameStrata (strata:GetFrameStrata())
else
self.statusbar:SetFrameStrata (strata)
end
end
--> container
function BarMetaFunctions:SetContainer (container)
self.container = container
end
------------------------------------------------------------------------------------------------------------
--> scripts
local OnEnter = function (frame)
local capsule = frame.MyObject
local kill = capsule:RunHooksForWidget ("OnEnter", frame, capsule)
if (kill) then
return
end
frame.MyObject.background:Show()
if (frame.MyObject.have_tooltip) then
GameCooltip2:Reset()
GameCooltip2:AddLine (frame.MyObject.have_tooltip)
GameCooltip2:ShowCooltip (frame, "tooltip")
end
end
local OnLeave = function (frame)
local capsule = frame.MyObject
local kill = capsule:RunHooksForWidget ("OnLeave", frame, capsule)
if (kill) then
return
end
if (frame.MyObject.have_tooltip) then
GameCooltip2:ShowMe (false)
end
end
local OnHide = function (frame)
local capsule = frame.MyObject
local kill = capsule:RunHooksForWidget ("OnHide", frame, capsule)
if (kill) then
return
end
end
local OnShow = function (frame)
local capsule = frame.MyObject
local kill = capsule:RunHooksForWidget ("OnShow", frame, capsule)
if (kill) then
return
end
end
local OnMouseDown = function (frame, button)
local capsule = frame.MyObject
local kill = capsule:RunHooksForWidget ("OnMouseDown", frame, button, capsule)
if (kill) then
return
end
if (not frame.MyObject.container.isLocked and frame.MyObject.container:IsMovable()) then
if (not frame.isLocked and frame:IsMovable()) then
frame.MyObject.container.isMoving = true
frame.MyObject.container:StartMoving()
end
end
end
local OnMouseUp = function (frame, button)
local capsule = frame.MyObject
local kill = capsule:RunHooksForWidget ("OnMouseUp", frame, button, capsule)
if (kill) then
return
end
if (frame.MyObject.container.isMoving) then
frame.MyObject.container:StopMovingOrSizing()
frame.MyObject.container.isMoving = false
end
end
------------------------------------------------------------------------------------------------------------
--> timer
function BarMetaFunctions:OnTimerEnd()
local capsule = self
local kill = capsule:RunHooksForWidget ("OnTimerEnd", self.widget, capsule)
if (kill) then
return
end
self.timer_texture:Hide()
self.timer_textureR:Hide()
self.div_timer:Hide()
self:Hide()
self.timer = false
end
function BarMetaFunctions:CancelTimerBar (no_timer_end)
if (not self.HasTimer) then
return
end
if (self.TimerScheduled) then
DF:CancelTimer (self.TimerScheduled)
self.TimerScheduled = nil
else
if (self.statusbar:GetScript ("OnUpdate")) then
self.statusbar:SetScript ("OnUpdate", nil)
end
end
self.righttext = ""
if (not no_timer_end) then
self:OnTimerEnd()
end
end
local OnUpdate = function (self, elapsed)
--> percent of elapsed
local pct = abs (self.end_timer - GetTime() - self.tempo) / self.tempo
if (self.inverse) then
self.t:SetWidth (self.total_size * pct)
else
self.t:SetWidth (self.total_size * abs (pct-1))
end
--> right text
self.remaining = self.remaining - elapsed
if (self.MyObject.RightTextIsTimer) then
self.righttext:SetText (DF:IntegerToTimer (self.remaining))
else
self.righttext:SetText (_math_floor (self.remaining))
end
if (pct >= 1) then
self.righttext:SetText ("")
self:SetScript ("OnUpdate", nil)
self.MyObject.HasTimer = nil
self.MyObject:OnTimerEnd()
end
end
function BarMetaFunctions:SetTimer (tempo, end_at)
if (end_at) then
self.statusbar.tempo = end_at - tempo
self.statusbar.remaining = end_at - GetTime()
self.statusbar.end_timer = end_at
else
self.statusbar.tempo = tempo
self.statusbar.remaining = tempo
self.statusbar.end_timer = GetTime() + tempo
end
self.statusbar.total_size = self.statusbar:GetWidth()
self.statusbar.inverse = self.BarIsInverse
self (0)
self.div_timer:Show()
self.background:Show()
self:Show()
if (self.LeftToRight) then
self.timer_texture:Hide()
self.timer_textureR:Show()
self.statusbar.t = self.timer_textureR
self.timer_textureR:ClearAllPoints()
self.timer_textureR:SetPoint ("right", self.statusbar, "right")
self.div_timer:SetPoint ("left", self.timer_textureR, "left", -14, -1)
else
self.timer_texture:Show()
self.timer_textureR:Hide()
self.statusbar.t = self.timer_texture
self.timer_texture:ClearAllPoints()
self.timer_texture:SetPoint ("left", self.statusbar, "left")
self.div_timer:SetPoint ("left", self.timer_texture, "right", -16, -1)
end
if (self.BarIsInverse) then
self.statusbar.t:SetWidth (1)
else
self.statusbar.t:SetWidth (self.statusbar.total_size)
end
self.timer = true
self.HasTimer = true
self.TimerScheduled = DF:ScheduleTimer ("StartTimeBarAnimation", 0.1, self)
end
function DF:StartTimeBarAnimation (timebar)
timebar.TimerScheduled = nil
timebar.statusbar:SetScript ("OnUpdate", OnUpdate)
end
------------------------------------------------------------------------------------------------------------
--> object constructor
function DetailsFrameworkNormalBar_OnCreate (self)
self.texture.original_colors = {1, 1, 1, 1}
self.background.original_colors = {.3, .3, .3, .3}
self.timertexture.original_colors = {.3, .3, .3, .3}
return true
end
function DF:CreateBar (parent, texture, w, h, value, member, name)
return DF:NewBar (parent, parent, name, member, w, h, value, texture)
end
function DF:NewBar (parent, container, name, member, w, h, value, texture_name)
if (not name) then
name = "DetailsFrameworkBarNumber" .. DF.BarNameCounter
DF.BarNameCounter = DF.BarNameCounter + 1
elseif (not parent) then
return error ("Details! FrameWork: parent not found.", 2)
elseif (not container) then
container = parent
end
if (name:find ("$parent")) then
local parentName = DF.GetParentName (parent)
name = name:gsub ("$parent", parentName)
end
local BarObject = {type = "bar", dframework = true}
if (member) then
parent [member] = BarObject
end
if (parent.dframework) then
parent = parent.widget
end
if (container.dframework) then
container = container.widget
end
value = value or 0
w = w or 150
h = h or 14
--> default members:
--> misc
BarObject.locked = false
BarObject.container = container
--> create widgets
BarObject.statusbar = CreateFrame ("statusbar", name, parent, "DetailsFrameworkNormalBarTemplate")
BarObject.widget = BarObject.statusbar
if (not APIBarFunctions) then
APIBarFunctions = true
local idx = getmetatable (BarObject.statusbar).__index
for funcName, funcAddress in pairs (idx) do
if (not BarMetaFunctions [funcName]) then
BarMetaFunctions [funcName] = function (object, ...)
local x = loadstring ( "return _G['"..object.statusbar:GetName().."']:"..funcName.."(...)")
return x (...)
end
end
end
end
BarObject.statusbar:SetHeight (h)
BarObject.statusbar:SetWidth (w)
BarObject.statusbar:SetFrameLevel (parent:GetFrameLevel()+1)
BarObject.statusbar:SetMinMaxValues (0, 100)
BarObject.statusbar:SetValue (value or 50)
BarObject.statusbar.MyObject = BarObject
BarObject.timer_texture = _G [name .. "_timerTexture"]
BarObject.timer_texture:SetWidth (w)
BarObject.timer_texture:SetHeight (h)
BarObject.timer_textureR = _G [name .. "_timerTextureR"]
BarObject.timer_textureR:Hide()
BarObject._texture = _G [name .. "_statusbarTexture"]
BarObject.background = _G [name .. "_background"]
BarObject._icon = _G [name .. "_icon"]
BarObject.textleft = _G [name .. "_TextLeft"]
BarObject.textright = _G [name .. "_TextRight"]
BarObject.div = _G [name .. "_sparkMouseover"]
BarObject.div_timer = _G [name .. "_sparkTimer"]
--> hooks
BarObject.HookList = {
OnEnter = {},
OnLeave = {},
OnHide = {},
OnShow = {},
OnMouseDown = {},
OnMouseUp = {},
OnTimerEnd = {},
}
BarObject.statusbar:SetScript ("OnEnter", OnEnter)
BarObject.statusbar:SetScript ("OnLeave", OnLeave)
BarObject.statusbar:SetScript ("OnHide", OnHide)
BarObject.statusbar:SetScript ("OnShow", OnShow)
BarObject.statusbar:SetScript ("OnMouseDown", OnMouseDown)
BarObject.statusbar:SetScript ("OnMouseUp", OnMouseUp)
--> set class
_setmetatable (BarObject, BarMetaFunctions)
--> set texture
if (texture_name) then
smember_texture (BarObject, texture_name)
end
return BarObject
end --endd
| mit |
Ali-2h/ali | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
shiprabehera/kong | kong/tools/ip.lua | 5 | 1207 | local ip = require "resty.mediador.ip"
local px = require "resty.mediador.proxy"
local function trust_all() return true end
local function trust_none() return false end
local _M = { valid = ip.valid }
function _M.init(config)
local ips = config.trusted_ips
local count = #ips
local trusted_ips = {}
local trust_all_ipv4, trust_all_ipv6
-- This is because we don't support unix: that the ngx_http_realip module supports.
-- Also as an optimization we will only compile trusted ips if the Kong is not run
-- with the default 0.0.0.0/0, ::/0 aka trust all ip addresses settings.
for i = 1, count do
local address = ips[i]
if ip.valid(address) then
trusted_ips[#trusted_ips+1] = address
if address == "0.0.0.0/0" then
trust_all_ipv4 = true
elseif address == "::/0" then
trust_all_ipv6 = true
end
end
end
if #trusted_ips == 0 then
return {
valid = ip.valid,
trusted = trust_none,
}
end
if trust_all_ipv4 and trust_all_ipv6 then
return {
valid = ip.valid,
trusted = trust_all,
}
end
return {
valid = ip.valid,
trusted = px.compile(trusted_ips),
}
end
return _M
| apache-2.0 |
Yonaba/Algorithm-Implementations | Boyer_Moore_Horspool/Lua/Yonaba/bmh_test.lua | 27 | 1111 | -- Tests for bmh.lua
local bmh = require 'bmh'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Finds a substring in a string', function()
assert(bmh('a', 'b') == nil)
assert(bmh('a', 'a') == 1)
assert(bmh('', 'a') == nil)
assert(bmh('hello', 'llo') == 3)
assert(bmh('harry and john', 'john') == 11)
assert(bmh('Boyer-Moore-Horspool', 'Boyer') == 1)
assert(bmh('Boyer-Moore-Horspool', 'Moore') == 7)
assert(bmh('Boyer-Moore-Horspool', 'Horspool') == 13)
assert(bmh('Boyer-Moore-Horspool', '-') == 6)
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.