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 |
|---|---|---|---|---|---|
StephenZhuang/qdkpv2 | QDKP_V2/QDKP_V2/Code/Logging/LogEntry.lua | 1 | 44788 | -- Copyright 2012 Akhaan & Honesty Hyj (www.quickdkp.com)
-- This file is a part of QDKP_V2 (see about.txt in the Addon's root folder)
-- ## LOGGING SYSTEM ##
-- Log Entry functions
-- API Documentation
-- QDKP2log_Entry: Creates a new log entry. See the function description for mole details.
-- QDKP2log_Event(name,event): Dummy of QDKP2log_Entry, gives a fast interface to create a new Event type log entry
-- QDKP2log_Link: Not-real-dummy of QDKP2log_Entry that creates a link to a given log.
-- QDKP2log_UnDoEntry(name,log,SID,[on,off]): Toggle a DKP log entry between ACTIVE and INACTIVE status. Takes care to add/subtract DKPs.
-- QDKP2log_SetLogEntry(name,log,SID,[G,S,H,Reason]): Changes the log's DKP and reason.
-- QDKP2log_AwardLinkedEntry(name,log,SID,todo=toggle): Set log to award or not-award. Works only with linked logs (not main)
-- QDKP2log_UpdateLinkedDKPLog(name,Log,SID): Updates a linked DKP log entry (Raid aw, ZS). To be used when you modify a main DKP entry.
-- QDKP2log_GetModEntryText(Log,isRaid): Returns a human-readable description of Log. Trasparent to links.
-- QDKP2log_GetLastLogText(name): dummy of GetModEntryText, returns the description of the last log made for <Name>
-- QDKP2log_CheckLink(Log): Resolves Link,true if Log is a link, returns Log,false if not.
-- QDKP2log_GetData(Log) : Unpacker for Log data.
-- QDKP2log_GetType(Log) : Returns the type of LogEntry
-- QDKP2log_GetTS(Log) : Returns the TimeStamp of Log
-- QDKP2log_GetModEntryDateTime(Log): Returns the date the log entry was created in standard QDKP form (Dummy)
-- QDKP2log_GetReason(Log) : Returns the reason field of Log
-- QDKP2log_GetVersion(Log) : Returns the Version of Log
-- QDKP2log_GetAmounts(Log) : Returns the amounts in the log (if any) in this form: awards,spends,hours,coefficent,nominalAward
-- QDKP2log_GetChange(LogEntry) : Returns the net DKP change subtended by LogEntry.
-- QDKP2log_GetFlags(Log) : Retruns the flag of Log, if any
-- QDKP2log_GetCreator(Log,SID) : Returns the name of the log creator
-- QDKP2log_GetModder(Log, SID) : Retruns the name of the last log modder.
-- QDKP2log_GetStr(LogEntry); Coverts the Log in a string.
-- QDKP2log_GetLogFromStr(LogEntry); convers a string made with QDKP2log_GetStr back to a log.
-- QDKP2log_BackupSave(session,name,Log): Called before modifying a DKP entry, stores a copy to revert back if needed.
-- QDKP2log_BackupDelete(session,name,Log): Deletes the log backup with the given coordinates (if any)
-- QDKP2log_getBackup(SID,name,Log); returns true if the log has been modified and not yet uploaded.
-- QDKP2log_BackupRevert(SID,name,Log); takes the backup copy (if any) and overwrite the given coordinates with it, reverting to last save.
-- QDKP2log_getBackupList(): Returns a list of the currently saved Backup entries in this format: {{SID1,Log1},{SID2,Log2},...}
----------------------QDKP2log_Entry----------------------
--[[Adds to the Log an entry
Usage QDKP2log_Entry(name, action, type, [undo], [timestamp], flags, outsideSession)
name: string, the name of the player to loc. Can be "RAID" for raid log
action: string, the action that has to ble logged
type: an identifier of the log entry. can be QDKP2LOG_EVENT, QDKP2LOG_CRITICAL,... (look at the beginning of the file)
undo: a table with this structure: {[1]=x, [2]=y, [3]=z}. used to undo that command (on click)}
x= total increase, y= spent increase and z=hours increase
timestamp: tells the program the time to use
flags: used to store additional numbers/bits for advanced entries like linked awards. Should not be referenced when used as API
outsideSession: Records the entry in the general session regardless os the ongoing session.
returns the session SID in which the entry was stored. nil if aborted.
]]--
function QDKP2log_Entry(name, action, Type, undo, timestamp, flags, outsideSession)
QDKP2_Debug(2,"Logging","QDKP2log_Entry called. N:"..tostring(name).." ACT:"..tostring(action).." T:"..tostring(Type).." U:"..tostring(undo).." Tm:"..tostring(timestamp))
if not QDKP2_OfficerMode() and not (Type==QDKP2LOG_EXTERNAL) then
QDKP2_Debug(1,"Logging","Trying to create a log entry, but you aren't in officer mode!")
-- QDKP2_Msg(QDKP2_LOC_NoRights)
return
end
if name=="RAID" and not QDKP2_IsManagingSession() then
QDKP2_Debug(1,"Logging","Trying to create a RAID entry while no sessions are active!")
return
end
name=QDKP2_GetMain(name)
local SessPlayer=(QDKP2log[QDKP2_OngoingSession()] or {})[name] --this will be nil if player didn't took part in the session
if (name=='RAID' or QDKP2_IsSessionRelated(Type) or SessPlayer or QDKP2_IsInRaid(name)) and not outsideSession then
SID = QDKP2_OngoingSession()
else
SID='0'
end
SessionLog=QDKP2log[SID]
if SID=='0' and QDKP2_IsSessionRelated(Type) then
QDKP2_Debug(1,"Logging", "Trying to make a log entry that is related to a Session, but the session to write into is the <0>. ACT="..tostring(action))
return
end
if not SessionLog then
QDKP2_Debug(1,"Logging","OngoingSession index of QDKP2log is nil?!?! (SID: "..tostring(SID)..")")
return
end
if not SessionLog[name] then
QDKP2_Debug(3,"Logging","Initializing the session for the given player")
SessionLog[name] = {}
end
local net
PlayersLog=SessionLog[name]
timestamp = timestamp or QDKP2_Timestamp()
local version
if QDKP2_IsVersionedEntry(Type) then
version=0
end
local tempEntry
if SID=="0" then
-- type timest. spam Vrs amounts mod date flags creator Sign
tempEntry = {Type, timestamp, action, version, undo, nil, nil , flags, QDKP2_PLAYER_NAME_12}
else
tempEntry = {Type, timestamp, action, version, undo, nil, nil , flags}
end
--Defining empty log backup so the revert will delete the entry.
if Type==QDKP2LOG_MODIFY then QDKP2log_BackupSave(SID,name,tempEntry,true); end
local LogSize = table.getn(PlayersLog) and QDKP2_LOG_MAXSIZE
--add the entry at the top of the log
local tempLog={tempEntry}
local MaxSize=QDKP2_LOG_MAXSIZE
if name=="RAID" then MaxSize=QDKP2_LOG_RAIDMAXSIZE;end
MaxSize=MaxSize-1
if LogSize > MaxSize then LogSize = MaxSize;end --pop the last entries if i'm at the maximum log's length
for buildLog=1, LogSize do table.insert(tempLog, PlayersLog[buildLog]); end
SessionLog[name] = tempLog
QDKP2_Debug(3,"Logging","Log entry successful created")
return SID
end
--two dummies for QDKP2log_Entry
function QDKP2log_Event(name,event)
--this creates a generic log entry.
QDKP2log_Entry(name,event,QDKP2LOG_EVENT)
end
function QDKP2log_Link(name, nametolink, timestamp, session)
--a link to a log entry.
session = session or QDKP2_OngoingSession()
QDKP2_Debug(2,"Logging","Creating a log link from "..name.." to "..nametolink.." in session "..session)
if not timestamp then
QDKP2_Debug(1,"Logging","Trying to create a log link without providing the timestamp!")
return
end
if not nametolink then
QDKP2_Debug(1,"Logging","Trying to create a log link without providing the linked player!")
return
end
local out=session
if QDKP2_IsAlt(nametolink) then
out=out.."|"..QDKP2_GetMain(nametolink)
end
out=out.."|"..nametolink
QDKP2log_Entry(name, out, QDKP2LOG_LINK, nil, timestamp)
return out
end
---------------------- Revert Mirrors (Backups) ------------------------------------
function QDKP2log_BackupSave(SID,name,Log,deleteIt)
-- Saves a log entry, so you can revert it to this state. Used before editing a DKP log entry.
-- return true if succeeds.
QDKP2logEntries_BackMod[name]=QDKP2logEntries_BackMod[name] or {}
local playerBackups=QDKP2logEntries_BackMod[name]
local ts=tostring(Log[QDKP2LOG_FIELD_TIME])
local key=SID.."|"..ts
if not playerBackups[key] then --if not nil then i already have the original saved.
QDKP2_Debug(3,"Logging","Saving "..key.." for "..name.." before modifying it...")
local Undo=Log[QDKP2LOG_FIELD_AMOUNTS]
local backupLog=QDKP2_CopyTable(Log)
if Undo then backupLog[QDKP2LOG_FIELD_AMOUNTS]=QDKP2_CopyTable(Undo); end
if deleteIt then backupLog[QDKP2LOG_FIELD_TYPE]=nil; end
playerBackups[key]=backupLog
return true
else
QDKP2_Debug(3,"Logging","I'm not saving "..key.." for "..name.."because there is already a backup.")
end
end
function QDKP2log_BackupDel(SID,name,Log)
local playerBackups=QDKP2logEntries_BackMod[name]
if not playerBackups then return; end
local ts=tostring(Log[QDKP2LOG_FIELD_TIME])
local key=SID.."|"..ts
if playerBackups[key] then
playerBackups[key]=nil
return true
end
end
function QDKP2log_getBackup(SID,name,Log)
local playerBackups=QDKP2logEntries_BackMod[name]
if not playerBackups then return; end
if not QDKP2_IsInGuild(name) then
QDKP2log_BackupDel(SID,name,Log)
return
end
local ts=tostring(Log[QDKP2LOG_FIELD_TIME])
local key=SID.."|"..ts
return playerBackups[key]
end
function QDKP2log_BackupRevert(SID,name,Log)
-- reverts a modified entry back to its original conditions. returns true if succeeds.
QDKP2_Debug(2,"Logging","Reverting log entry "..SID..":"..tostring(Log).." in "..name.."'s log")
local Backup=QDKP2log_getBackup(SID,name,Log)
if not Backup then
QDKP2_Debug(1,"Logging","Trying to revert a Log Entry that does not have a Backup.")
return
end
if not QDKP2_IsInGuild(name) then
QDKP2_Debug(1,"Logging","Trying to revert a Log Entry of a player that is not in guild. removing.")
QDKP2log_BackupDel(SID,name,Log)
return
end
local ts=Log[QDKP2LOG_FIELD_TIME]
local List=QDKP2log_GetPlayer(SID,name)
if not List then
QDKP2_Debug(1,"Logging","Trying to revert a log with an invalid SID/name code")
return
end
local index=QDKP2log_FindIndex(List,ts)
if not index then
QDKP2_Debug(1,"Logging","Trying to revert an Inexisting log entry!")
return
end
if Backup[QDKP2LOG_FIELD_TYPE] then
List[index]=Backup
else
table.remove(List,index)
end
local key=SID.."|"..tostring(ts)
QDKP2logEntries_BackMod[name][key]=nil
return true
end
function QDKP2log_getBackupList(name)
-- returns a list of coordinates of logs with backups, in this way: {{sid1,log1},{sid2,log2},...}
-- it also cleans the BackModlist from entries that are avilable no more.
local playerBackups=QDKP2logEntries_BackMod[name]
if not playerBackups then return {}; end
local out={}
table.foreach(playerBackups, function(key,Backup)
local _,_,SID,ts=string.find(key,"([^,]*)|([^,]*)")
ts=tonumber(ts)
if not ts or not SID then return; end
local Log
local SessList=QDKP2log[SID]
if SessList then
local LogList=SessList[name]
if LogList then
Log=QDKP2log_Find(SessList[name],ts)
end
end
if Log then
table.insert(out,{SID,Log})
else
QDKP2_Msg(2,"Logging","Removing "..key.." from "..name.."'s log backups because can't find corresponding log.")
playerBackups[key]=nil --backup does not have a corresponding log. delete it.
end
end)
return out
end
----------------------LOG ENTRY FUNCTIONS------------------------------------
--- Readers
-- QDKP2log_GetModEntryText(Log,isRaid)
-- Returns the log's human-readable description.
--also used as integrity check, will return text,broken on corrupted entry. text is a description of the error, and broken wll be true.
-- Log is the source of the description, Raid must be set to true if is in the raid log.
function QDKP2log_GetModEntryText(Log,isRaid)
if not Log then return "NULL Entry"; end
local LinkedName, AltLinkedName
local Type=QDKP2log_GetType(Log)
local Bit0,Bit1,Bit2,Bit3,Var1,Var2=QDKP2log_GetFlags(Log)
local RaidAw,ZeroSum,MainEntry=Bit0,Bit1,Bit2 --for easier reading
local output = ""
local DataLog=Log
if Type==QDKP2LOG_LINK or (ZeroSum and not MainEntry) then
Log,LinkedName,AltLinkedName=QDKP2log_FindLink(Log)
if QDKP2_IsInvalidEntry(Type) then return Log[QDKP2LOG_FIELD_ACTION]; end
if not ZeroSum or MainEntry then
LinkedName=LinkedName or '*'..UNKNOWN..'*'
if AltLinkedName then output=output..AltLinkedName.." ("..LinkedName..") "
else output=output..LinkedName.." "
end
DataLog=Log
Bit0,Bit1,Bit2,Bit3,Var1,Var2=QDKP2log_GetFlags(Log)
RaidAw,ZeroSum,MainEntry=Bit0,Bit1,Bit2
Type = QDKP2log_GetType(Log)
end
end
local reason = Log[QDKP2LOG_FIELD_ACTION]
if Type==QDKP2LOG_SESSION then
local SessList,SessName=QDKP2_GetSessionInfo(reason)
SessName=SessName or '<'..UNKNOWN ..'>'
if isRaid then
output=output .. QDKP2_LOC_Session .. " $SESSION"
else
output=output .. QDKP2_LOC_SessJoin
end
output=string.gsub(output,"$SESSION",SessName)
elseif QDKP2_IsDKPEntry(Type) then
local gained,spent,hours,Mod,Ngained=QDKP2log_GetAmounts(DataLog)
if (not Ngained and not spent and not hours) then
if (RaidAw or ZeroSum) and not MainEntry then
Ngained=0
else
Ngained=0
spent=0
end
end
if Type==QDKP2LOG_EXTERNAL then
output=output .. QDKP2_LOC_ExtMod
elseif reason then
if RaidAw and not MainEntry then
output=output .. QDKP2_LOC_RaidAwReas
elseif RaidAw then
output=output .. QDKP2_LOC_RaidAwMainReas
elseif ZeroSum and not MainEntry then
output = output .. QDKP2_LOC_ZeroSumAwReas
elseif ZeroSum then
output = output .. QDKP2_LOC_ZeroSumSpReas
elseif spent and not gained and not hours and GetItemIcon(reason) then --i use getitemicon to tell if reason is a valid item name/link
output= output .. QDKP2_LOC_DKPPurchase
output=string.gsub(output,"$ITEM",reason)
output=string.gsub(output,"$AMOUNT",spent)
return output
else
output= output .. QDKP2_LOC_GenericReas
end
output=string.gsub(output,"$REASON",tostring(reason))
else
if RaidAw and not MainEntry then
output=output .. QDKP2_LOC_RaidAw
elseif RaidAw then
output=output .. QDKP2_LOC_RaidAwMain
elseif ZeroSum and not MainEntry then
output = output .. QDKP2_LOC_ZeroSumAw
elseif ZeroSum then
output = output .. QDKP2_LOC_ZeroSumSp
else
output = output .. QDKP2_LOC_Generic
end
end
if ZeroSum then
local giver=""
if AltLinkedName then giver=AltLinkedName.." ("..LinkedName..")"
elseif LinkedName then giver=LinkedName
end
output=string.gsub(output,"$GIVER",giver)
gained=tostring(Ngained)
if Mod and Mod ~= 100 then
gained=gained.."x"..tostring(Mod).."%%"
end
output=string.gsub(output,"$AMOUNT",gained)
output=string.gsub(output,"$SPENT",tostring(spent))
end
local AwardSpendText=QDKP2_GetAwardSpendText(Ngained, spent, hours,Mod)
output=string.gsub(output,"$AWARDSPENDTEXT",AwardSpendText)
elseif Type==QDKP2LOG_LOOT then
if Bit0 then
output=output .. QDKP2_LOC_ShardsItem
else
output=output .. QDKP2_LOC_LootsItem
end
local itemName,itemLink=GetItemInfo(reason or '')
local text=itemLink or ''
if Var1>1 then text=text.."x"..tostring(Var1); end
output=string.gsub(output,"$ITEM",text)
elseif Type==QDKP2LOG_BOSS then
output=QDKP2_LOC_BossKill
output=string.gsub(output,"$BOSS",tostring(reason))
elseif QDKP2_IsNODKPEntry(Type) then
local gained, spent, hours, Mod, Ngained = QDKP2log_GetAmounts(DataLog)
if Var1==QDKP2LOG_NODKP_MANUAL then
whynot=QDKP2_LOC_NODKP_Manual
elseif Var1==QDKP2LOG_NODKP_OFFLINE then
whynot = QDKP2_LOC_NODKP_Offline
elseif Var1==QDKP2LOG_NODKP_RANK then
whynot = QDKP2_LOC_NODKP_Rank
elseif Var1==QDKP2LOG_NODKP_ZONE then
whynot = QDKP2_LOC_NODKP_Zone
elseif Var1==QDKP2LOG_NODKP_LOWRAID then
whynot = QDKP2_LOC_NODKP_LowAtt
whynot=string.gsub(whynot,"$PERC",tostring(Var2 or "??"))
elseif Var1==QDKP2LOG_NODKP_LIMIT then
whynot= QDKP2_LOC_NODKP_NetLimit
elseif Var1==QDKP2LOG_NODKP_IMSTART then
whynot= QDKP2_LOC_NODKP_IMStart
elseif Var1==QDKP2LOG_NODKP_IMSTOP then
whynot= QDKP2_LOC_NODKP_IMStop
elseif Var1==QDKP2LOG_NODKP_ALT then
whynot= QDKP2_LOC_NODKP_Alt
elseif Var1==QDKP2LOG_NODKP_STANDBY then
whynot= QDKP2_LOC_NODKP_Standby
elseif Var1==QDKP2LOG_NODKP_EXTERNAL then
whynot= QDKP2_LOC_NODKP_External
else
whynot= QDKP2_LOC_NODKP_Generic
end
if gained then
if reason then
if RaidAw and not MainEntry then
output = output .. QDKP2_LOC_NoDKPRaidReas
else
output = output .. QDKP2_LOC_NoDKPZSReas
end
output = string.gsub(output,"$REASON",reason)
else
if RaidAw and not MainEntry then
output = output .. QDKP2_LOC_NoDKPRaid
else
output = output .. QDKP2_LOC_NoDKPZS
end
end
local gainTxt=tostring(Ngained)
if Mod and Mod ~= 100 then gainTxt=gainTxt.."x"..tostring(Mod).."%%"; end
output = string.gsub(output,"$AMOUNT",gainTxt)
elseif hours then
output = output .. QDKP2_LOC_NoTick
end
if ZeroSum then
local giver=""
if AltLinkedName then giver=AltLinkedName.." ("..LinkedName..")"
elseif LinkedName then giver=LinkedName
end
output=string.gsub(output,"$GIVER",giver)
end
output = string.gsub(output,"$WHYNOT",whynot)
else
output = output..reason
end
if not output or string.len(output)==0 then output="<NIL>"; end
return output
end
--dummy of GetModEntryText,
--Returns the description of the last log entry of name.
--session is optional.
function QDKP2log_GetLastLogText(name,session)
local Log=QDKP2log_GetLastLog(name,session)
return QDKP2log_GetModEntryText(Log,name=='RAID')
end
local LogColors={}
LogColors.Default={r=1,g=1,b=1}
LogColors.NegativeDKP={r=1,g=0.3,b=0.3}
LogColors.PositiveDKP={r=0,g=1,b=0}
LogColors.LostDKP={r=0.6,g=0.6,b=0.6}
LogColors[QDKP2LOG_EVENT]={r=1,g=1,b=1}
LogColors[QDKP2LOG_CONFIRMED]={r=0.3,g=1,b=0.3}
LogColors[QDKP2LOG_CRITICAL]={r=1,g=0.3,b=0.3}
LogColors[QDKP2LOG_MODIFY]={r=0.4,g=1,b=1}
LogColors[QDKP2LOG_JOINED]={r=1,g=0.6,b=0}
LogColors[QDKP2LOG_LEFT]={r=1,g=0.6,b=0}
LogColors[QDKP2LOG_LOOT]={r=1,g=1,b=0}
LogColors[QDKP2LOG_ABORTED]={r=0.6,g=0.6,b=0.6}
LogColors[QDKP2LOG_NODKP]={r=1,g=0.5,b=0.5}
LogColors[QDKP2LOG_BOSS]={r=1,g=1,b=1}
LogColors[QDKP2LOG_BIDDING]={r=1,g=0.3,b=1}
LogColors[QDKP2LOG_SESSION]={r=1,g=1,b=0.5}
LogColors[QDKP2LOG_INVALID]={r=1,g=1,b=1}
LogColors[QDKP2LOG_EXTERNAL]={r=1,g=1,b=1}
function QDKP2log_GetEntryColor(type)
return (LogColors[type] or LogColors.Default)
end
---------------------------------- Low level Retrivers ---------------------------------------------
function QDKP2log_GetData(Log)
-- retruns all the raw data contained in a log
-- Type,Time,Action,Version,Amounts,ModBy,ModDate,Flags,Creator = QDKP2log_GetData(Log)
return Log[1],Log[2],Log[3],Log[4],Log[5],Log[6],Log[7],Log[8],Log[9]
end
--Returns the type of the log
function QDKP2log_GetType(Log)
return Log[QDKP2LOG_FIELD_TYPE] or QDKP2LOG_INVALID
end
function QDKP2log_GetTS(Log) -- returns the TimeStamp of Log
-- Returns the TimeStamp of log (returns 0 if is nil. raise an error if Log is nil.)
return Log[QDKP2LOG_FIELD_TIME] or 0
end
function QDKP2log_GetModEntryDateTime(Log)
--returns the date and time for the log voice passed
return QDKP2_GetDateTextFromTS(QDKP2log_GetTS(Log))
end
function QDKP2log_GetReason(Log)
--REturns the reason field of Log
return Log[QDKP2LOG_FIELD_ACTION]
end
function QDKP2log_GetAmounts(Log)
--Returns the amounts in the log
--gain,spend,hours,Coeff,Ngain = QDKP2log_GetAmounts(log)
--where gain is the effective gained amount modified by Mod, and
--Ngain is the nominal amount.
local Undo = Log[QDKP2LOG_FIELD_AMOUNTS]
if not Undo or type(Undo)~="table" then
QDKP2_Debug(1,"Logging","Asking the amounts for a log entry withouth Undo field!")
return
end
--print("{"..tostring(Undo[1])..","..tostring(Undo[2])..","..tostring(Undo[3])..","..tostring(Undo[4]).."}")
local Ngain=Undo[1]
local spend=Undo[2]
local hours=Undo[3]
local Coeff=Undo[4]
local gain
if Ngain then gain = RoundNum(Ngain * (Coeff or 100)/100); end
return gain,spend,hours,Coeff,Ngain
end
--returns the net change of given log entry.
function QDKP2log_GetChange(LogEntry)
LogEntry,link=QDKP2log_CheckLink(LogEntry)
local Type=LogEntry[QDKP2LOG_FIELD_TYPE]
if not QDKP2_IsActiveDKPEntry(Type) then return; end
local Total,Spent=QDKP2log_GetAmounts(LogEntry)
return (Total or 0)-(Spent or 0)
end
function QDKP2log_GetFlags(Log)
--Extracts the flags from the number in QDKP2LOG_FIELD_FLAGS. Extracts up to 4 bits and 2 bytes.
if not Log then return; end
local Data=Log[QDKP2LOG_FIELD_FLAGS] or 0
Data=math.floor(Data)
local Bit0,Bit1,Bit2,Bit3,Var1,Var2
Bit0 = bit.band(Data,0x00001);
Bit1 = bit.band(Data,0x00002);
Bit2 = bit.band(Data,0x00004);
Bit3 = bit.band(Data,0x00008);
Var1 = bit.band(Data,0x00FF0);
Var2 = bit.band(Data,0xFF000);
if Bit0==0 then Bit0=false; end
if Bit1==0 then Bit1=false; end
if Bit2==0 then Bit2=false; end
if Bit3==0 then Bit3=false; end
return Bit0,Bit1,Bit2,Bit3,bit.rshift(Var1,4),bit.rshift(Var2,12)
end
function QDKP2log_GetCreator(Log,SID)
--returns the name of the creator of the log. Needs SID
--Returns the name of the last editor of the log. Needs SID.
local name=Log[QDKP2LOG_FIELD_CREATOR]
if name then return name; end
local _,_,name = QDKP2_GetSessionInfo(SID)
return name
end
function QDKP2log_GetModder(Log, SID)
--Returns the name of the last editor of the log. Needs SID.
local name=Log[QDKP2LOG_FIELD_MODBY] or QDKP2log_GetCreator(Log,SID)
return name
end
function QDKP2log_GetModDate(Log,SID)
return Log[QDKP2LOG_FIELD_MODDATE]
end
------------- Modificators
function QDKP2log_UnDoEntry(name,Log,SID,onofftog)
-- Given a log entry, toggle between ACTIVE and INACTIVE and manages the DKPs.
-- It manages linked entries (raid awards, zerosums) activating/deactivating them too.
-- QDKP2log_UnDoEntry(name,Log,SID,onofftog)
-- name: The name of the player that owns the log.
-- Log: The log entry to activate/deactivate
-- onofftog: Optionals, can be "on" and "off". If nil will cause a toggle.
QDKP2_Debug(2,"Logging","UnDoEntry Called for "..tostring(name)..". Log="..tostring(Log)..", SID="..SID..", onoff="..tostring(onofftog))
local LogType = Log[QDKP2LOG_FIELD_TYPE]
if onofftog=="on" and LogType~=QDKP2LOG_ABORTED then return
elseif onofftog=="off" and LogType==QDKP2LOG_ABORTED then return
elseif LogType==QDKP2LOG_ABORTED then onofftog="on"
else onofftog="off"
end
local RaidAw,ZeroSum,MainEntry,Bit3,Var1,Var2=QDKP2log_GetFlags(Log)
if MainEntry then
end
local addsub
if QDKP2_IsDKPEntry(LogType) then
local DTotal, DSpent, DHours, DMod, NTotal = QDKP2log_GetAmounts(Log)
DMod=(DMod or 100)/100
local SetTotal = NTotal
local SetSpent = DSpent
local SetHours = DHours
local DeltaDKP = 0
if onofftog == "on" then addsub = 1
elseif onofftog == "off" then addsub = -1
end
if DTotal then
DTotal = DTotal * addsub
DeltaDKP = DTotal
else
SetTotal=0
end
if DSpent then
DSpent = DSpent * addsub
DeltaDKP = DeltaDKP - DSpent
else
SetSpent=0
end
if DHours then
DHours = DHours *addsub
else
SetHours=0
end
local ChDeltaDKP=DeltaDKP
if name~="RAID" then
local maxNet=QDKP2_GetNet(name)
local minNet=QDKP2_GetNet(name)
if maxNet+DeltaDKP>QDKP2_MAXIMUM_NET then
QDKP2_Debug(2,"Logging","Limiting the gain because it would break the max Net limit")
SetTotal=RoundNum((SetTotal-(maxNet+DeltaDKP-QDKP2_MAXIMUM_NET)/DMod))
DTotal=RoundNum(SetTotal * DMod * addsub)
DeltaDKP=QDKP2_MAXIMUM_NET - maxNet
end
if minNet+DeltaDKP<QDKP2_MINIMUM_NET then
QDKP2_Debug(2,"Logging","Limiting the loss because it would break the min Net limit")
SetSpent = SetSpent + (minNet+DeltaDKP-QDKP2_MINIMUM_NET)
DSpent=SetSpent * addsub
DeltaDKP=QDKP2_MINIMUM_NET-minNet
end
end
ChDeltaDKP= ChDeltaDKP-DeltaDKP
QDKP2log_BackupSave(SID,name,Log)
-- Modifying the log entry --
if name ~="RAID" then
if SetTotal==0 then SetTotal=nil; end
if SetSpent==0 then SetSpent=nil; end
if SetHours==0 then SetHours=nil; end
QDKP2log_SetAmountsField(Log, {SetTotal,SetSpent,SetHours})
local newChange=0
QDKP2_AddTotals(name, DTotal, DSpent, DHours, nil, nil, nil, true)
end
local newType
if addsub==1 then
newType = QDKP2LOG_MODIFY
else
newType = QDKP2LOG_ABORTED
end
QDKP2log_SetTypeField(Log, newType)
local RaidAw,ZeroSum,MainEntry=QDKP2log_GetFlags(Log)
if MainEntry then --update linked dkp entries
QDKP2log_UpdateLinkedDKPLog(name,Log,SID)
end
QDKP2_Debug(3,"Logging","UnDo Entry finished for "..name)
end
end
function QDKP2log_SetEntry(name,Log,SID,newGained,newSpent,newHours,newCoeff,newReason, Activate, NoIncreaseVersion, NoUpdateZS)
-- Function to change a DKP entry's amounts.
-- It will take care of any linked entry (raid awards, zerosums,...)
-- QDKP2log_SetLogEntry(name,Log,newGained,newSpent,newHours,newMod,newReason, Activate, NoProcessZs)
-- name: The name of the player that owns the log
-- Log: The log to modify.
-- SID: The SID of the session the entry is.
-- newGained,newSpent,newHours, newReason, newMod: Guess wha! If nil, they won't be changed.
QDKP2_Debug(2,"Logging","SetEntry called for "..tostring(name)..", log "..tostring(Log).." of session "..tostring(SID)..". NewUndo: "..tostring(newGained)..","..tostring(newSpent)..","..tostring(newHours)..","..tostring(newCoeff))
if not name then
QDKP2_Debug(1,"Logging","Calling SetEntry with nil name")
return
elseif not Log then
QDKP2_Debug(1,"Logging","Calling SetEntry with nil Log")
return
end
if not SID then
QDKP2_Debug(1,"Logging","SetEntry called with nil SID")
return
end
local SessList,SessName,SessMantainer=QDKP2_GetSessionInfo(SID)
local LogType = QDKP2log_GetType(Log)
local RaidAw,ZeroSum,MainEntry=QDKP2log_GetFlags(Log)
name=QDKP2_GetMain(name)
local oldGained
local oldSpent
local oldHours
local oldMod
local oldCoeff,oldNGained
oldGained, oldSpent, oldHours, oldCoeff, oldNGained = QDKP2log_GetAmounts(Log)
oldGained=oldGained or 0
oldSpent=oldSpent or 0
oldHours=oldHours or 0
oldNGained=oldNGained or 0
oldCoeff=oldCoeff or 100
if QDKP2_IsNODKPEntry(LogType) then
oldGained=0
oldSpent=0
oldHours=0
oldNGained=0
end
local Dnet = 0
local newNGained
newNGained = tonumber(newGained or oldNGained) or oldNGained
newSpent = tonumber(newSpent or oldSpent) or oldSpent
newHours = tonumber(newHours or oldHours) or oldHours
newCoeff = tonumber(newCoeff or oldCoeff) or oldCoeff
newCoeff100 = newCoeff/100
newGained = RoundNum(newNGained * newCoeff100)
Dnet = newGained - newSpent
if name~="RAID" and QDKP2_IsDKPEntry(LogType) then
local maxNet=QDKP2_GetNet(name)
local minNet=QDKP2_GetNet(name)
--[[
for i=index,1,-1 do
local tmpNet = QDKP2log[name][i][QDKP2LOG_NET]
if tmpNet and tmpNet<minNet then minNet=tmpNet; end
if tmpNet and tmpNet>maxNet then maxNet=tmpNet; end
end
]]-- Disabled. It serachs the maximum and minum net amounts in log history's. Bad for sync.
if maxNet+Dnet>QDKP2_MAXIMUM_NET then
QDKP2_Debug(2,"Logging","Limiting the change because it would break the maximum net DKP amount")
newNGained=RoundNum((newNGained-(maxNet+Dnet-QDKP2_MAXIMUM_NET)/newCoeff100))
newGained=newNGained * newCoeff100
Dnet=QDKP2_MAXIMUM_NET-maxNet
end
if minNet+Dnet<QDKP2_MINIMUM_NET then
QDKP2_Debug(2,"Logging","Limiting the change because it would break the minimum net DKP amount")
newSpent=newSpent+((minNet+Dnet)-QDKP2_MINIMUM_NET)
Dnet=QDKP2_MINIMUM_NET-minNet
end
end
local Dgained = newGained - oldGained
local Dspent = newSpent - oldSpent
local Dhours = newHours - oldHours
if (Activate or not QDKP2_IsDeletedEntry(LogType)) and QDKP2_IsDKPEntry(LogType) and name ~= "RAID" then
QDKP2_AddTotals(name, Dgained, Dspent, Dhours, nil, nil, nil, true)
end
if not NoIncreaseVersion and LogType~=QDKP2LOG_MODIFY then
QDKP2log_BackupSave(SID,name,Log)
elseif NoIncreaseVersion and LogType==QDKP2LOG_MODIFY then
QDKP2_Msg(3,"Logging","Updating log's backup to match new initial values.")
QDKP2log_BackupDel(SID,name,Log)
QDKP2log_BackupSave(SID,name,Log,true)
end
if Dgained ~= 0 or Dspent ~= 0 or math.abs(Dhours)>0.09 then
if LogType == QDKP2LOG_CONFIRMED or Activate then
QDKP2log_SetTypeField(Log,QDKP2LOG_MODIFY,NoIncreaseVersion)
end
end
if newReason and (not ZeroSum or MainEntry) then
if newReason=="" then newReason=nil; end
QDKP2log_SetReasonField(Log, newReason, NoIncreaseVersion)
end
QDKP2log_SetAmountsField(Log,{newNGained,newSpent,newHours,newCoeff},NoIncreaseVersion)
--this is to fix those log entries with a redundant MODBY name.
if Log[QDKP2LOG_FIELD_MODBY]==SessMantainer then
Log[QDKP2LOG_FIELD_MODBY]=nil
end
if MainEntry and not NoUpdateZS then --update linked dkp entries
QDKP2log_UpdateLinkedDKPLog(name,Log,SID,NoIncreaseVersion)
end
QDKP2_Debug(3,"Logging","SetEntry successfully finished for "..name)
end
function QDKP2log_AwardLinkedEntry(name,Log,SID,todo,ReasonCode)
--Sets a slave link DKP entry a award or a not-award.
--name, Log, SID: Self descripting
--todo: can be 'award', 'not-award' and 'toggle'
--ReasonCode: The reason code (optional). Won't be touched if nil
todo=todo or 'toggle'
local RaidAw,ZeroSum,MainEntry,B3,V0,V1=QDKP2log_GetFlags(Log)
if (not ZeroSum and not RaidAw) or MainEntry then
QDKP2_Debug(1,"Logging","AwardLinkedEntry called with a log that isn't a linked log entry")
return
end
QDKP2log_BackupSave(SID,name,Log)
local Type=QDKP2log_GetType(Log)
if todo=='award' and QDKP2_IsNODKPEntry(Type) then
QDKP2log_SetTypeField(Log, QDKP2LOG_ABORTED)
elseif todo=='not-award' and not QDKP2_IsNODKPEntry(Type) then
QDKP2log_UnDoEntry(name,Log,SID,'off')
QDKP2log_SetTypeField(Log, QDKP2LOG_NODKP)
if not V0 then ReasonCode=QDKP2LOG_NODKP_MANUAL; end --default reason for entries that are switched off (Manually removed)
if ReasonCode then
QDKP2log_SetFlags(Log,RaidAw,ZeroSum,MainEntry,B3,ReasonCode,V1)
end
elseif todo=='toggle' then
if QDKP2_IsNODKPEntry(Type) then QDKP2log_AwardLinkedEntry(name,Log,SID,'award',ReasonCode)
else QDKP2log_AwardLinkedEntry(name,Log,SID,'not-award',ReasonCode)
end
else
QDKP2_Debug(1,"Logging","AwardLinkedEntry got an invalid todo.")
return
end
local vLog,vSID,vPlayer=QDKP2log_GetMainDKPEntry(Log,SID)
QDKP2log_UpdateLinkedDKPLog(vPlayer, vLog, vSID)
end
--[[
function QDKP2log_ToggleAward(name,Log,SID,onofftog)
--Function that, given a slave DKP entry log, puts it from active to excluded state back and forth.
if not name then
QDKP2_Debug(1,"Log","Can't toggle award state: name is nil.")
return
elseif not Log then
QDKP2_Debug(1,"Log","Can't toggle award state: Log is nil.")
return
end
local _=QDKP2log_BackupSave(SID,name,Log) or QDKP2_Msg(1,"Logging","Couldn't update the log's backup.")
local Type=QDKP2log_GetType(Log)
local B0,B1,B2,B3,V0,V1=QDKP2log_GetFlags(Log)
if QDKP2_IsNODKPEntry(Type) then
QDKP2_Debug(2,"Log","Enabling Award for "..tostring(name)..", session="..tostring(SID))
QDKP2log_SetTypeField(Log, QDKP2LOG_ABORTED)
else
QDKP2_Debug(2,"Log","Disabling Award for "..tostring(name)..", session="..tostring(SID))
else
]]--
--This updates a linked DKP entry (Raid Award or Zerosum).
--MUST be called everytime you modify a main DKP entry.
function QDKP2log_UpdateLinkedDKPLog(name,Log,SID,NoIncreaseVersion)
if not (type(name)=='string') then
QDKP2_Debug(1,"Logging", 'UpdateLinkedDKPLog called with invalid name: '..tostring(name))
return
end
if not (type(Log)=='table') then
QDKP2_Debug(1,"Logging", 'UpdateLinkedDKPLog called with invalid log')
return
end
if not (type(SID)=='string') then
QDKP2_Debug(1,"Logging", 'UpdateLinkedDKPLog called with SID that is not a string')
return
end
local LogType = Log[QDKP2LOG_FIELD_TYPE]
if not QDKP2_IsDKPEntry(LogType) then
QDKP2_Debug(1,"Logging","Calling UpdateLinkedDKPLog with a log that is not a main DKP entry.")
return
end
local RaidAw,ZeroSum,MainEntry,Bit3,Var1,Var2=QDKP2log_GetFlags(Log)
local newGained,newSpent,newHours=QDKP2log_GetAmounts(Log)
local newReason=QDKP2log_GetReason(Log)
local nameList, logList
if RaidAw and MainEntry then
--RaidAward entry
QDKP2_Debug(3,"Logging","Given log is a raid award main entry. Propagating the change to all the child entries.")
nameList, logList =QDKP2log_GetList(SID,Log[QDKP2LOG_FIELD_TIME])
for i=1, #nameList do
local name2=nameList[i]
local log2 = logList[i]
if not QDKP2_IsAlt(name2) and name2 ~= name then
QDKP2log_SetEntry(name2,log2,SID,newGained or 0,newSpent or 0,newHours or 0,nil,newReason or '',nil,NoIncreaseVersion)
end
end
elseif (ZeroSum and MainEntry) then
--Zerosum entry
QDKP2_Debug(3,"Logging","Given log is a zerosum main entry. Propagating the change to all the child entries.")
QDKP2_ZeroSum_Update(name,Log,SID,NoIncreaseVersion)
end
--this updates the status, active or deactive
if not nameList then
nameList, logList =QDKP2log_GetList(SID,Log[QDKP2LOG_FIELD_TIME])
end
for i=1, #nameList do
local name2=nameList[i]
if not QDKP2_IsAlt(name2) and name2~=name then
local log2 = logList[i]
log2type=QDKP2log_GetType(log2)
local todo
if LogType == log2type then todo=nil --all ok
elseif QDKP2_IsActiveDKPEntry(LogType) and not QDKP2_IsActiveDKPEntry(log2type) then todo='on'
elseif not QDKP2_IsActiveDKPEntry(LogType) and QDKP2_IsActiveDKPEntry(log2type) then todo='off'
end
if todo then QDKP2log_UnDoEntry(name2,log2,SID,todo); end
end
end
return true
end
--Change type
function QDKP2log_SetTypeField(Log, newValue, NoIncreaseVersion)
local oldValue=Log[QDKP2LOG_FIELD_TYPE]
if oldValue ~= newValue then
Log[QDKP2LOG_FIELD_TYPE]=newValue or QDKP2LOG_INVALID
if not NoIncreaseVersion then QDKP2log_LogEntryModified(Log); end
end
end
--Change Reason
function QDKP2log_SetReasonField(Log, newValue, NoIncreaseVersion)
local oldValue=Log[QDKP2LOG_FIELD_ACTION]
if oldValue ~= newValue then
Log[QDKP2LOG_FIELD_ACTION]=newValue
if not NoIncreaseVersion then QDKP2log_LogEntryModified(Log); end
end
end
--Change amounts
function QDKP2log_SetAmountsField(Log, newValue, NoIncreaseVersion)
if not newValue or type(newValue)~="table" then
QDKP2_Debug(1,"Logging","SetAmountsField called without a valid newValue")
return
end
local oldValue=Log[QDKP2LOG_FIELD_AMOUNTS] or {}
newValue={newValue[1] or oldValue[1],newValue[2] or oldValue[2],newValue[3] or oldValue[3],newValue[4] or oldValue[4]}
if newValue[1]==0 then newValue[1]=nil; end
if newValue[2]==0 then newValue[2]=nil; end
if newValue[3]==0 then newValue[3]=nil; end
if newValue[4]==100 then newValue[4]=nil; end
Log[QDKP2LOG_FIELD_AMOUNTS]=newValue
if not NoIncreaseVersion then QDKP2log_LogEntryModified(Log); end
end
--Change flags/Variables.
function QDKP2log_SetFlags(Log,B0,B1,B2,B3,V0,V1)
local flags=QDKP2log_PacketFlags(B0,B1,B2,B3,V0,V1)
Log[QDKP2LOG_FIELD_FLAGS]=flags
QDKP2log_LogEntryModified(Log)
end
---------------Utilities-------------------------
function QDKP2log_GetStr(Log)
local reason=Log[3]
local undo=Log[5]
local flags=Log[8]
if flags then flags=string.format("%X",flags)
else flags=''
end
if undo then
undo=tostring(undo[1])..","..tostring(undo[2])..","..tostring(undo[3])
undo=string.gsub(undo,'nil','')
else undo=''
end
if reason then reason=string.gsub(reason,"§","S")
else reason=''
end
local out=tostring(Log[1] or '')..'§'..
tostring(Log[2] or '')..'§'..
reason..'§'..
tostring(Log[4] or '')..'§'..
undo..'§'..
tostring(Log[6] or '')..'§'..
tostring(Log[7] or '')..'§'..
flags..'§'..
tostring(Log[9] or '')..'§'..
tostring(Log[10] or '')
return out
end
function QDKP2log_GetLogFromString(str)
local _,_,Type,TS,Act,Ver,UndoS,ModBy,ModDate,Flags,Own,Sign=string.find(
'([^§]*)§([^§]*)§([^§]*)§([^§]*)§([^§]*)§([^§]*)§([^§]*)§([^§]*)§([^§]*)§([^§]*)')
Type=tonumber(Type) or QDKP2LOG_INVALID
TS=tonumber(TS)
Ver=tonumber(Ver)
local undo,_={}
_,_,undo[1],undo[2],undo[3]=string.find(UndoS,'([^,]*),([^,]*),([^,]*)')
undo=table.foreach(undo,tonumber)
end
function QDKP2log_PacketFlags(Bit0,Bit1,Bit2,Bit3,Val1,Val2)
--Packets the flags into a single integer
local out=0
if Bit0 then out=out+1; end
if Bit1 then out=out+2; end
if Bit2 then out=out+4; end
if Bit3 then out=out+8; end
if Val1 then
Val1=math.floor(Val1)
if Val1<0 then Val1=0
elseif Val1>255 then Val1=255
end
out=out+Val1*16
end
if Val2 then
Val2=math.floor(Val2)
if Val2<0 then Val2=0
elseif Val2>255 then Val2=255
end
out=out+Val2*4096
end
return out
end
function QDKP2log_CheckLink(Log)
-- Returns the linked log if is a link, and the log itself if not.
-- As second output returns true if the log is a link, false if is not.
if QDKP2log_GetType(Log)==QDKP2LOG_LINK then
return QDKP2log_FindLink(Log), true
else
return Log, false
end
end
--Updates the modification timer and name.
function QDKP2log_LogEntryModified(Log)
QDKP2_Debug(2,"Logging","Increasing mod version of log "..tostring(Log))
local Version=Log[QDKP2LOG_FIELD_VERSION]
if not Version then
QDKP2_Debug(1,"Logging","You can't increase the version of a not-versioned entry!")
return
end
Log[QDKP2LOG_FIELD_MODDATE]=QDKP2_Time()
Log[QDKP2LOG_FIELD_VERSION]=Version + 1
Log[QDKP2LOG_FIELD_SIGN]=nil
if Log[QDKP2LOG_FIELD_CREATOR]==QDKP2_PLAYER_NAME_12 then
Log[QDKP2LOG_FIELD_MODBY]=nil
else
Log[QDKP2LOG_FIELD_MODBY]=QDKP2_PLAYER_NAME_12
end
end
function QDKP2_ZeroSum_Update(giverName,mainLog,SID,NoIncreaseVersion)
--This is called when the zerosum main entry is changed.
QDKP2_Debug(2, "RaidAward", "Updating Zerosum entry "..tostring(mainLog).." by "..tostring(giverName).." in session "..tostring(SID))
if not giverName then
QDKP2_Debug(1, "RaidAward", "Calling Update_Zerosum with nil giverName")
return
end
if not mainLog then
QDKP2_Debug(1, "RaidAward", "Calling Update_Zerosum with nil mainLog")
return
end
if not SID then
QDKP2_Debug(1,"RaidAward", "Calling Update_Zerosum with nil SID")
return
end
local SessionLog=QDKP2log[SID]
local Amount=mainLog[QDKP2LOG_FIELD_AMOUNTS][2]
local timeStamp=QDKP2log_GetTS(mainLog)
QDKP2_Debug(3, "RaidAward", tostring(Amount).." DKP to share")
local nameList, LogList = QDKP2log_GetIndexList(SID, timeStamp)
local whoGet={}
local whoGetLog={}
local whoDontGet={}
local whoDontGetLog={}
for i=1,table.getn(nameList) do
local Name=nameList[i]
local NameLog=SessionLog[Name]
if Name ~= "RAID" and (Name ~= giverName or QDKP_GIVEZSTOLOOTER) then
local index=LogList[i]
local Log=NameLog[index]
local Type=QDKP2log_GetType(Log)
if QDKP2_IsDKPEntry(Type) then
table.insert(whoGet,Name)
table.insert(whoGetLog,Log)
else
table.insert(whoDontGet,Name)
table.insert(whoDontGetLog,Log)
end
end
end
local Sharer = table.getn(whoGet)
if Sharer==0 then
QDKP2_Msg(QDKP2_COLOR_YELLOW.."Warning: No players eligible for the share found. Shared DKP will be destroyed.")
end
QDKP2_Debug(3, "RaidAward", tostring(Sharer).." players are elegible for the share")
if Sharer > 0 then
--here i use a iterative system to get the value that best shares the given DKP amount.
local Share = 0 --initial values
local Total = 0
local oldShare, oldTotal
local iter=0
while true do
local iterPrec=Share
if not oldShare then
Share=RoundNum(Amount/Sharer) --prima iterata
elseif oldTotal==Total then --this is to avoid division by zero, but should never happen.
--pass
else
local x1=Amount - oldTotal
local x2=Amount - Total
local y1=oldShare
local y2=Share
Share=RoundNum(((x2*y1)-(x1*y2))/(x2-x1)) --newton's iteration
end
QDKP2_Debug(3,"RaidAward","UpdateZS - It. #"..tostring(iter+1)..", Share="..tostring(Share))
if (Share==oldShare or Total==oldTotal) and iter>0 then
QDKP2_Debug(2,"RaidAward","UpdateZS - Found aprox root after "..tostring(iter+1).." it. : S="..tostring(Share))
break
elseif iter>=20 then
QDKP2_Message("Zerosum Award: some DKP couldn't be shared. (giving "..tostring(oldTotal).." over "..tostring(Amount).." DKP.")
end
oldShare=iterPrec
oldTotal=Total
Total=0
for i=1,Sharer do
local Name=whoGet[i]
local Log=whoGetLog[i]
QDKP2_Debug(3,"RaidAward",Name.." gets the share.")
QDKP2log_SetEntry(Name,Log,SID,Share,nil,nil,nil,nil,nil,NoIncreaseVersion,true)
local gain,spend=QDKP2log_GetAmounts(Log)
Total=Total+(gain or 0)
end
if Total==Amount then
QDKP2_Debug(2,"RaidAward","UpdateZS - Found precise root after"..tostring(iter+1).." it. :S="..tostring(Share))
break
end
iter=iter+1
end
end
local ToNoDKP=math.ceil(Amount/(Sharer+1))
for i=1,table.getn(whoDontGet) do
local Name=whoDontGet[i]
local Log=whoDontGetLog[i]
local Undo=Log[QDKP2LOG_FIELD_AMOUNTS]
local Reason=Log[QDKP2LOG_FIELD_ACTION]
QDKP2_Debug(3,"RaidAward",Name.." loses the share ("..tostring(ToNoDKP).." DKP)")
QDKP2log_SetEntry(Name,Log,SID,ToNoDKP,nil,nil,nil,nil,nil,NoIncreaseVersion,true)
end
end
function QDKP2_GetAwardSpendText(gained, spent, hours, Mod)
--Returns a "Gains x and Spends y" report.
if gained then
if spent then
if hours then
output=QDKP2_LOC_GainsSpendsEarns
else
output=QDKP2_LOC_GainsSpends
end
else
if hours then
output=QDKP2_LOC_GainsEarns
else
output=QDKP2_LOC_Gains
end
end
else
if spent then
if hours then
output=QDKP2_LOC_SpendsEarns
else
output=QDKP2_LOC_Spends
end
else
if hours then
output=QDKP2_LOC_Earns
else
output=""
end
end
end
if gained then
gained=tostring(gained)
if Mod and Mod ~= 100 then
gained=gained.."x"..tostring(Mod).."%%%%"
end
output=string.gsub(output,"$GAIN",gained)
end
if spent then
output=string.gsub(output,"$SPEND",spent)
end
if hours then
output=string.gsub(output,"$HOUR",hours)
end
return output
end
| gpl-3.0 |
MikeMcShaffry/gamecode3 | Dev/Source/3rdParty/LuaPlus/Src/Modules/luaexpat/tests/test-lom.lua | 18 | 1389 | #!/usr/local/bin/lua
local lom = require "lxp.lom"
local tests = {
[[<abc a1="A1" a2="A2">inside tag `abc'</abc>]],
[[<qwerty q1="q1" q2="q2">
<asdf>some text</asdf>
</qwerty>]],
}
function table._tostring (tab, indent, spacing)
local s = {}
spacing = spacing or ""
indent = indent or "\t"
table.insert (s, "{\n")
for nome, val in pairs (tab) do
table.insert (s, spacing..indent)
local t = type(nome)
if t == "string" then
table.insert (s, string.format ("[%q] = ", tostring (nome)))
elseif t == "number" or t == "boolean" then
table.insert (s, string.format ("[%s] = ", tostring (nome)))
else
table.insert (s, t)
end
t = type(val)
if t == "string" or t == "number" then
table.insert (s, string.format ("%q", val))
elseif t == "table" then
table.insert (s, table._tostring (val, indent, spacing..indent))
else
table.insert (s, t)
end
table.insert (s, ",\n")
end
table.insert (s, spacing.."}")
return table.concat (s)
end
function table.print (tab, indent, spacing)
io.write (table._tostring (tab, indent, spacing))
end
for i, s in ipairs(tests) do
--s = string.gsub (s, "[\n\r\t]", "")
local ds = assert (lom.parse ([[<?xml version="1.0" encoding="ISO-8859-1"?>]]..s))
print(table._tostring(ds))
end
| lgpl-2.1 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/repairBattlefieldStructure.lua | 4 | 2171 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
RepairBattlefieldStructureCommand = {
name = "repairbattlefieldstructure",
}
AddCommand(RepairBattlefieldStructureCommand)
| agpl-3.0 |
p0pr0ck5/lua-resty-waf | t/translation/18_translate.lua | 1 | 3658 | describe("translate", function()
local lib = require "resty.waf.translate"
local t = lib.translate
local chains, errs
before_each(function()
chains = {}
errs = nil
end)
it("single valid rule with no errors", function()
local raw = {
[[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]]
}
assert.has.no_errors(function() chains, errs = t(raw, opts) end)
assert.is_nil(errs)
end)
it("single invalid rule with errors", function()
local raw = {
[[SecRule DNE "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]]
}
assert.has.no_errors(function() chains, errs = t(raw) end)
assert.is_not_nil(errs)
end)
it("forces translation of a single valid rule with errors", function()
local raw = {
[[SecRule ARGS|DNE "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]]
}
local opts = { force = true }
assert.has.no_errors(function() chains, errs = t(raw, opts) end)
assert.is_nil(errs)
assert.is.same(#chains.access[1].vars, 1)
end)
it("single valid rule with invalid action", function()
local raw = {
[[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg',foo"]]
}
assert.has.no_errors(function() chains, errs = t(raw) end)
assert.is_not_nil(errs)
end)
it("loose single valid rule with invalid action", function()
local raw = {
[[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg',foo"]]
}
local opts = { loose = true }
assert.has.no_errors(function() chains, errs = t(raw, opts) end)
assert.is_nil(errs)
end)
it("single valid rule with data file pattern", function()
local raw = {
[[SecRule REMOTE_ADDR "@ipMatchFromFile ips.txt" ]] ..
[[ "id:12345,phase:2,deny,msg:'dummy msg'"]]
}
local opts = { path = require("lfs").currentdir() .. '/t/data' }
assert.has.no_errors(function() chains, errs = t(raw, opts) end)
assert.is_nil(errs)
assert.is.same(chains.access[1].pattern, {
'1.2.3.4', '5.6.7.8', '10.10.10.0/24'
})
end)
it("single invalid rule with data file pattern", function()
local raw = {
[[SecRule REMOTE_ADDR "@ipMatchFromFile ips.txt" ]] ..
[[ "id:12345,phase:2,deny,msg:'dummy msg'"]]
}
local opts = { path = require("lfs").currentdir() .. '/t/dne' }
assert.has.no_errors(function() chains, errs = t(raw, opts) end)
assert.is_not_nil(errs)
assert.is.same(#chains.access, 0)
end)
it("multiple rules in the same phase", function()
local raw = {
[[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]],
[[SecRule ARGS "foo" "id:12346,phase:2,deny,msg:'dummy msg'"]]
}
local funcs = { 'clean_input', 'tokenize', 'parse_tokens',
'build_chains', 'translate_chains' }
local s = {}
for i = 1, #funcs do
local func = funcs[i]
s[func] = spy.on(lib, func)
end
assert.has.no_errors(function() chains, errs = t(raw, opts) end)
assert.is_nil(errs)
assert.is.same(#chains.access, 2)
for i = 1, #funcs do
local func = funcs[i]
assert.spy(s[func]).was.called()
end
end)
it("multiple rules in different phases", function()
local raw = {
[[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]],
[[SecRule ARGS "foo" "id:12346,phase:3,deny,msg:'dummy msg'"]]
}
local funcs = { 'clean_input', 'tokenize', 'parse_tokens',
'build_chains', 'translate_chains' }
local s = {}
for i = 1, #funcs do
local func = funcs[i]
s[func] = spy.on(lib, func)
end
assert.has.no_errors(function() chains, errs = t(raw, opts) end)
assert.is_nil(errs)
assert.is.same(#chains.access, 1)
assert.is.same(#chains.header_filter, 1)
for i = 1, #funcs do
local func = funcs[i]
assert.spy(s[func]).was.called()
end
end)
end)
| gpl-3.0 |
amirhoseinkarimi2233/uzzbot | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
tfagit/telegram-bot | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
ozhanf/ozhan | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
flandr/thrift | lib/lua/TSocket.lua | 113 | 2996 | ---- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'TTransport'
require 'libluasocket'
-- TSocketBase
TSocketBase = TTransportBase:new{
__type = 'TSocketBase',
timeout = 1000,
host = 'localhost',
port = 9090,
handle
}
function TSocketBase:close()
if self.handle then
self.handle:destroy()
self.handle = nil
end
end
-- Returns a table with the fields host and port
function TSocketBase:getSocketInfo()
if self.handle then
return self.handle:getsockinfo()
end
terror(TTransportException:new{errorCode = TTransportException.NOT_OPEN})
end
function TSocketBase:setTimeout(timeout)
if timeout and ttype(timeout) == 'number' then
if self.handle then
self.handle:settimeout(timeout)
end
self.timeout = timeout
end
end
-- TSocket
TSocket = TSocketBase:new{
__type = 'TSocket',
host = 'localhost',
port = 9090
}
function TSocket:isOpen()
if self.handle then
return true
end
return false
end
function TSocket:open()
if self.handle then
self:close()
end
-- Create local handle
local sock, err = luasocket.create_and_connect(
self.host, self.port, self.timeout)
if err == nil then
self.handle = sock
end
if err then
terror(TTransportException:new{
message = 'Could not connect to ' .. self.host .. ':' .. self.port
.. ' (' .. err .. ')'
})
end
end
function TSocket:read(len)
local buf = self.handle:receive(self.handle, len)
if not buf or string.len(buf) ~= len then
terror(TTransportException:new{errorCode = TTransportException.UNKNOWN})
end
return buf
end
function TSocket:write(buf)
self.handle:send(self.handle, buf)
end
function TSocket:flush()
end
-- TServerSocket
TServerSocket = TSocketBase:new{
__type = 'TServerSocket',
host = 'localhost',
port = 9090
}
function TServerSocket:listen()
if self.handle then
self:close()
end
local sock, err = luasocket.create(self.host, self.port)
if not err then
self.handle = sock
else
terror(err)
end
self.handle:settimeout(self.timeout)
self.handle:listen()
end
function TServerSocket:accept()
local client, err = self.handle:accept()
if err then
terror(err)
end
return TSocket:new({handle = client})
end
| apache-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/totalHealOther.lua | 3 | 2135 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
TotalHealOtherCommand = {
name = "totalhealother",
}
AddCommand(TotalHealOtherCommand)
| agpl-3.0 |
braydondavis/Nerd-Gaming-Public | resources/NGDrugs/weed_client.lua | 2 | 4343 | drugs.Marijuana = {
loaded = false,
func = { },
var = {
rasta = {
{ 0, 255, 0 },
{ 255, 255, 0 },
{ 255, 0, 0 }
}
},
info = {
timePerDoce = 30,
}
}
local weed = drugs.Marijuana
function weed.func.load ( )
if ( not weed.loaded ) then
weed.loaded = true
if ( not isElement ( weed.var.music ) ) then
weed.var.music = playSound ( "files/weed_music.mp3", true )
end
if ( isElement ( weed.var.volTime ) ) then
destroyElement ( weed.var.volTime )
end
weed.var.recAlpha = 0
weed.var.recMode = "add"
weed.var.imgMode = "small"
weed.var.imgStart = getTickCount ( )
weed.var.vehTick = getTickCount ( )
weed.var.vehColors = { }
for i, v in pairs ( getElementsByType ( "vehicle" ) ) do
weed.var.vehColors [ v ] = { getVehicleColor ( v, true ) }
local r, g, b = unpack ( weed.var.rasta [ math.random ( #weed.var.rasta ) ] )
local r2, g2, b2 = unpack ( weed.var.rasta [ math.random ( #weed.var.rasta ) ] )
setVehicleColor ( v, r, g, b, r2, g2, b2, r, g, b, r2, g2, b2 )
end
setSkyGradient ( 255, 0, 0, 255, 0, 0 )
setGameSpeed ( 0.7 )
weed.var.healthTimer = setTimer ( function ( )
triggerServerEvent ( "NGDrugs:Module->Marijuana:updatePlayerHealth", localPlayer )
end, 1000, 0 )
triggerServerEvent ( "NGDrugs:Module->Core:setPlayerHeadText", localPlayer, "Stoned", { 120, 0, 255 } )
addEventHandler ( "onClientRender", root, weed.func.render )
end
end
function weed.func.unload ( )
if ( weed.loaded ) then
triggerServerEvent ( "NGDrugs:Module->Core:destroyPlayerHeadText", localPlayer )
weed.loaded = false
if ( isElement ( weed.var.music ) ) then
weed.var.volTime = setTimer ( function ( )
if ( not isElement ( weed.var.music ) ) then
killTimer ( weed.var.volTime )
else
local v = getSoundVolume ( weed.var.music )
v = math.round ( v - 0.1, 1 )
if ( v <= 0 ) then
destroyElement ( weed.var.music )
else
setSoundVolume ( weed.var.music, v )
end
end
end, 200, 0 )
end
if ( weed.var.vehColors ) then
for i, v in pairs ( weed.var.vehColors ) do
if ( isElement ( i ) ) then
setVehicleColor ( i, unpack ( v ) )
end
end
end
if ( isElement ( weed.var.healthTimer ) ) then
killTImer ( weed.var.healthTimer )
end
setGameSpeed ( 1 )
resetSkyGradient ( )
removeEventHandler ( "onClientRender", root, weed.func.render )
end
end
function weed.func.render ( )
if ( getTickCount ( ) - weed.var.vehTick >= 3000 ) then
weed.var.vehTick = getTickCount ( )
for i, v in pairs ( getElementsByType ( "vehicle" ) ) do
if ( not weed.var.vehColors [ v ] ) then
weed.var.vehColors [ v ] = { getVehicleColor ( v ) }
end
local r, g, b = unpack ( weed.var.rasta [ math.random ( #weed.var.rasta ) ] )
local r2, g2, b2 = unpack ( weed.var.rasta [ math.random ( #weed.var.rasta ) ] )
setVehicleColor ( v, r, g, b, r2, g2, b2, r, g, b, r2, g2, b2 )
end
end
local a = weed.var.recAlpha
if ( weed.var.recMode == "add" ) then
a = a + 3
if ( a >= 90 ) then
weed.var.recMode = "remove"
end
else
a = a - 3
if ( a <= 10 ) then
weed.var.recMode = "add"
end
end
weed.var.recAlpha = a
dxDrawRectangle ( 0, 0, sx_, sy_, tocolor ( 255, 255, 0, a ) )
local en = weed.var.imgStart + 1200
if ( getTickCount ( ) >= en ) then
weed.var.imgStart = getTickCount ( )
if ( weed.var.imgMode == "small" ) then
weed.var.imgMode = "big"
else
weed.var.imgMode = "small"
end
end
local mode = weed.var.imgMode
local elapsedTime = getTickCount() - weed.var.imgStart
local duration = (weed.var.imgStart+1200) - weed.var.imgStart
local prog = elapsedTime / duration
if ( mode == "small" ) then
w, h, _ = interpolateBetween ( sx_/1.4, sy_/1.4, 0, sx_/2, sy_/2, 0, prog, "InQuad" )
else
w, h, _ = interpolateBetween ( sx_/2, sy_/2, 0, sx_/1.4, sy_/1.4, 0, prog, "OutQuad" )
end
dxDrawImage ( (sx_/2-w/2), (sy_/2-h/2), w, h, "files/weed_icon.png", 0, 0, 0, tocolor ( 255, 255, 255, 120-weed.var.recAlpha ) )
end
drugs.Marijuana = weed
function math.round(number, decimals, method)
decimals = decimals or 0
local factor = 10 ^ decimals
if (method == "ceil" or method == "floor") then return math[method](number * factor) / factor
else return tonumber(("%."..decimals.."f"):format(number)) end
end
| mit |
Blizzard/premake-core | modules/vstudio/tests/sln2005/test_dependencies.lua | 15 | 2331 | --
-- tests/actions/vstudio/sln2005/test_dependencies.lua
-- Validate generation of Visual Studio 2005+ solution project dependencies.
-- Copyright (c) 2009-2012 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("vstudio_sln2005_dependencies")
local sln2005 = p.vstudio.sln2005
--
-- Setup
--
local wks, prj1, prj2
function suite.setup()
p.action.set("vs2005")
wks, prj1 = test.createWorkspace()
uuid "AE61726D-187C-E440-BD07-2556188A6565"
prj2 = test.createproject(wks)
uuid "2151E83B-997F-4A9D-955D-380157E88C31"
prj3 = test.createproject(wks)
uuid "CAA68162-8B96-11E1-8D5E-5885BBE59B18"
links "MyProject"
dependson "MyProject2"
end
local function prepare(language)
prj1.language = language
prj2.language = language
prj2 = test.getproject(wks, 2)
sln2005.projectdependencies(prj2)
prj3.language = language
prj3 = test.getproject(wks, 3)
sln2005.projectdependencies(prj3)
end
--
-- Verify dependencies between C++ projects are listed.
--
function suite.dependency_onCppProjects()
prepare("C++")
test.capture [[
ProjectSection(ProjectDependencies) = postProject
{2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31}
EndProjectSection
]]
end
--
-- Verify dependencies between C# projects are listed.
--
function suite.dependency_onCSharpProjects()
prepare("C#")
test.capture [[
ProjectSection(ProjectDependencies) = postProject
{2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31}
EndProjectSection
]]
end
--
-- Most C# references should go into the project rather than the solution,
-- but until I know the conditions, put everything here to be safe.
--
function suite.dependency_onCSharpProjectsVs2010()
p.action.set("vs2010")
prepare("C#")
test.capture [[
ProjectSection(ProjectDependencies) = postProject
{2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31}
EndProjectSection
]]
end
--
-- Verify dependencies between projects C# are listed for VS2012.
--
function suite.dependency_onCSharpProjectsVs2012()
p.action.set("vs2012")
prepare("C#")
test.capture [[
ProjectSection(ProjectDependencies) = postProject
{2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31}
EndProjectSection
]]
end
| bsd-3-clause |
Blizzard/premake-core | modules/vstudio/tests/vc200x/test_project_refs.lua | 16 | 1831 | --
-- tests/actions/vstudio/vc200x/test_project_refs.lua
-- Validate project references in Visual Studio 200x C/C++ projects.
-- Copyright (c) 2011-2012 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("vstudio_vs200x_project_refs")
local vc200x = p.vstudio.vc200x
--
-- Setup
--
local wks, prj
function suite.setup()
p.action.set("vs2008")
wks = test.createWorkspace()
uuid "00112233-4455-6677-8888-99AABBCCDDEE"
test.createproject(wks)
end
local function prepare(platform)
prj = test.getproject(wks, 2)
vc200x.projectReferences(prj)
end
--
-- If there are no sibling projects listed in links(), then the
-- entire project references item group should be skipped.
--
function suite.noProjectReferencesGroup_onNoSiblingReferences()
prepare()
test.isemptycapture()
end
--
-- If a sibling project is listed in links(), an item group should
-- be written with a reference to that sibling project.
--
function suite.projectReferenceAdded_onSiblingProjectLink()
links { "MyProject" }
prepare()
test.capture [[
<ProjectReference
ReferencedProjectIdentifier="{00112233-4455-6677-8888-99AABBCCDDEE}"
RelativePathToProject=".\MyProject.vcproj"
/>
]]
end
--
-- Project references should always be specified relative to the
-- *solution* doing the referencing. Which is kind of weird, since it
-- would be incorrect if the project were included in more than one
-- solution file, yes?
--
function suite.referencesAreRelative_onDifferentProjectLocation()
links { "MyProject" }
location "build/MyProject2"
project("MyProject")
location "build/MyProject"
prepare()
test.capture [[
<ProjectReference
ReferencedProjectIdentifier="{00112233-4455-6677-8888-99AABBCCDDEE}"
RelativePathToProject=".\build\MyProject\MyProject.vcproj"
/>
]]
end
| bsd-3-clause |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/mediumPoison.lua | 2 | 2313 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
MediumPoisonCommand = {
name = "mediumpoison",
combatSpam = "attack",
dotEffects = {
DotEffect(
POISONED,
{ "resistance_poison", "poison_disease_resist" },
HEALTH,
true,
100,
40,
50,
45,
60
)
}
}
AddCommand(MediumPoisonCommand)
| agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/lair/npc_theater/dathomir_nightsister_elder_enclave_neutral_large_theater.lua | 3 | 1113 | dathomir_nightsister_elder_enclave_neutral_large_theater = Lair:new {
mobiles = {
{"nightsister_elder",1},
{"nightsister_protector",2},
{"nightsister_sentinel",4},
{"nightsister_initiate",4}
},
spawnLimit = 15,
buildingsVeryEasy = {"object/building/poi/dathomir_nightsisterpatrol_large1.iff","object/building/poi/dathomir_nightsisterpatrol_large2.iff"},
buildingsEasy = {"object/building/poi/dathomir_nightsisterpatrol_large1.iff","object/building/poi/dathomir_nightsisterpatrol_large2.iff"},
buildingsMedium = {"object/building/poi/dathomir_nightsisterpatrol_large1.iff","object/building/poi/dathomir_nightsisterpatrol_large2.iff"},
buildingsHard = {"object/building/poi/dathomir_nightsisterpatrol_large1.iff","object/building/poi/dathomir_nightsisterpatrol_large2.iff"},
buildingsVeryHard = {"object/building/poi/dathomir_nightsisterpatrol_large1.iff","object/building/poi/dathomir_nightsisterpatrol_large2.iff"},
mobType = "npc",
buildingType = "theater"
}
addLairTemplate("dathomir_nightsister_elder_enclave_neutral_large_theater", dathomir_nightsister_elder_enclave_neutral_large_theater)
| agpl-3.0 |
braydondavis/Nerd-Gaming-Public | resources/NGLogin/server.lua | 2 | 5816 | ------------------------------------------
-- Dx Login Panel --
------------------------------------------
-- Developer: Braydon Davis (xXMADEXx) --
-- File: server.lua --
-- Copyright 2013 (C) Braydon Davis --
-- All rights reserved. --
------------------------------------------
local cameras = {
{ 329.10980224609, -2117.2749023438, 50.161201477051, 329.65179443359, -2116.4926757813, 49.853763580322 },
{ 1266.0053710938, -1965.7087402344, 114.59829711914, 1265.1549072266, -1966.1115722656, 114.25980377197 },
{ 1514.0283203125, -1716.5743408203, 39.910701751709, 1514.5087890625, -1715.865234375, 39.394691467285 },
{ 1338.7514648438, -875.66558837891, 99.84880065918, 1339.4935302734, -875.07824707031, 99.52579498291 },
{ 1426.5421142578, -725.40289306641, 120.97090148926, 1427.3695068359, -725.00805664063, 120.571434021 },
{ 1357.5914306641, -592.23327636719, 125.15190124512, 1357.1751708984, -593.02673339844, 124.70780944824 },
{ 988.01123046875, -341.88409423828, 74.752601623535, 988.70251464844, -342.45135498047, 75.200187683105 },
{ -224.32290649414, -153.71020507813, 35.085899353027, -223.61195373535, -153.04695129395, 34.852146148682 }
}
function openView( plr )
local theplr = nil
if ( source and getElementType ( source ) == 'player' ) then
theplr = source
elseif ( plr and getElementType ( plr ) == 'player' ) then
theplr = plr
end
setTimer ( function ( p )
local ind = math.random ( #cameras )
setCameraMatrix ( p, unpack ( cameras[ind] ) )
fadeCamera ( p, true )
end, 300, 1, theplr )
end
addEventHandler ( "onPlayerJoin", root, openView )
addEventHandler ( "onPlayerLogout", root, openView )
function attemptLogin ( user, pass )
local s = getPlayerSerial ( source )
if ( exports.NGBans:isSerialBanned ( s ) ) then
exports.NGBans:loadBanScreenForPlayer ( source )
triggerClientEvent ( source, "NGLogin:hideLoginPanel", source )
end
if ( user and pass and type ( user ) == 'string' and type ( pass ) == 'string' ) then
--local user = string.lower ( user )
--local pass = string.lower ( pass )
local account = getAccount ( user )
if ( account ) then
if ( not logIn ( source, account, pass ) ) then
message ( source, "Incorrect password." )
return false
end
exports['NGLogs']:outputActionLog ( getPlayerName ( source ).." has logged in as "..tostring(user).." (IP: "..getPlayerIP(source).." || Serial: "..getPlayerSerial(source)..")" )
setCameraTarget ( source, source )
triggerLogin ( source, user, pass, false )
else
message ( source, "Unknown account." )
return false
end
end
return false
end
addEvent ( "Login:onClientAttemptLogin", true )
addEventHandler ( "Login:onClientAttemptLogin", root, attemptLogin )
addEvent ( "NGLogin:RequestClientLoginConfirmation", true )
addEventHandler ( "NGLogin:RequestClientLoginConfirmation", root, function ( )
local s = getPlayerSerial ( source )
if ( exports.NGBans:isSerialBanned ( s ) ) then
exports.NGBans:loadBanScreenForPlayer ( source )
return
end
triggerClientEvent ( source, "NGLogin:OnServerGiveClientAutherizationForLogin", source )
end )
function attemptRegister ( user, pass )
if ( user and pass and type ( user ) == 'string' and type ( pass ) == 'string' ) then
--local user = string.lower ( user )
--local pass = string.lower ( pass )
local account = getAccount ( user )
if ( not account ) then
local account = addAccount ( user, pass )
if ( account ) then
if ( not logIn ( source, account, pass ) ) then
return message ( source, "Logging in has failed." )
end
exports['NGLogs']:outputActionLog ( getPlayerName ( source ).." has registered on the server" )
triggerLogin ( source, user, pass, true )
setElementData ( source, "Job", "UnEmployed" )
setElementData ( source, "NGPlayerFunctions:Playtime_Mins", 0 )
setElementData ( source, "Playtime", "0 Hours" )
setElementData ( source, "Gang", "None" )
setElementData ( source, "Gang Rank", "None" )
exports['NGSQL']:createAccount ( user );
exports['NGJobs']:addPlayerToJobDatabase ( source )
exports.NGPlayerFunctions:setTeam(source,"Unemployed")
else
message ( source, "Adding account failed.\nPlease report to an admin." )
end
else
message ( source, "This account already exists." )
end
end
return false
end
addEvent ( "Login:onClientAttemptRegistration", true )
addEventHandler ( "Login:onClientAttemptRegistration", root, attemptRegister )
function message ( source, msg ) triggerClientEvent ( source, "onPlayerLoginPanelError", source, msg ) end
function triggerLogin ( source, user, pass, triggerIntro ) triggerClientEvent ( source, "onClientPlayerLogin", source, user, pass, triggerIntro, getPlayerIP ( source ) ) end
addEventHandler ( 'onPlayerLogout', root, function ( ) triggerClientEvent ( source, 'onClientPlayerLogout', source ) end )
addEvent ( "Login:onPlayerFinishIntro", true )
addEventHandler ( "Login:onPlayerFinishIntro", root, function ( )
if source then
setElementInterior ( source, 0 )
setElementDimension ( source, 0 )
fadeCamera ( source, true )
setCameraTarget ( source, source )
spawnPlayer ( source, 1546.58, -1675.31, 13.56 )
setElementModel ( source, 28 )
setPlayerMoney ( source, 1500 )
setElementRotation ( source, 0, 0, 90 )
showChat ( source, true )
showCursor ( source, false )
showPlayerHudComponent ( source, 'all', true )
end
return false
end )
addEventHandler ( "onPlayerJoin", root, function ( )
setElementData ( source, "Job", "None" )
setElementData ( source, "Job Rank", "None" )
setElementData ( source, "Gang", "None" )
setElementData ( source, "Gang Rank", "None" )
setElementData ( source, "Money", "$0" )
setElementData ( source, "Playtime", "0 Minutes" )
setElementData ( source, "FPS", "0" )
end )
| mit |
moonlight/cave-adventure | data/scripts/AI.lua | 2 | 3206 | --
-- Our 'magnificent' AI implementation
--
-- Common states for an AI monster
AI_WAITING = 1
AI_WALKING = 2
AI_ATTACK = 3
AI_DEAD = 4
AI_HIT = 5
AI_READY = 6
CommonAI = {}
function CommonAI:event_init()
self.state = AI_READY
self.tick_time = 1
self.charge = 0
self.charge_time = 200
self.attack_time = 50
self.attack_range = 3
self.attack_min_dam = 1
self.attack_max_dam = 3
self.health = 25
self.maxHealth = self.health
end
function CommonAI:tick()
if (self.charge > 0) then self.charge = self.charge - 1 end
-- Switch to ready from walking
if (self.state == AI_WALKING and self.walking == 0) then
self:setState(AI_READY)
end
-- When an AI is ready, it's waiting for something to happen to take action
if (self.state == AI_READY) then
-- Check if player is drawing near
playerDist = playerDistance(self)
local player = m_get_player()
if (playerDist < 5 and player.state ~= CHR_DEAD) then
-- Chase or attack?
if (playerDist <= self.attack_range) then
-- Attack on charged
if (self.charge == 0 and self.walking == 0) then
self:attack(playerDirection(self))
end
else
self:walk(playerDirection(self))
end
end
end
end
function CommonAI:attack(dir)
--m_message("AI attacking!");
self.dir = dir
self:setState(AI_ATTACK)
local player = m_get_player()
-- Handle attack (deal damage to player)
player:takeDamage(self.attack_min_dam + math.random(self.attack_max_dam - self.attack_min_dam))
-- Spawn the hitting effect (ie. sparks)
if (self.attack_object) then self:attack_object(player) end
ActionController:addSequence{
ActionWait(self.attack_time),
ActionSetState(self, AI_READY),
ActionSetVariable(self, "charge", self.charge_time),
}
end
function CommonAI:walk(dir)
m_walk_obj(self, dir)
self:setState(AI_WALKING)
end
function CommonAI:setState(state)
self.state = state
if (self.state == AI_ATTACK) then self.attacking = 1 else self.attacking = 0 end
self:update_bitmap()
if (self.state == AI_DEAD) then
if (self.do_death) then self:do_death()
else
self.animation = nil
ActionController:addSequence({
ActionWait(100),
ActionSetVariable(self, "draw_mode", DM_TRANS),
ActionTweenVariable(self, "alpha", 200, 0),
ActionDestroyObject(self),
})
end
self.tick_time = 0
end
end
function CommonAI:take_damage(amount)
if (self.state ~= AI_DEAD) then
-- Should probably suspend a little when being hit
--self:setState(AI_HIT)
self.health = self.health - amount
-- Spawn the getting hit effect (ie. blood)
if (self.do_hit) then self:do_hit()
else
local obj = m_add_object(self.x, self.y, "BloodSplat")
obj.offset_z = obj.offset_z + 12
end
if (self.health <= 0) then
self:setState(AI_DEAD)
local player = m_get_player()
player.experience = player.experience + self.experience
if (player.experience >= player.nextLevelExperience) then
player.endurance = player.endurance + 5
player.nextLevelExperience = 2.5 * player.nextLevelExperience
player:derive_attributes()
end
end
end
end
| gpl-2.0 |
mabotech/mabo.io | py/opcda/lua/send.lua | 1 | 1119 |
-- for ak_client.py
-- key1,argv1,argv2
local payload = redis.call("HGET", KEYS[1],"val")
--redis.call("HSET", KEYS[1],"tag",ARGV[1])
--redis.call("HSET", KEYS[1],"x",ARGV[3])
--redis.call("HSET", KEYS[1],"y",ARGV[4])
if payload == ARGV[2] then
-- redis.call("LPUSH", "c1","chan2")
redis.call("HSET", KEYS[1],"heartbeat",ARGV[2])
redis.call("HSET", KEYS[1],"off",0)
return "same"
else
local starton = redis.call("HGET", KEYS[1],"starton")
if starton == false then
starton = ARGV[4]
end
local msg = cmsgpack.pack(
{id=KEYS[1], pstatus = payload,
duration = ARGV[4] - starton,
ch_ori_eqpt = ARGV[2], heartbeat=ARGV[4],
time_precision="ms"}
)
redis.call("HSET", KEYS[1],"val",ARGV[2])
redis.call("HSET", KEYS[1],"starton",ARGV[4])
redis.call("HSET", KEYS[1],"heartbeat",ARGV[4])
redis.call("HSET", KEYS[1],"off",0)
redis.call("RPUSH", "data_queue",msg) -- msg queue
redis.call("PUBLISH", "new_data","new") -- notice
return payload -- return old val
end
| mit |
Blizzard/premake-core | tests/_tests.lua | 8 | 1575 | return {
-- Base API tests
"test_string.lua",
"base/test_aliasing.lua",
"base/test_binmodules.lua",
"base/test_configset.lua",
"base/test_context.lua",
"base/test_criteria.lua",
"base/test_detoken.lua",
"base/test_include.lua",
"base/test_module_loader.lua",
"base/test_option.lua",
"base/test_os.lua",
"base/test_override.lua",
"base/test_path.lua",
"base/test_premake_command.lua",
"base/test_table.lua",
"base/test_tree.lua",
"base/test_uuid.lua",
"base/test_versions.lua",
"base/test_http.lua",
"base/test_json.lua",
-- Workspace object tests
"workspace/test_eachconfig.lua",
"workspace/test_location.lua",
"workspace/test_objdirs.lua",
-- Project object tests
"project/test_config_maps.lua",
"project/test_eachconfig.lua",
"project/test_getconfig.lua",
"project/test_location.lua",
"project/test_sources.lua",
"project/test_vpaths.lua",
-- Configuration object tests
"config/test_linkinfo.lua",
"config/test_links.lua",
"config/test_targetinfo.lua",
-- Baking tests
"oven/test_filtering.lua",
"oven/test_objdirs.lua",
-- API tests
"api/test_boolean_kind.lua",
"api/test_containers.lua",
"api/test_directory_kind.lua",
"api/test_list_kind.lua",
"api/test_path_kind.lua",
"api/test_register.lua",
"api/test_string_kind.lua",
"api/test_table_kind.lua",
"api/test_deprecations.lua",
-- Control system tests
"test_premake.lua",
"base/test_validation.lua",
-- -- Toolset tests
"tools/test_dotnet.lua",
"tools/test_gcc.lua",
"tools/test_msc.lua",
}
| bsd-3-clause |
kidaa/Algorithm-Implementations | Depth_Limited_Search/Lua/Yonaba/dls.lua | 26 | 3110 | -- Generic Depth-Limited search algorithm implementation
-- See : http://en.wikipedia.org/wiki/Depth-limited_search
-- Notes : this is a generic implementation of Depth-Limited search algorithm.
-- It is devised to be used on any type of graph (point-graph, tile-graph,
-- or whatever. It expects to be initialized with a handler, which acts as
-- an interface between the search algorithm and the search space.
-- The DLS class expects a handler to be initialized. Roughly said, the handler
-- is an interface between your search space and the generic search algorithm.
-- This ensures flexibility, so that the generic algorithm can be adapted to
-- search on any kind of space.
-- The passed-in handler should implement those functions.
-- handler.getNode(...) -> returns a Node (instance of node.lua)
-- handler.getNeighbors(n) -> returns an array of all nodes that can be reached
-- via node n (also called successors of node n)
-- The actual implementation uses recursion to look up for the path.
-- Between consecutive path requests, the user must call the :resetForNextSearch()
-- method to clear all nodes data created during a previous search.
-- The generic Node class provided (see node.lua) should also be implemented
-- through the handler. Basically, it should describe how nodes are labelled
-- and tested for equality for a custom search space.
-- The following functions should be implemented:
-- function Node:initialize(...) -> creates a Node with custom attributes
-- function Node:isEqualTo(n) -> returns if self is equal to node n
-- function Node:toString() -> returns a unique string representation of
-- the node, for debug purposes
-- See custom handlers for reference (*_hander.lua).
-- Dependencies
local class = require 'utils.class'
-- Builds and returns the path to the goal node
local function backtrace(node)
local path = {}
repeat
table.insert(path, 1, node)
node = node.parent
until not node
return path
end
-- Initializes Depth-Limited search with a custom handler
local DLS = class()
function DLS:initialize(handler)
self.handler = handler
end
-- Clears all nodes for a next search
-- Must be called in-between consecutive searches
function DLS:resetForNextSearch()
local nodes = self.handler.getAllNodes()
for _, node in ipairs(nodes) do
node.visited, node.parent = nil, nil
end
end
-- Returns the path between start and goal locations
-- start : a Node representing the start location
-- goal : a Node representing the target location
-- depth : the maximum depth of search
-- returns : an array of nodes
function DLS:findPath(start, goal, depth)
if start == goal then return backtrace(start) end
if depth == 0 then return end
start.visited = true
local neighbors = self.handler.getNeighbors(start)
for _, neighbor in ipairs(neighbors) do
if not neighbor.visited then
neighbor.parent = start
local foundGoal = self:findPath(neighbor, goal, depth - 1)
if foundGoal then return foundGoal end
end
end
end
return DLS
| mit |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/corpse.lua | 4 | 2111 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
CorpseCommand = {
name = "corpse",
}
AddCommand(CorpseCommand)
| agpl-3.0 |
tequir00t/dotfiles | awesome/lain/widgets/yawn/init.lua | 2 | 6334 |
--[[
Licensed under GNU General Public License v2
* (c) 2013, Luke Bonham
--]]
local newtimer = require("lain.helpers").newtimer
local async = require("lain.asyncshell")
local naughty = require("naughty")
local wibox = require("wibox")
local debug = { getinfo = debug.getinfo }
local io = { lines = io.lines,
open = io.open }
local os = { date = os.date,
getenv = os.getenv }
local string = { find = string.find,
match = string.match,
gsub = string.gsub,
sub = string.sub }
local tonumber = tonumber
local setmetatable = setmetatable
-- YAhoo! Weather Notification
-- lain.widgets.yawn
local yawn =
{
icon = wibox.widget.imagebox(),
widget = wibox.widget.textbox('')
}
local project_path = debug.getinfo(1, 'S').source:match[[^@(.*/).*$]]
local localizations_path = project_path .. 'localizations/'
local icon_path = project_path .. 'icons/'
local api_url = 'http://weather.yahooapis.com/forecastrss'
local units_set = '?u=c&w=' -- Default is Celsius
local language = string.match(os.getenv("LANG"), "(%S*$*)[.]") or "en_US" -- if LANG is not set
local weather_data = nil
local notification = nil
local city_id = nil
local sky = nil
local settings = function() end
yawn_notification_preset = {}
function yawn.fetch_weather()
local url = api_url .. units_set .. city_id
local cmd = "curl --connect-timeout 1 -fsm 3 '" .. url .. "'"
async.request(cmd, function(f)
local text = f:read("*a")
f:close()
-- In case of no connection or invalid city ID
-- widgets won't display
if text == "" or text:match("City not found")
then
yawn.icon:set_image(icon_path .. "na.png")
if text == "" then
weather_data = "Service not available at the moment."
yawn.widget:set_text(" N/A ")
else
weather_data = "City not found!\n" ..
"Are you sure " .. city_id ..
" is your Yahoo city ID?"
yawn.widget:set_text(" ? ")
end
return
end
-- Processing raw data
weather_data = text:gsub("<.->", "")
weather_data = weather_data:match("Current Conditions:.-Full") or ""
-- may still happens in case of bad connectivity
if weather_data == "" then
yawn.icon:set_image(icon_path .. "na.png")
yawn.widget:set_text(" ? ")
return
end
weather_data = weather_data:gsub("Current Conditions:.-\n", "Now: ")
weather_data = weather_data:gsub("Forecast:.-\n", "")
weather_data = weather_data:gsub("\nFull", "")
weather_data = weather_data:gsub("[\n]$", "")
weather_data = weather_data:gsub(" [-] " , ": ")
weather_data = weather_data:gsub("[.]", ",")
weather_data = weather_data:gsub("High: ", "")
weather_data = weather_data:gsub(" Low: ", " - ")
-- Getting info for text widget
local now = weather_data:sub(weather_data:find("Now:")+5,
weather_data:find("\n")-1)
forecast = now:sub(1, now:find(",")-1)
units = now:sub(now:find(",")+2, -2)
-- Day/Night icon change
local hour = tonumber(os.date("%H"))
sky = icon_path
if forecast == "Clear" or
forecast == "Fair" or
forecast == "Partly Cloudy" or
forecast == "Mostly Cloudy"
then
if hour >= 6 and hour <= 18
then
sky = sky .. "Day"
else
sky = sky .. "Night"
end
end
sky = sky .. forecast:gsub(" ", ""):gsub("/", "") .. ".png"
-- In case there's no defined icon for current forecast
if io.open(sky) == nil then
sky = icon_path .. "na.png"
end
-- Localization
local f = io.open(localizations_path .. language, "r")
if language:find("en_") == nil and f ~= nil
then
f:close()
for line in io.lines(localizations_path .. language)
do
word = string.sub(line, 1, line:find("|")-1)
translation = string.sub(line, line:find("|")+1)
weather_data = string.gsub(weather_data, word, translation)
end
end
-- Finally setting infos
yawn.icon:set_image(sky)
widget = yawn.widget
_data = weather_data:match(": %S.-,") or weather_data
forecast = _data:gsub(": ", ""):gsub(",", "")
units = units:gsub(" ", "")
settings()
end)
end
function yawn.hide()
if notification ~= nil then
naughty.destroy(notification)
notification = nil
end
end
function yawn.show(t_out)
if yawn.widget._layout.text:match("?")
then
yawn.fetch_weather()
end
yawn.hide()
notification = naughty.notify({
preset = yawn_notification_preset,
text = weather_data,
icon = sky,
timeout = t_out,
})
end
function yawn.register(id, args)
local args = args or {}
local timeout = args.timeout or 600
settings = args.settings or function() end
if args.u == "f" then units_set = '?u=f&w=' end
city_id = id
newtimer("yawn", timeout, yawn.fetch_weather)
yawn.icon:connect_signal("mouse::enter", function()
yawn.show(0)
end)
yawn.icon:connect_signal("mouse::leave", function()
yawn.hide()
end)
return yawn
end
function yawn.attach(widget, id, args)
yawn.register(id, args)
widget:connect_signal("mouse::enter", function()
yawn.show(0)
end)
widget:connect_signal("mouse::leave", function()
yawn.hide()
end)
end
return setmetatable(yawn, { __call = function(_, ...) return yawn.register(...) end })
| gpl-2.0 |
szczukot/domoticz | dzVents/runtime/tests/testUtils.lua | 5 | 13152 | local _ = require 'lodash'
--package.path = package.path .. ";../?.lua"
local scriptPath = ''
package.path = ";../?.lua;" .. scriptPath .. '/?.lua;../device-adapters/?.lua;../../../scripts/lua/?.lua;' .. package.path
local LOG_INFO = 2
local LOG_DEBUG = 3
local LOG_ERROR = 1
describe('event helpers', function()
local utils
setup(function()
_G.logLevel = 1
_G.log = function() end
_G.globalvariables = {
Security = 'sec',
['radix_separator'] = '.',
['script_path'] = scriptPath,
['domoticz_listening_port'] = '8080'
}
_G.domoticzData =
{
[1] = { ["id"] = 1, ["baseType"] = "device", ["name"] = "ExistingDevice" },
[2] = { ["id"] = 2, ["baseType"] = "group", ["name"] = "ExistingGroup" },
[3] = { ["id"] = 3, ["baseType"] = "scene", ["name"] = "ExistingScene" },
[4] = { ["id"] = 4, ["baseType"] = "uservariable", ["name"] = "ExistingVariable" },
[5] = { ["id"] = 5, ["baseType"] = "camera", ["name"] = "ExistingCamera" },
[6] = { ["id"] = 6, ["baseType"] = "hardware", ["name"] = "ExistingHardware" },
}
utils = require('Utils')
end)
teardown(function()
utils = nil
_G.domoticzData = nil
end)
describe("Logging", function()
it('should print using the global log function', function()
local printed
utils.print = function(msg)
printed = msg
end
utils.log('abc', utils.LOG_ERROR)
assert.is_same('Error: (' .. utils.DZVERSION .. ') abc', printed)
end)
it('should log INFO by default', function()
local printed
utils.print = function(msg)
printed = msg
end
_G.logLevel = utils.LOG_INFO
utils.log('something')
assert.is_same('Info: something', printed)
end)
it('should log print with requested marker', function()
local printed
utils.print = function(msg)
printed = msg
end
_G.logLevel = utils.LOG_INFO
utils.log('something')
assert.is_same('Info: something', printed)
_G.moduleLabel = 'testUtils'
utils.setLogMarker()
utils.log('something')
assert.is_same('Info: testUtils: something', printed)
utils.setLogMarker('Busted')
utils.log('something')
assert.is_same('Info: Busted: something', printed)
end)
it('should not log above level', function()
local printed
utils.print = function(msg)
printed = msg
end
_G.logLevel = utils.LOG_INFO
utils.log('something', utils.LOG_DEBUG)
assert.is_nil(printed)
_G.logLevel = utils.LOG_ERROR
utils.log('error', utils.LOG_INFO)
assert.is_nil(printed)
utils.log('error', utils.LOG_WARNING)
assert.is_nil(printed)
_G.logLevel = 0
utils.log('error', utils.LOG_ERROR)
assert.is_nil(printed)
end)
end)
describe("various utils", function()
it('should return true if a file exists', function()
assert.is_true(utils.fileExists('testfile'))
end)
it('should right pad a string', function()
assert.is_same(utils.rightPad('string',7),'string ')
assert.is_same(utils.rightPad('string',7,'@'),'string@')
assert.is_same(utils.rightPad('string',2),'string')
end)
it('should left pad a string', function()
assert.is_same(utils.leftPad('string',7),' string')
assert.is_same(utils.leftPad('string',7,'@'),'@string')
assert.is_same(utils.leftPad('string',2),'string')
end)
it('should center and pad a string', function()
assert.is_same(utils.centerPad('string',8),' string ')
assert.is_same(utils.centerPad('string',8,'@'),'@string@')
assert.is_same(utils.centerPad('string',2),'string')
end)
it('should pad a number with leading zeros', function()
assert.is_same(utils.leadingZeros(99,3),'099')
assert.is_same(utils.leadingZeros(999,2),'999')
end)
it('should return nil for osexecute (echo)', function()
assert.is_nil(utils.osExecute('echo test > testfile.out'))
end)
it('should return nil for os.execute (rm)', function()
assert.is_nil(utils.osExecute('rm testfile.out'))
end)
it('should return nil for osCommand (echo)', function()
local res, rc = utils.osCommand('echo test > testfile.out')
assert.is_same(rc, 0)
assert.is_same(res, '')
end)
it('should return nil for osCommand (rm)', function()
local res, rc = utils.osCommand('rm -fv nofile.nofile ')
assert.is_same(rc, 0)
assert.is_same(res, '')
local res, rc = utils.osCommand('rm -v testfile.out')
assert.is_same(rc, 0)
assert.is_same(res:sub(1,4), "remo")
end)
it('should return false if a file does not exist', function()
assert.is_false(utils.fileExists('blatestfile'))
end)
it('should return false if a device does not exist and id or name when it does', function()
local device = { id = 1}
local noDevice = { id = 2}
assert.is_false(utils.deviceExists('noDevice'))
assert.is_false(utils.deviceExists(noDevice))
assert.is_false(utils.deviceExists(2))
assert.is_true(utils.deviceExists('ExistingDevice') == 1 )
assert.is_true(utils.deviceExists(1) == 'ExistingDevice' )
assert.is_true(utils.deviceExists(device) == 1)
end)
it('should return false if a group does not exist and id or name when it does', function()
local group = { id = 2}
local noGroup = { id = 3}
assert.is_false(utils.groupExists('noGroup'))
assert.is_false(utils.groupExists(noGroup))
assert.is_false(utils.groupExists(3))
assert.is_true(utils.groupExists('ExistingGroup') == 2 )
assert.is_true(utils.groupExists(2) == 'ExistingGroup' )
assert.is_true(utils.groupExists(group) == 2)
end)
it('should return false if a scene does not exist and id or name when it does', function()
local scene = { id = 3}
local noScene = { id = 4}
assert.is_false(utils.sceneExists('noScene'))
assert.is_false(utils.sceneExists(noScene))
assert.is_false(utils.sceneExists(4))
assert.is_true(utils.sceneExists('ExistingScene') == 3 )
assert.is_true(utils.sceneExists(3) == 'ExistingScene' )
assert.is_true(utils.sceneExists(scene) == 3)
end)
it('should return false if a variable does not exist and id or name when it does', function()
local variable = { id = 4}
local noVariable = { id = 5}
assert.is_false(utils.variableExists('noVariable'))
assert.is_false(utils.variableExists(noVariable))
assert.is_false(utils.variableExists(5))
assert.is_true(utils.variableExists('ExistingVariable') == 4 )
assert.is_true(utils.variableExists(4) == 'ExistingVariable' )
assert.is_true(utils.variableExists(variable) == 4)
end)
it('should return false if a camera does not exist and id or name when it does', function()
local camera = { id = 5}
local noCamera = { id = 6}
assert.is_false(utils.cameraExists('noCamera'))
assert.is_false(utils.cameraExists(noCamera))
assert.is_false(utils.cameraExists(6))
assert.is_true(utils.cameraExists('ExistingCamera') == 5 )
assert.is_true(utils.cameraExists(5) == 'ExistingCamera' )
assert.is_true(utils.cameraExists(camera) == 5)
end)
it('should return false if hardware does not exist and id or name when it does', function()
assert.is_false(utils.hardwareExists('noHardware'))
assert.is_false(utils.hardwareExists(7))
assert.is_true(utils.hardwareExists('ExistingHardware') == 6 )
assert.is_true(utils.hardwareExists(6) == 'ExistingHardware' )
end)
it('should convert a json to a table', function()
local json = '{ "a": 1 }'
local t = utils.fromJSON(json)
assert.is_same(1, t['a'])
end)
it('should convert a serialized json to a table when set to true', function()
local json = '{"level 1":{"level 2_1":{"level 3":{\"level 4\":'..
'{\"level 5_1\":[\"a\"],\"level 5_2\":[\"b\",\"c"]}}},' ..
'"level 2_2":{"level 3":"[\"found\",\"1\",\"2\",\"3\"]},' ..
'"level 2_3":{"level 3":"[block] as data"}}}'
local t = utils.fromJSON(json)
assert.is_nil(t)
local t = utils.fromJSON(json, json)
assert.is_same(t,json)
local t = utils.fromJSON(json, json, true)
assert.is_same('found', t['level 1']['level 2_2']['level 3'][1])
assert.is_same('[block] as data', t['level 1']['level 2_3']['level 3'])
end)
it('should round a number', function()
local number = '2.43'
assert.is_same(2, utils.round(number) )
number = -2.43
assert.is_same(-2, utils.round(number) )
number = {}
assert.is_nil( utils.round(number) )
end)
it('should recognize an xml string', function()
local xml = '<testXML>What a nice feature!</testXML>'
assert.is_true(utils.isXML(xml))
local xml = nil
assert.is_nil(utils.isXML(xml))
local xml = '<testXML>What a bad XML!</testXML> xml'
assert.is_nil(utils.isXML(xml))
local xml = '{ wrong XML }'
local content = 'application/xml'
fallback = nil
assert.is_true(utils.isXML(xml, content))
end)
it('should recognize a json string', function()
local json = '[{ "test": 12 }]'
assert.is_true(utils.isJSON(json))
local json = '{ "test": 12 }'
assert.is_true(utils.isJSON(json))
local json = nil
assert.is_false(utils.isJSON(json))
local json = '< wrong XML >'
local content = 'application/json'
fallback = nil
assert.is_true(utils.isJSON(json, content))
end)
it('should convert a json string to a table or fallback to fallback', function()
local json = '{ "a": 1 }'
local t = utils.fromJSON(json, fallback)
assert.is_same(1, t['a'])
local json = '[{"obj":"Switch","act":"On" }]'
local t = utils.fromJSON(json, fallback)
assert.is_same('Switch', t[1].obj)
json = nil
local fallback = { a=1 }
local t = utils.fromJSON(json, fallback)
assert.is_same(1, t['a'])
json = nil
fallback = nil
local t = utils.fromJSON(json, fallback)
assert.is_nil(t)
end)
it('should convert an xml string to a table or fallback to fallback', function()
local xml = '<testXML>What a nice feature!</testXML>'
local t = utils.fromXML(xml, fallback)
assert.is_same('What a nice feature!', t.testXML)
local xml = nil
local fallback = { a=1 }
local t = utils.fromXML(xml, fallback)
assert.is_same(1, t['a'])
local xml = nil
fallback = nil
local t = utils.fromXML(xml, fallback)
assert.is_nil(t)
end)
it('should convert a table to json', function()
local t = {
a = 1,
b = function()
print('This should do nothing')
end
}
local res = utils.toJSON(t)
assert.is_same('{"a":1,"b":"Function"}', res)
end)
it('should convert a table to xml', function()
local t = { a= 1 }
local res = utils.toXML(t, 'busted')
assert.is_same('<busted>\n<a>1</a>\n</busted>\n', res)
end)
it('should convert a string or number to base64Code', function()
local res = utils.toBase64('Busted in base64')
assert.is_same('QnVzdGVkIGluIGJhc2U2NA==', res)
local res = utils.toBase64(123.45)
assert.is_same('MTIzLjQ1', res)
local res = utils.toBase64(1234567890)
assert.is_same('MTIzNDU2Nzg5MA==', res)
end)
it('should send errormessage when sending table to toBase64', function()
utils.log = function(msg)
printed = msg
end
local t = { a= 1 }
local res = utils.toBase64(t)
assert.is_same('toBase64: parm should be a number or a string; you supplied a table', printed)
end)
it('should decode a base64 encoded string', function()
local res = utils.fromBase64('QnVzdGVkIGluIGJhc2U2NA==')
assert.is_same('Busted in base64', res)
end)
it('should send errormessage when sending table to fromBase64', function()
utils.log = function(msg)
printed = msg
end
local t = { a= 1 }
local res = utils.fromBase64(t)
assert.is_same('fromBase64: parm should be a string; you supplied a table', printed)
end)
it('should dump a table to log', function()
local t = { a=1,b=2,c={d=3,e=4, "test"} }
local res = utils.dumpTable(t,"> ")
assert.is_nil(res)
end)
it('should split a string ', function()
assert.is_same(utils.stringSplit("A-B-C", "-")[2],"B")
assert.is_same(utils.stringSplit("I forgot to include this in Domoticz.lua")[7],"Domoticz.lua")
end)
it('should split a line', function()
assert.is_same(utils.splitLine("segment one or segment two or segment 3", "or")[2],"segment two")
assert.is_same(utils.splitLine("segment one or segment two or segment 3", "or")[3],"segment 3")
end)
it('should fuzzy match a string ', function()
assert.is_same(utils.fuzzyLookup('HtpRepsonse','httpResponse'),3)
assert.is_same(utils.fuzzyLookup('httpResponse','httpResponse'),0)
local validEventTypes = 'devices,timer,security,customEvents,system,httpResponses,scenes,groups,variables,devices'
assert.is_same(utils.fuzzyLookup('CutsomeEvent',utils.stringSplit(validEventTypes,',')),'customEvents')
end)
it('should match a string with Lua magic chars', function()
assert.is_same(string.sMatch("testing (A-B-C) testing","(A-B-C)"), "(A-B-C)")
assert.is_not(string.match("testing (A-B-C) testing", "(A-B-C)"), "(A-B-C)")
end)
it('should handle inTable ', function()
assert.is_same(utils.inTable({ testVersion = "2.5" }, 2.5 ), "value")
assert.is_same(utils.inTable({ testVersion = "2.5" }, "testVersion"), "key")
assert.is_not(utils.inTable({ testVersion = "2.5" }, 2.4 ), false)
end)
end)
end)
| gpl-3.0 |
braydondavis/Nerd-Gaming-Public | resources/NGDrugs/core_client.lua | 2 | 2799 | --[[
How does the script work?
When the function useDrug() is called, it will check to see if the selected drug is already running. If
the drug is already running, then it'll kill the timer and create a new timer with the doce time + the
remaining time. If the drug isn't running, then it'll just create a new timer. The function will call:
drugs[drugName].func.load ( ) to start the drug, even if it's already running. The script will call:
drugs[drugName].func.unload ( ) to stop the running drug
GLOBAL VARIABLES:
drugs
Type: Table
For: Storing all the drugs, along with their variables and functions
Drug variables are stored in: drugs[drugName].var
Drug functions are stored in: drugs[drugName].func
sx_
Type: Int
For: Storing the clients X axis resolution
sy_
Type: Int
For: Storing the clients Y axis resolution
sx:
Type: Float
For: Storing the clients X offset, to make the effects same in all resolution
sy:
Type: Float
For: Storing the clients X offset, to make the effects same in all resolution
]]
drugs = { }
sx_, sy_ = guiGetScreenSize ( )
sx, sy = sx_/1280, sy_/720
local var = { }
var.timers = { }
var.rendering = false
function useDrug ( drug, amount )
if ( localPlayer.interior ~= 0 or localPlayer.dimension ~= 0 ) then
return false, "You need to be outside"
end
local drug = tostring ( drug )
if ( not drugs [ drug ] ) then return false end
local d = drugs [ drug ]
rTime = 0
if ( var.timers [ drug ] and isTimer ( var.timers [ drug ] ) ) then
rTime = getTimerDetails ( var.timers [ drug ] )
killTimer ( var.timers [ drug ] )
var.timers [ drug ] = nil
end
drugs[drug].func.load ( )
var.timers[drug] = setTimer ( drugs [drug].func.unload, ((drugs[drug].info.timePerDoce*amount)*1000)+rTime, 1 )
if ( not var.rendering ) then
addEventHandler ( "onClientRender", root, var.render )
var.rendering = true
end
end
function var.render ( )
local id = 0
local remove = { }
for i, v in pairs ( var.timers ) do
if ( not v or not isTimer ( v ) ) then
remove [ i ] = true
else
dxDrawRectangle ( sx*(300+(id*170)), sy*655, sx*160, sy*50, tocolor ( 0, 0, 0, 170 ) )
dxDrawText ( tostring ( i ) .. " - ".. tostring ( math.floor ( getTimerDetails ( v ) / 1000 ) ),
sx*(300+(id*170)), sy*655,
(sx*(300+(id*170)))+(sx*160), (sy*655)+(sy*50),
tocolor ( 255, 255, 255, 255 ), 1.5, "default", "center", "center" )
id = id + 1
end
end
for i, v in pairs ( remove ) do
var.timers [ i ] = nil
end
if ( id == 0 or not var.rendering ) then
removeEventHandler ( "onClientRender", root, var.render )
var.rendering = false
end
end
function table.len ( table )
local c = 0
for i, v in pairs ( table ) do
c = c + 1
end
return c
end | mit |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/broadcastPlanet.lua | 4 | 2138 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
BroadcastPlanetCommand = {
name = "broadcastplanet",
}
AddCommand(BroadcastPlanetCommand)
| agpl-3.0 |
choptastic/GuildRaidSnapShot | GuildRaidSnapShot.lua | 2 | 92815 | -- GuildRaidSnapShot Mod
-- Copyright (c) 2005-2014 Sigma Star Systems
-- Released under the MIT License. See LICENSE.txt for full license
GuildRaidSnapShot_SnapShots = {};
GuildRaidSnapShot_Loot = {};
GuildRaidSnapShot_Notes = {};
GuildRaidSnapShot_Adj = {};
GRSS_Calendar = {};
GRSS_Alts = {};
GRSS_MainOnly = {};
GRSS_Divide = {};
GRSS_Systems = {};
GRSS_Full_DKP = {};
GRSS_Bosses_Old = {"Lucifron","Magmadar","Gehennas","Garr","Baron Geddon","Shazzrah","Sulfuron Harbinger","Golemagg the Incinerator","Ragnaros","Doom Lord Kazzak","Azuregos","Lethon","Emeriss","Onyxia","Taerar","Ysondre","Razorgore the Untamed","Vaelastrasz the Corrupt","Flamegor","Ebonroc","Firemaw","Chromaggus","Broodlord Lashlayer","Nefarian","Prophet Skeram","Lord Kri","Battleguard Sartura","Princess Huhuran","Fankriss the Unyielding","Viscidus","Ouro","C'Thun","Emperor Vek'nilash","Emperor Vek'lor","Anub'Rekhan","Grand Widow Faerlina","Maexxna","Feugen","Gluth","Gothik the Harvester","Grobbulus","Heigan the Unclean","Highlord Mograine","Instructor Razuvious","Lady Blaumeux","Loatheb","Noth the Plaguebringer","Patchwerk","Sapphiron","Sir Zeliek","Stalagg","Thaddius","Thane Korth'azz","Ossirian the Unscarred","Moam","Kurinnaxx","General Rajaxx","Buru the Gorger","Ayamiss the Hunter","Bloodlord Mandokir","Gahz'ranka","Gri'lek","Hakkar","Hazza'rah","High Priest Thekal","High Priest Venoxis","High Priestess Arlokk","High Priestess Jeklik","High Priestess Mar'li","Jin'do the Hexxer","Renataki","Wushoolay","The Crone","Hyakiss the Lurker","Julianne","Maiden of Virtue","Moroes","Netherspite","Nightbane","Prince Malchezaar","Rokad the Ravager","Romulo","Shade of Aran","Shadikith the Glider","Terestian Illhoof","The Big Bad Wolf","The Curator","Gruul the Dragonkiller","Magtheridon","High King Maulgar","Fathom-Lord Karathress","Hydross the Unstable","Lady Vashj","Leotheras the Blind","Morogrim Tidewalker","The Lurker Below","Al'ar","High Astromancer Solarian","Kael'thas Sunstrider","Void Reaver","Doomwalker","Attumen the Huntsman","Illidan Stormrage","Gathios the Shatterer","High Nethermancer Zerevor","Lady Malande","Veras Darkshadow","Essence of Anger","Gurtogg Bloodboil","Illidari Council","Teron Gorefiend","High Warlord Naj'entus","Mother Shahraz","Shade of Akama","Supremus","Anetheron","Archimonde","Azgalor","Kaz'rogal","Rage Winterchill","Nalorakk","Akil'zon","Jan'alai","Halazzi","Hex Lord Malacrass","Zul'jin","Kalecgos","Sathrovarr the Corruptor","Brutallus","Felmyst","Lady Sacrolash","Grand Warlock Alythess","M'uru","Entropius","Kil'jaeden","Kel'Thuzad","Sartharion","Archavon the Stone Watcher","Malygos","Flame Leviathan","Razorscale","XT-002 Deconstructor","Ignis the Furnace Master","Assembly of Iron","Kologarn","Auriaya","Mimiron","Hodir","Thorim","Freva","General Vezax","Yogg-Saron","Algalon the Observer","Emalon the Storm Watcher","Icehowl","Lord Jaraxxus","Fjola Lightbane","Anub'arak","Koralon the Flame Watcher","Lord Marrowgar","Lady Deathwhisper","Deathbringer Saurfang","Festergut","Rotface","Professor Putricide","Blood-Queen Lana'thal","Valithria Dreamwalker","Sindragosa","The Lich King","Prince Keleseth",
-- Cata Bosses
"Argaloth","Halfus Wyrmbreaker","Theralion","Cho'gall","Magmaw","Omnitron Defense System","Maloriak","Atramedes","Chimaeron","Nefarian","Al'Akir","Sinestra","Shannox","Lord Rhyolith","Beth'tilac","Alysrazor","Baelroc","Majordomo Staghelm","Ragnaros","Volcanus","Morchok","Warlord Zon'ozz","Yor'sahj the Unsleeping","Hagara the Stormbinder","Ultraxion","Warmaster Blackhorn","Deathwing",
-- MOP Bosses
"Imperial Vizier Zor'lok","Blade Lord Ta'yak","Garalon","Wind Lord Mel'jarak","Amber-Shaper Un-sok","Grand Empress Shek'zeer",
"Jade Guardian","Feng the Accursed","Gara'jal the Spiritbinder","The Spirit Kings","Elegon","Jan-xi",
"Sha of Anger","Salyis's Warband",
"Tsulong","Lei Shi","Sha of Fear",
"Jin'rokh the Breaker","Horridon","Tortos","Megaera","Ji-Kun","Durumu the Forgotten","Primordius","Dark Animus","Iron Qon","Twin Consorts","Lei Shen","Ra-den",
"Immerseus","The Fallen Protectors","Amalgam of Corruption","Sha of Pride","Galakras","Iron Juggernaut","Earthbreaker Haromm","General Nazgrim","Malkorok","Thok the Bloodthirsty","Siegecrafter Blackfuse","Garrosh Hellscream",
};
GRSS_Bosses = {
-- WOD Bosses
"Kargath Bladefist", "The Butcher", "Brackenspore", "Tectus", "Pol", "Ko'ragh", "Imperator Mar'gok",
"Gruul","Oregorger", "Blast Furnace", "Hans'gar", "Flamebender Ka'graz", "Kromog", "Beastlord Darmac","Operator Thogar","Admiral Gar'an","Blackhand",
"Siegemaster Mar'tak", "Kormrok","Killrogg Deadeye","Gurtogg Bloodboil","Gorefiend","Shadow-Lord Iskar","Socrethar the Eternal","Tyrant Velhari","Fel Lord Zakuun","Xhul'horac","Mannoroth","Archimonde",
--[[ (TESTING) uncomment for testing the mobs outside shattrath and orgrimmar
"Dreadfang Lurker","Timber Worg","Ironspine Petrifier","Talrendis Scout","Weakened Mosshoof Stag"
--]]
};
GRSS_FastBossLookup = {}; --This gets initialized with the mod
GRSS_Ignore = {"Onyxian","Onyxia's Elite Guard","Maexxna Spiderling","Patchwerk Golem","Hakkari","Son of Hakkar"," slain by ","Nightbane .+",".+the Crone","Netherspite Infernal","Ember of Al'ar","Sartharion Twilight Whelp","Sartharion Twilight Egg"};
GRSS_Yells = {};
GRSS_LootIgnore = {"Hakkari Bijou","Alabaster Idol","Amber Idol","Azure Idol","Jasper Idol","Lambent Idol","Obsidian Idol","Onyx Idol","Vermillion Idol","Lava Core","Fiery Core","Large .+ Shard","Small .+ Shard","Nexus Crystal","Wartorn .+ Scrap","Badge of Justice","Cosmic Infuser","^Devastation$","Infinity Blade","Phaseshift Bulwark","Warp Slicer","Staff of Disintegration","Netherstrand Longbow","Nether Spike","Bundle of Nether Spikes","Emblem of Heroism","Emblem of Valor","Abyss Crystal","Emblem of Conquest","Emblem of Triumph","Emblem of Frost","Maelstrom Crystal"};
-- GRSS_Yells = Bosses that when they die trigger a snapshot
GRSS_Yells["Majordomo Executus"] = "Impossible!.+I submit!";
GRSS_Yells["Attumen the Huntsman"] = "Always knew.+the hunted";
GRSS_Yells["Freya"] = "His hold on me dissipates";
GRSS_Yells["Thorim"] = "Stay your arms!";
GRSS_Yells["Hodir"] = "I am released from his grasp";
GRSS_Yells["Mimiron"] = "I allowed my mind to be corrupted";
GRSS_Yells["Garrosh Hellscream"] = "That was just a taste of what the future brings. FOR THE HORDE!";
GRSS_Yells["King Varian Wrynn"] = "GLORY TO THE ALLIANCE!";
GRSS_Yells["High Overlord Saurfang"] = "The Alliance falter. Onward to the Lich King!";
GRSS_Yells["Muradin Bronzebeard"] = "Don't say I didn't warn ya, scoundrels! Onward, brothers and sisters!";
GRSS_Yells["Valithria Dreamwalker"] = "I am renewed!.+to rest!";
GRSS_Yells["Elementium Monstrosity"] = "IMPOSSIBLE";
GRSS_Yells["Omnitron"] = "Defense systems obliterated. Powering down.";
GRSS_Yells["Al'Akir"] = "The Conclave of Wind has dissipated.+";
GRSS_Yells["Lorewalker Cho"] = "A secret passage has opened beneath the platform, this way!";
GRSS_Yells["Elder Asani"] = "The Sha...must be...stopped.";
--GRSS_Yells["Chops"] = "this is a test";
-- GRSS_Yell_Redirects = Bosses that if they yell something from above, the snapshot gets recorded not as the name of the mob, but as the assignment
-- For example, in Garrosh Hellscream yells "That was just a test of what the future brings. FOR THE HORDE", the snapshot will be recorded as "Faction Champions"
GRSS_Yell_Redirect = {};
GRSS_Yell_Redirect["Garrosh Hellscream"] = "Faction Champions";
GRSS_Yell_Redirect["King Varian Wrynn"] = "Faction Champions";
GRSS_Yell_Redirect["High Overlord Saurfang"] = "Gunship Battle";
GRSS_Yell_Redirect["Muradin Bronzebeard"] = "Gunship Battle";
GRSS_Yell_Redirect["Elementium Monstrosity"] = "Twilight Ascendants";
GRSS_Yell_Redirect["Omnitron"] = "Omnitron Defense System";
GRSS_Yell_Redirect["Al'Akir"] = "Conclave of Wind";
GRSS_Yell_Redirect["Lorewalker Cho"] = "The Spirit Kings";
GRSS_Yell_Redirect["Elder Asani"] = "Protectors of the Endless";
--GRSS_Yell_Redirect["Chops"] = "Faction Champions Test";
-- GRSS_BossRedirects = When a specific boss dies, the snapshot is recorded as something else
-- In this case, if "Jade Guardian" dies, the snapshot is recorded as "The Stone Guard"
-- This is useful for bosses that are linked together and share health.
GRSS_Boss_Redirect = {};
GRSS_Boss_Redirect["Jade Guardian"] = "The Stone Guard";
GRSS_Boss_Redirect["Jan-xi"] = "Will of the Emperor";
GRSS_Boss_Redirect["Amalgam of Corruption"] = "Norushen";
GRSS_Boss_Redirect["Earthbreaker Haromm"] = "Kor'kron Dark Shaman";
GRSS_Boss_Redirect["Gurtogg Bloodboil"] = "Hellfire High Council";
GRSS_Boss_Redirect["Siegemaster Mar'tak"] = "Hellfire Assault";
GRSS_Boss_Redirect["Pol"] = "Twin Ogron";
GRSS_Boss_Redirect["Admiral Gar'an"] = "Iron Maidens";
--GRSS_Boss_Redirect["Weakened Mosshoof Stag"] = "Test Redirect";
-- GRSS_BossEmote = events that aren't yells or anything, but something represent "world emotes"
-- For the "Chess" event example from Burning Crusade's Karazhan, when the Chess events ends, there
-- is a world-emote like "The doors of the Gamesman's Hall shake...". This is how it triggers when the event happens
GRSS_BossEmote = {};
GRSS_BossEmote["Chess"] = "doors of the Gamesman's Hall";
-- GRSS_ZoneIgnore is probably no longer necessary, since GRSS already checks if you're in a PVP (Arena or Battleground)
GRSS_ZoneIgnore = {"Arathi Basin","Alterac Valley","Eye of the Storm","Warsong Gulch"};
GRSS_Auto = 1;
GRSS_LootCap = 1;
GRSS_Bidding = 0;
GRSS_Rolling = 0;
GRSS_BidRolls = nil;
GRSS_HighBid = 0;
GRSS_HighBidder = "";
GRSS_CurrentSort = "total";
GRSS_BidStyle = "Silent Auction";
GRSS_CurrentItem = "";
GRSS_ItemHistory = {};
GRSS_TakeScreenshots = 0;
GRSS_CurrentLootDate = "";
GRSS_CurrentLootIndex = 0;
GRSS_LastCommand = {};
GRSS_ItemPrices = {};
GRSS_RaidFilter = "All";
GRSS_ClassFilter = "All";
GRSS_ItemQueue = {};
GRSS_ItemBoxOpen = 0;
GRSS_Old_Bosses_On = false;
GRSS_WipeCauser = "Unknown";
GRSS_LastWipeTime = 0;
GRSS_LastSnapshot = 0;
GRSSNewVersionPrinted = nil;
GRSS_PopupPoints = 0;
GRSS_PopupLootDate = "";
GRSS_PopupLootIndex = "";
GRSS_WaitListRequest = {}; --This is functioning as a Queue of WaitingList requests
GRSS_WaitListRequestBoxOpen = 0;
GRSS_NumberedSystems = {};
GRSS_Loot = {};
GRSS_WaitingList = {};
GRSS_RaidSignups = {};
GRSS_InviteType = "Waiting List";
GRSS_RollNumber = 1000;
GRSS_RaidPointsPopup = 1;
GRSS_AutoWipe = 1;
GRSS_PendingSnapShotName = ""
GRSS_CurrentCalendarIndex = 1;
GRSS_LootPromptInCombat = 0;
GRSS_LastSnapShotName = "";
GRSS_Redistribute_SnapShot = "";
GRSS_Redistribute_SnapShot_ExpireTime = 0;
GRSS_DoingParty = 1;
GRSS_NextTime = nil;
GRSS_Period = 60;
GRSS_ReadyForTimer = false;
GRSS_Prefix = "GRSS: ";
GRSS_Guild = {};
GRSS_DKP = {};
GRSS_Bids = {};
GRSSCurrentSystem = "";
GRSSCurrentAction = "DKP Standings";
GRSSHelpMsg = {
"!help = This help menu",
"!dkp = Your current DKP",
"!dkp name [name2 name3...] = the DKP for the player 'name' (and name2 and name3) (i.e. !dkp Joe Fred)",
"!items = Your item history",
"!items name = Item history for player 'name' (i.e. !items Joe)",
"!bid X = Bid X points on the current item",
"!request = Put in a request for the item",
"!dkpclass class [class2 class3...] = the current standings for the 'class' (and 'class2' and 'class3') (i.e. !dkpclass mage warlock)",
"!dkpraid X = the current standings for DKP System X for current raid members (to get the list of appropriate Systems, just type !dkpraid)",
"!dkpall X = the current standings for DKP System X (to get the list of appropriate Systems, just type !dkpall)",
"!price itemname = the price of the item 'itemname' (parts of names work too, i.e. '!price felheart' will retrieve the prices of all items with 'felheart' in the name)",
"!waitlist = Add me to the Waiting List",
"!waitlistwho = Show a list of who's on the waiting list",
};
local GRSSVersion = "2.033";
local GRSSUsage = {
"Type |c00ffff00/grss <snapshotname>|r to take a snapshot (ex: |c00ffff00/grss Kel'Thuzad|r)",
"|c00ffff00/grss loot|r to open a loot prompt to manually record an item being received",
"|c00ffff00/grss adj|r to record an adjustment",
"|c00ffff00/grss reset|r to delete all your snapshots",
"|c00ffff00/grss show|r to bring up the DKP standings/bidding/rolling screen",
"|c00ffff00/grss invite|r to bring up the Waiting List/Auto-Invite screen",
"|c00ffff00/grss starttimer|r start Periodic Snapshots",
"|c00ffff00/grss stoptimer|r to disable Periodic Snapshots",
"|c00ffff00/grss noauto|r to disable auto-snapshot",
"|c00ffff00/grss yesauto|r to enable auto-snapshot",
"|c00ffff00/grss nosnapshotpopup|r to disable snapshot points popup asking how many points a snapshot is worth",
"|c00ffff00/grss yessnapshotpopup|r to enable snapshots points popup asking how many points a snapshot is worth",
"|c00ffff00/grss yesscreenshot|r to make snapshots also take a screenshot",
"|c00ffff00/grss noscreenshot|r to make snapshots NOT take a screenshot",
"|c00ffff00/grss yesloot|r to make Loot received (Blue and better) prompt for points spent",
"|c00ffff00/grss noloot|r to disable the loot prompt when items are received",
"|c00ffff00/grss yeswipe|r to enable the snapshot prompt when a wipe occurs",
"|c00ffff00/grss nowipe|r to disable the snapshot prompt when a wipe occurs",
"|c00ffff00/grss yeslootcombat|r allows the loot prompt to pop up in combat",
"|c00ffff00/grss nolootcombat|r forces the loot prompt to wait until out of combat (recommended unless you're having problems)",
"|c00ffff00/grss yesold|r enables old bosses to trigger a snapshot",
"|c00ffff00/grss noold|r disables old bosses triggering a snapshot",
"==========================================",
"Members can also send you tells like the following for information (you can even send yourself a tell for this info, too)",
};
local GRSS_Colors={
--[[
["ff9d9d9d"] = "grey",
["ffffffff"] = "white",
["ff00ff00"] = "green",
["ff0070dd"] = "rare",--]]
["ffa335ee"] = "epic",
["ffff8000"] = "legendary"
};
local GRSS_ChatFrame_OnEvent_Original = nil;
function GRSS_IsWhisperGRSSWhisper(e,t,w)
if string.find(w,"^!dkp") or string.find(w,"^!items") or string.find(w,"^!info") or string.find(w,"^!commands") or string.find(w,"^!price") or string.find(w,"^!waitlist") then
return true;
else
return false;
end
end
function GRSS_IsOutgoingWhisperGRSSWhisper(e,t,w)
if string.find(w,"^"..GRSS_Prefix) then
return true;
else
return false;
end
end
function GRSS_SetItemRef(link,text,button)
if GRSSCurrentAction ~= "DKP Standings" and GRSS_Bidding~=1 and GRSS_Rolling~=1 then
GRSSItemName:SetText(text);
end
end
function GRSS_EnableOldBosses()
GRSS_Old_Bosses_On = true;
GRSS_FastBossLookup = {};
for i,v in pairs(GRSS_Bosses) do
GRSS_FastBossLookup[v] = v;
end
for i,v in pairs(GRSS_Bosses_Old) do
GRSS_FastBossLookup[v] = v;
end
end
function GRSS_DisableOldBosses()
GRSS_Old_Bosses_On = false;
GRSS_FastBossLookup = {};
for i,v in pairs(GRSS_Bosses) do
GRSS_FastBossLookup[v] = v;
end
end
-- ******************************************************************
-- ************************** ENTRY POINT ***************************
-- ******************************************************************
function GuildRaidSnapShot_OnLoad(this)
SlashCmdList["GuildRaidSnapShot"] = GuildRaidSnapShot_SlashHandler;
SLASH_GuildRaidSnapShot1 = "/grss";
SLASH_GuildRaidSnapShot1 = "/GRSS";
if GRSS_Old_Bosses_On == true then
GRSS_EnableOldBosses();
else
GRSS_DisableOldBosses();
end
this:RegisterEvent("PLAYER_REGEN_ENABLED");
this:RegisterEvent("PLAYER_REGEN_DISABLED");
this:RegisterEvent("PLAYER_DEAD");
this:RegisterEvent("CHAT_MSG_COMBAT_FRIENDLY_DEATH");
this:RegisterEvent("CHAT_MSG_COMBAT_HOSTILE_DEATH");
this:RegisterEvent("PLAYER_TARGET_CHANGED");
this:RegisterEvent("CHAT_MSG_LOOT");
this:RegisterEvent("CHAT_MSG_MONSTER_YELL");
--this:RegisterEvent("CHAT_MSG_YELL");
this:RegisterEvent("CHAT_MSG_RAID_BOSS_EMOTE");
this:RegisterEvent("PLAYER_GUILD_UPDATE");
this:RegisterEvent("GUILD_ROSTER_UPDATE");
this:RegisterEvent("CHAT_MSG_WHISPER");
this:RegisterEvent("CHAT_MSG_SYSTEM");
this:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED");
this:RegisterEvent("LOOT_OPENED");
this:RegisterEvent("RAID_ROSTER_UPDATE");
this:RegisterEvent("VARIABLES_LOADED");
this:RegisterEvent("CALENDAR_OPEN_EVENT");
this:RegisterEvent("CALENDAR_UPDATE_EVENT");
this:RegisterEvent("CALENDAR_UPDATE_EVENT_LIST");
this:RegisterEvent("CALENDAR_NEW_EVENT");
--
--
this:RegisterEvent("ADDON_LOADED");
DEFAULT_CHAT_FRAME:AddMessage("GuildRaidSnapShot (By DKPSystem.com) Version "..GRSSVersion.." loaded. ");
DEFAULT_CHAT_FRAME:AddMessage("Type |c00ffff00/grss|r to get a list of options for GuildRaidSnapShot");
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER",GRSS_IsWhisperGRSSWhisper); -- incoming whispers
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER_INFORM",GRSS_IsOutgoingWhisperGRSSWhisper); --outgoing whispers
hooksecurefunc("SetItemRef",GRSS_SetItemRef);
StaticPopupDialogs["GRSS_ITEMPOINTS"] = {
text = "How many points did |c00ffff00%s|r spend on %s",
button1 = "OK",
button2 = "Cancel",
OnAccept = function(self)
points = self.editBox:GetText()
GRSSRecordItemPointsOnly(points);
end,
OnShow = function(self)
GRSS_ItemBoxOpen = 1;
self.editBox:SetText(GRSS_PopupPoints);
end,
OnHide = function(self)
if table.getn(GRSS_ItemQueue) > 0 then
GRSS_NextItemPopup();
else
GRSS_ItemBoxOpen = 0;
end
end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
hasEditBox = 1,
enterClicksFirstButton = 1,
};
StaticPopupDialogs["GRSS_RAIDPOINTS"] = {
text = "How many points should be awarded for the attendees in the snapshot called |c00ffff00%s|r?. Enter |c00ff0000zs|r if you want to award points based on the following loot (items awarded for the next 10 minutes)",
button1 = "OK",
button2 = "Cancel",
OnAccept = function(self)
points = self.editBox:GetText()
GRSSSetSnapshotPoints(points);
end,
OnShow = function(self)
GRSS_SnapshotBoxOpen = 1;
self.editBox:SetText(GRSS_LastSnapShotPoints);
end,
OnHide = function(self)
end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
hasEditBox = 1,
enterClicksFirstButton = 1,
};
StaticPopupDialogs["GRSS_WAITINGLIST"] = {
text = "Name of person(s) to add to waiting list? If adding more than one, seperate by a space",
button1 = "OK",
button2 = "Cancel",
OnAccept = function(self)
name = self.editBox:GetText();
GRSS_AddNameToWaitingList(name);
end,
OnShow = function(self)
self.editBox:SetText("")
end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
hasEditBox = 1,
enterClicksFirstButton = 1,
};
StaticPopupDialogs["GRSS_RAIDCHECK"] = {
text = "There are %s recorded right now. Would you like to keep this data (and apply any expenditures to the current standings) or would you like to purge all the data. You should ONLY purge if you've already uploaded your snapshots.",
button1 = "Purge",
button2 = "Keep",
OnAccept = function(self)
GuildRaidSnapShot_SnapShots = {};
GuildRaidSnapShot_Loot = {};
GuildRaidSnapShot_Adj = {};
GRSSPrint("Snapshots Purged");
end,
OnCancel = function(self)
GRSS_RecalcSpentLoot();
end,
timeout = 0,
whileDead = 1,
};
StaticPopupDialogs["GRSS_TIMERCHECK"] = {
text = "The timer is currently running to take snapshots. The next snapshot is set to be taken in |c00ffff00%s minutes|r. Continue the periodic snapshots, or Stop the Timer?",
button1 = "Continue",
button2 = "Stop Timer",
OnAccept = function(self)
GRSS_ReadyForTimer = true;
local mins = GRSS_NextTime - GetTime();
if mins > 0 then
mins = math.floor(mins / 60);
GRSSPrint("The next snapshot wlll be in "..mins.." minutes");
end
end,
OnCancel = function(self)
GRSS_NextTime = nil;
GRSS_ReadyForTimer = true;
GRSSPrint("Snapshot Timer Stopped");
end,
timeout = 0
};
StaticPopupDialogs["GRSS_STARTTIMER"] = {
text = "How many minutes between snapshots?",
button1 = "OK",
button2 = "Cancel",
OnAccept = function(self)
mins = self.editBox:GetText();
if tonumber(mins) == nil then
GRSSPrint(mins.." isn't exactly a number, is it?");
else
GRSS_StartTimer(mins);
end
end,
OnShow = function(self)
self.editBox:SetText(GRSS_Period);
end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
hasEditBox = 1,
enterClicksFirstButton = 1,
};
StaticPopupDialogs["GRSS_WIPE"] = {
text = "Was this a wipe? If so, and if you want to take a snapshot, enter the name of the snapshot and click 'Record Wipe', otherwise, click Cancel",
button1 = "Record Wipe",
button2 = "Cancel",
OnAccept = function(self)
name = self.editBox:GetText()
GRSS_TakeSnapShot(name);
end,
OnShow = function(self)
self.editBox:SetText("Wipe on "..GRSS_WipeCauser);
end,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
hasEditBox = 1,
enterClicksFirstButton = 1,
};
StaticPopupDialogs["GRSS_AUTOWAITLIST"] = {
text = "|c00ffff00%s|r is requesting to be added to the Wait List. Accept or Deny?",
button1 = "Accept",
button2 = "Deny",
OnAccept = function(self)
local last = table.getn(GRSS_WaitListRequest);
local name = GRSS_WaitListRequest[last];
GRSS_AddNameToWaitingList(name);
GRSS_SendWhisper("You've been added to the waiting list","WHISPER",nil,name);
end,
OnCancel = function(self)
local last = table.getn(GRSS_WaitListRequest);
local name = GRSS_WaitListRequest[last];
GRSS_SendWhisper("Your request to be added to the waiting list has been denied","WHISPER",nil,name);
end,
OnHide = function(self)
table.remove(GRSS_WaitListRequest);
if table.getn(GRSS_WaitListRequest) > 0 then
GRSS_NextWaitListRequest();
else
GRSS_WaitListRequestBoxOpen = 0;
end
end,
onShow = function(self)
GRSS_WaitListRequestBoxOpen = 1;
end,
timeout = 0,
whileDead = 1,
};
end
function GRSS_GetCalendar()
local curmonth,curyear;
_,curmonth,_,curyear = CalendarGetDate();
if(GRSS_Calendar == nil) then
GRSS_Calendar = {};
end
local keepers = {}
for m = -1,1 do
for d=1,31 do
local numevents = CalendarGetNumDayEvents(0,d);
--GRSSPrint("Num Events:"..numevents);
if numevents > 0 then
for e=1,numevents do
local title, hour, minute, caltype,_,eventtype = CalendarGetDayEvent(m,d,e);
if eventtype > 0 then
if caltype=="GUILD" or caltype=="GUILD_EVENT" or caltype=="PLAYER" then
month = curmonth + m;
year = curyear;
if(month < 0) then
year = year - 1;
month = 12;
elseif(month > 12) then
year = year + 1;
month = 1;
end
local found = GRSS_FindEvent(title,year,month,d,hour,minute);
if found == nil then
local event = {
title = title,
monthoffset = m,
month = month,
year = year,
day = d,
eventindex = e,
hour = hour,
minute = minute,
eventtype = eventtype
}
table.insert(GRSS_Calendar,event);
found = table.getn(GRSS_Calendar);
end
keepers[found] = found;
end
end
end
end
end
end
for i,v in pairs(GRSS_Calendar) do
if keepers[i]==nil then
GRSS_Calendar[i] = nil;
end
end
end
function GRSS_FindEvent(title,year,month,day,hour,minute)
for i,e in pairs(GRSS_Calendar) do
if(e.title == title and e.month==month and e.day==day and e.hour==hour and e.minute==minute and e.year==year) then
return i;
end
end
return nil;
end
function GRSS_StoreEventDetails()
local title, desc, creator,eventtype,_,maxsize,_,_,month,day,year,hour,minute = CalendarGetEventInfo();
local i = GRSS_FindEvent(title,year,month,day,hour,minute);
if i ~= nil then
GRSS_Calendar[i].description = desc;
GRSS_Calendar[i].creator = creator;
GRSS_Calendar[i].maxsize = maxsize;
local numinvites = CalendarEventGetNumInvites();
local invites = {}
for ii = 1,numinvites do
local name,level,className,_,inviteStatus,modStatus = CalendarEventGetInvite(ii);
local _,s_month, s_day, s_year, s_hour, s_minute = CalendarEventGetInviteResponseTime(ii);
local signuptime;
if s_year==0 then
signuptime = month.."/"..day.."/"..year.." "..hour..":"..minute;
else
signuptime = s_month.."/"..s_day.."/"..s_year.." "..s_hour..":"..s_minute;
end
local inv = {
name = name,
level = level,
class = className,
status = inviteStatus,
signuptime = signuptime,
};
table.insert(invites,inv);
end
GRSS_Calendar[i].invites = invites;
end
end
function GRSS_StartTimer(mins)
GRSS_Period = mins;
GRSS_NextTime = GetTime() + (GRSS_Period*60);
GRSS_TakeSnapShot("Periodic Snapshot");
GRSSPrint("Periodic Snapshots Started. Next Snapshot will be in "..mins.." minutes");
end
function GRSS_StopTimer()
GRSS_Period = nil;
GRSS_NextTime = nil;
GRSSPrint("Periodic Snapshots Halted");
end
function GRSS_Timer_OnUpdate()
if GRSS_ReadyForTimer and GRSS_Period and GRSS_NextTime then
local now = GetTime();
if now > GRSS_NextTime then
GRSS_TakeSnapShot("Periodic Snapshot");
GRSSPrint("Next snapshot will be in "..GRSS_Period.." minutes");
GRSS_NextTime = GetTime() + (GRSS_Period*60);
--GRSS_TimerNotify = {};
end
end
--GRSSPrint("update");
if type(GRSS_GeneralTimer)=="function" then
local now = GetTime();
if now > GRSS_GeneralTimeout then
GRSSPrint("Timeout");
GRSS_GeneralTimer();
GRSS_GeneralTimer = nil;
GRSS_GeneralTimeout = nil;
end
end
end
function GRSS_StartGeneralTimer(seconds,fun)
GRSS_GeneralTimer = fun;
GRSS_GeneralTimeout = GetTime() + seconds;
end
function GRSS_NextItemPopup()
if table.getn(GRSS_ItemQueue) > 0 then
local i = table.getn(GRSS_ItemQueue);
local item, name, points;
GRSS_PopupLootDate = GRSS_ItemQueue[i].date;
GRSS_PopupLootIndex = GRSS_ItemQueue[i].index;
item = GRSS_ItemQueue[i].item;
name = GRSS_ItemQueue[i].name;
GRSS_PopupPoints = GRSS_ItemQueue[i].points;
table.remove(GRSS_ItemQueue,i);
StaticPopup_Show("GRSS_ITEMPOINTS",name,item);
end
end
function GRSS_EnqueueItem(date,index,name,item,points)
local temp = {};
temp.date = date;
temp.index = index;
temp.name = name;
temp.item = item;
temp.points = points;
table.insert(GRSS_ItemQueue,1,temp);
end
function GRSSLootSave()
local system = UIDropDownMenu_GetText(GRSSLootSystemDropDown);
local player = GRSSLootPlayer:GetText();
local points = GRSSLootPoints:GetText();
local item = GRSSLootItem:GetText();
GRSSLootClear();
GRSSRecordItem(system,player,item,points);
end
function GRSSRecordItemPointsOnly(points)
local lootrec = GuildRaidSnapShot_Loot[GRSS_PopupLootDate][GRSS_PopupLootIndex];
local playername = lootrec.player;
local sys = lootrec.system;
local hardpoints = GRSSPlayerPointCost(playername,sys,points);
GuildRaidSnapShot_Loot[GRSS_PopupLootDate][GRSS_PopupLootIndex].points = points;
GuildRaidSnapShot_Loot[GRSS_PopupLootDate][GRSS_PopupLootIndex].hardpoints = hardpoints;
GRSS_RecordCurrentPlayerReceivedItem(points);
if GRSS_Redistributing() then
GRSSObamaPoints(hardpoints)
end
end
function GRSSAdjSave()
local system = UIDropDownMenu_GetText(GRSSAdjSystemDropDown);
local player = GRSSAdjPlayer:GetText();
local points = GRSSAdjPoints:GetText();
local desc = GRSSAdjDesc:GetText();
local adjtype = "";
if GRSS_Divide[system] then
adjtype = GRSS_GetAdjType();
end
GRSSAdjClear();
GRSSRecordAdj(system,player,item,points,adjtype,desc);
end
function GRSSRecordItem(system,player,item,points)
local lootdate = date("%Y-%m-%d");
if(GuildRaidSnapShot_Loot[lootdate] == nil) then
GuildRaidSnapShot_Loot[lootdate] = {};
end
local iteminfo = {};
iteminfo.player = player;
iteminfo.item = item;
iteminfo.RealmName = GetRealmName();
iteminfo.date = date("%Y-%m-%d %H:%M:%S");
iteminfo.system = system;
iteminfo.points = points;
iteminfo.hardpoints = GRSSPlayerPointCost(player,system,points);
if GRSS_Redistributing() then
GRSSObamaPoints(iteminfo.hardpoints);
end
table.insert(GuildRaidSnapShot_Loot[lootdate],iteminfo);
if points ~= nil then
GRSSAddPoints(player,system,"spent",iteminfo.hardpoints);
end
return lootdate;
end
function GRSSRecordAdj(system,player,item,points,adjtype,desc)
local lootdate = date("%Y-%m-%d");
if(GuildRaidSnapShot_Adj[lootdate] == nil) then
GuildRaidSnapShot_Adj[lootdate] = {};
end
local adjinfo = {};
adjinfo.player = player;
adjinfo.item = item;
adjinfo.RealmName = GetRealmName();
adjinfo.date = date("%Y-%m-%d %H:%M:%S");
adjinfo.system = system;
adjinfo.points = points;
adjinfo.adjtype = adjtype;
adjinfo.description = desc;
table.insert(GuildRaidSnapShot_Adj[lootdate],adjinfo);
if points ~= nil then
if GRSS_Divide[system] then
GRSSAddPoints(player,system,adjtype,points);
else
GRSSAddPoints(player,system,"adj",points);
end
end
return lootdate;
end
function GRSSLootClear()
getglobal("GRSSLootPlayer"):SetText("");
getglobal("GRSSLootPoints"):SetText("");
getglobal("GRSSLootItem"):SetText("");
end
function GRSSAdjClear()
getglobal("GRSSAdjPlayer"):SetText("");
getglobal("GRSSAdjPoints"):SetText("");
getglobal("GRSSAdjDesc"):SetText("");
end
function GRSS_RecalcSpentLoot()
if GuildRaidSnapShot_Loot then
for ld,daytable in pairs(GuildRaidSnapShot_Loot) do
for lootindex,loottable in pairs(daytable) do
if loottable.system == nil or GRSS_Systems[loottable.system]==nil then
loottable.system = GRSSCurrentSystem
end
--points = GRSSPlayerPointCost(loottable.player,loottable.system,loottable.points);
points = loottable.hardpoints;
if tonumber(points) == nil then
points = loottable.points;
end
if tonumber(points) ~= nil then
GRSSAddPoints(loottable.player,loottable.system,"spent",points);
end
end
end
end
if GuildRaidSnapShot_Adj then
for ld,daytable in pairs(GuildRaidSnapShot_Adj) do
if daytable then
for adjindex,adjtable in pairs(daytable) do
if adjtable.system == nil or GRSS_Systems[adjtable.system]==nil then
adjtable.system = GRSSCurrentSystem
end
points = adjtable.points;
if tonumber(points) ~= nil then
if GRSS_Divide[adjtable.system] then
adjtype = adjtable.adjtype;
else
adjtype = "adj";
end
GRSSAddPoints(adjtable.player,adjtable.system,adjtype,points);
end
end
end
end
end
if GuildRaidSnapShot_SnapShots then
for snapshot in pairs(GuildRaidSnapShot_SnapShots) do
GRSSAddSnapshotPoints(snapshot);
end
GRSSChangeSystem(GRSSCurrentSystem);
end
end
function GRSSSetSnapshotPoints(points)
if string.lower(points)=="zs" or string.lower(points)=="sz" then
GRSSPrint("All Items received for the next 15 minutes will get redistributed and associated with this snapshot");
GRSS_Redistribute_SnapShot = GRSS_LastSnapShotName;
GRSS_Redistribute_SnapShot_ExpireTime = GetTime() + 15*60; -- Expire in 15 minutes
GuildRaidSnapShot_SnapShots[GRSS_LastSnapShotName].redistribute = 1;
GuildRaidSnapShot_SnapShots[GRSS_LastSnapShotName].points = 0;
else
GuildRaidSnapShot_SnapShots[GRSS_LastSnapShotName].points = points;
end
GRSSAddSnapshotPoints(GRSS_LastSnapShotName);
end
-- This works for the whole snapshot
function GRSSAddSnapshotPoints(snapshotname)
local points = GRSSNumNilZero(GuildRaidSnapShot_SnapShots[snapshotname].points);
local sys = GuildRaidSnapShot_SnapShots[snapshotname].system;
local players = GRSS_ParsePlayers(GuildRaidSnapShot_SnapShots[snapshotname].Raid);
if GuildRaidSnapShot_SnapShots[snapshotname].redistribute then
points = points/table.getn(players);
end
for _,mem in pairs(players) do
GRSSAddPoints(mem,sys,"earned",points);
end
end
-- Obama = Redistribution, get it? OLZOLZOLZ
-- This works only for newly added items, to adjust the previous value of a snapshot when an item is received and redistributed
function GRSSObamaPoints(totalpoints)
local snapshotname = GRSS_Redistribute_SnapShot;
local curpoints = GuildRaidSnapShot_SnapShots[snapshotname].points;
local sys = GuildRaidSnapShot_SnapShots[snapshotname].system;
local players = GRSS_ParsePlayers(GuildRaidSnapShot_SnapShots[snapshotname].Raid);
local newpoints = curpoints + totalpoints;
GuildRaidSnapShot_SnapShots[snapshotname].points = newpoints;
local toadd = totalpoints / table.getn(players);
for _,mem in pairs(players) do
GRSSAddPoints(mem,sys,"earned",toadd);
end
end
-- Returns the snapshot name if we are redistributing, else, returns nil
function GRSS_Redistributing()
if GRSS_Redistribute_SnapShot_ExpireTime > 0 and GetTime() < GRSS_Redistribute_SnapShot_ExpireTime then
return GRSS_Redistribute_SnapShot;
else
return nil;
end
end
function GRSSTrim (s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
function GRSS_ParsePlayers(str)
local retarr = {};
local pzarr = { strsplit(",",str) }; -- Players with Zones
for _,pz in pairs(pzarr) do
local p,z = strsplit(":",pz);
if(z~="Offline") then
table.insert(retarr,GRSSTrim(p));
end
end
return retarr;
end
function GRSS_PendingSnapshotCheck()
local items = 0;
local snapshots = 0;
local adjustments = 0;
for _ in pairs(GuildRaidSnapShot_SnapShots) do
snapshots = snapshots + 1;
end
for i,v in pairs(GuildRaidSnapShot_Adj) do
adjustments = adjustments + table.getn(v);
end
for i,v in pairs(GuildRaidSnapShot_Loot) do
items = items + table.getn(v);
end
if snapshots > 0 or items > 0 or adjustments > 0 then
local msg = items.." items, "..snapshots.." snapshots, and "..adjustments.." adjustments";
StaticPopup_Show("GRSS_RAIDCHECK",msg);
end
end
function GRSS_TimerRunningCheck()
if GRSS_NextTime then
local mins = math.floor((GRSS_NextTime - GetTime())/60);
if mins < 0 then
mins = 0
end
GRSSPrint("timercheck");
StaticPopup_Show("GRSS_TIMERCHECK",mins);
else
GRSS_ReadyForTimer = true;
end
end
--
function GRSS_RecordCurrentPlayerReceivedItem(pointstr)
playername = string.lower(GuildRaidSnapShot_Loot[GRSS_PopupLootDate][GRSS_PopupLootIndex].player);
normalplayername = GuildRaidSnapShot_Loot[GRSS_PopupLootDate][GRSS_PopupLootIndex].player;
points = GRSSPlayerPointCost(playername,GRSSCurrentSystem,pointstr);
if tonumber(points) ~= nil and tonumber(points) ~= 0 then
points = tonumber(points);
GRSSAddPoints(normalplayername,GRSSCurrentSystem,"spent",points);
temp = "Today: "..normalplayername.." <-- "..GuildRaidSnapShot_Loot[GRSS_PopupLootDate][GRSS_PopupLootIndex].item.." for "..points;
if GRSS_ItemHistory[string.upper(playername)] ~= nil then
table.insert(GRSS_ItemHistory[string.upper(playername)],temp);
else
GRSS_ItemHistory[string.upper(playername)] = {};
GRSS_ItemHistory[string.upper(playername)][0] = temp;
end
GRSSScrollBar_Update();
end
end
function GRSS_GetItemPoints(item)
for i,v in pairs(GRSS_ItemPrices[GRSSCurrentSystem]) do
if string.lower(item)==string.lower(v.name) then
return v.points;
end
end
return "";
end
--Sorts the Temp table GRSS_DKP
function GRSSSortBy(sort)
GRSS_CurrentSort = sort;
table.sort(GRSS_DKP,
function(a,b)
if sort=="spent" then
if GRSSCurrentAction == "DKP Standings" then
return GRSSNum(a.spent) > GRSSNum(b.spent);
elseif GRSSCurrentAction == "Rolls" or GRSSCurrentAction=="DKP+Roll" then
return GRSSNum(a.roll) > GRSSNum(b.roll);
elseif GRSSCurrentAction == "Bids" or GRSSCurrentAction == "Bid+Roll" then
return GRSSNum(a.bid) > GRSSNum(b.bid);
end
elseif sort=="bidroll" or (GRSSCurrentAction=="Bid+Roll" and sort=="adj") then
return GRSSNumNilZero(a.roll) + GRSSNumNilZero(a.bid) > GRSSNumNilZero(b.roll) + GRSSNumNilZero(b.bid);
elseif sort=="rankid" then
return GRSSNum(a.rankid) < GRSSNum(b.rankid);
elseif a[sort]==b[sort] then
return GRSSNum(a.total) > GRSSNum(b.total);
elseif sort=="name" or sort=="class" then
return (string.lower(a[sort]) < string.lower(b[sort]))
else
return (GRSSNum(a[sort]) > GRSSNum(b[sort]))
end
end
);
GRSSScrollBar_Update();
end
--Sorts the Full table generated by the downloader: GRSS_Full_DKP
function GRSSSortByFull(sort,sys)
table.sort(GRSS_Full_DKP[sys],
function(a,b)
if sort=="spent" then
if GRSSCurrentAction == "DKP Standings" then
return GRSSNum(a.spent) > GRSSNum(b.spent);
elseif GRSSCurrentAction == "Rolls" then
return GRSSNum(a.roll) > GRSSNum(b.roll);
elseif GRSSCurrentAction == "Bids" then
return GRSSNum(a.bid) > GRSSNum(b.bid);
end
elseif a[sort]==b[sort] then
return GRSSNum(a.earned) + GRSSNum(a.adj) - GRSSNum(a.spent) > GRSSNum(b.earned) + GRSSNum(b.adj) - GRSSNum(b.spent);
elseif sort=="name" or sort=="class" then
return (string.lower(a[sort]) < string.lower(b[sort]))
else
return (GRSSNum(a[sort]) > GRSSNum(b[sort]))
end
end
);
end
function GRSSChangeSystem(sys)
if sys ~= nil and GRSS_Full_DKP[sys]~=nil then
local inc = 1;
local i,v;
local top = table.getn(GRSS_Full_DKP[sys]);
GRSS_DKP = {};
local RaidTable = GRSS_RaidTable();
if GRSS_RaidFilter == "Raid Only" and GRSS_MainOnly[sys] then
for name,v in pairs(RaidTable) do
if GRSS_Alts[string.lower(name)] then
RaidTable[string.upper(GRSS_Alts[string.lower(name)])] = 1;
end
end
end
if(GRSS_RaidFilter == "" or GRSS_RaidFilter == nil) then
GRSS_RaidFilter = "All";
end
for i=1,top do
if GRSS_RaidFilter == "All" or RaidTable[string.upper(GRSS_Full_DKP[sys][i].name)]==1 then
if GRSS_ClassFilter == "All" or string.upper(GRSS_Full_DKP[sys][i].class) == string.upper(GRSS_ClassFilter) then
GRSS_DKP[inc] = {};
GRSS_DKP[inc].name = GRSS_Full_DKP[sys][i].name;
GRSS_DKP[inc].class = GRSS_Full_DKP[sys][i].class;
GRSS_DKP[inc].earned = GRSS_Full_DKP[sys][i].earned;
GRSS_DKP[inc].spent = GRSS_Full_DKP[sys][i].spent;
GRSS_DKP[inc].adj = GRSS_Full_DKP[sys][i].adj;
if GRSS_Divide and GRSS_Divide[sys] then
GRSS_DKP[inc].total = GRSS_DKP[inc].earned/GRSSNumNilOne(GRSS_DKP[inc].spent);
else
GRSS_DKP[inc].total = GRSS_DKP[inc].earned + GRSS_DKP[inc].adj - GRSS_DKP[inc].spent
end
GRSS_DKP[inc].bid = ""
GRSS_DKP[inc].roll = ""
GRSS_DKP[inc].rank = GRSS_Full_DKP[sys][i].rank;
GRSS_DKP[inc].rankid = GRSS_Full_DKP[sys][i].rankid;
inc = inc + 1;
end
end
end
GRSSScrollBar_Update();
GRSSSortBy("total");
GRSSScrollBar:Show();
if table.getn(GRSS_NumberedSystems)==0 then
for mysys in pairs(GRSS_Systems) do
table.insert(GRSS_NumberedSystems,mysys);
end
end
end
end
function GRSSGenerateBids()
GRSS_Bids = {};
local temp = {};
local n = 24;
local m = table.getn(GRSS_DKP);
for i=1,n do
temp = {};
temp.name = GRSS_DKP[math.random(m)].name;
temp.bid = math.random(1000);
table.insert(GRSS_Bids,temp);
end
GRSSBidsScrollBar_Update();
end
function GRSSNum(v)
v = tonumber(v);
if v == nil then
v = -9999999
end
return v;
end
function GRSSNumNilOne(v)
v = tonumber(v);
if v==nil or v==0 then
v = 1;
end
return v;
end
function GRSSNumNilZero(v)
v = tonumber(v);
if v == nil then
v = 0
end
return v;
end
function GRSSScrollBar_Update()
local line; -- 1 through 10 of our window to scroll
local lineplusoffset; -- an index into our data calculated from the scroll offset
local earned,sent,adj;
FauxScrollFrame_Update(GRSSScrollBar,table.getn(GRSS_DKP),10,16);
for line=1,10 do
lineplusoffset = line + FauxScrollFrame_GetOffset(GRSSScrollBar);
if lineplusoffset <= table.getn(GRSS_DKP) then
earned = "";
spent = "";
adj = "";
total = GRSS_DKP[lineplusoffset].total; -- Default Val for that
if GRSSCurrentAction == "DKP Standings" then
spent = GRSS_DKP[lineplusoffset].spent;
earned = GRSS_DKP[lineplusoffset].earned;
adj = GRSS_DKP[lineplusoffset].adj;
elseif GRSSCurrentAction == "Rolls" then
spent = GRSS_DKP[lineplusoffset].roll;
elseif GRSSCurrentAction == "Bids" then
spent = GRSS_DKP[lineplusoffset].bid;
elseif GRSSCurrentAction == "Bid+Roll" then
earned = GRSS_DKP[lineplusoffset].roll;
spent = GRSS_DKP[lineplusoffset].bid;
adj = GRSSNumNilZero(earned) + GRSSNumNilZero(spent);
if adj==0 then
adj = "";
end
elseif GRSSCurrentAction == "DKP+Roll" then
earned = GRSS_DKP[lineplusoffset].roll;
if GRSSNumNilZero(earned) > 0 then
adj = GRSSNumNilZero(earned) + total;
end
end
getglobal("GRSSRow"..line.."FieldPlayer"):SetText(GRSS_DKP[lineplusoffset].name);
getglobal("GRSSRow"..line.."FieldClass"):SetText(GRSS_DKP[lineplusoffset].class);
getglobal("GRSSRow"..line.."FieldRank"):SetText(GRSS_DKP[lineplusoffset].rank);
getglobal("GRSSRow"..line.."FieldEarned"):SetText(earned);
getglobal("GRSSRow"..line.."FieldSpent"):SetText(spent);
getglobal("GRSSRow"..line.."FieldAdj"):SetText(adj);
if tonumber(GRSS_DKP[lineplusoffset].total) ~= nil then
getglobal("GRSSRow"..line.."FieldDKP"):SetText(string.format("%.2f",GRSS_DKP[lineplusoffset].total));
else
getglobal("GRSSRow"..line.."FieldDKP"):SetText(GRSS_DKP[lineplusoffset].total);
end
getglobal("GRSSRow"..line.."FieldPlayer"):Show();
getglobal("GRSSRow"..line.."FieldClass"):Show();
getglobal("GRSSRow"..line.."FieldRank"):Show();
getglobal("GRSSRow"..line.."FieldEarned"):Show();
getglobal("GRSSRow"..line.."FieldSpent"):Show();
getglobal("GRSSRow"..line.."FieldAdj"):Show();
getglobal("GRSSRow"..line.."FieldDKP"):Show();
getglobal("GRSSRow"..line.."FieldHighlight"):Show();
else
getglobal("GRSSRow"..line.."FieldPlayer"):Hide();
getglobal("GRSSRow"..line.."FieldClass"):Hide();
getglobal("GRSSRow"..line.."FieldRank"):Hide();
getglobal("GRSSRow"..line.."FieldEarned"):Hide();
getglobal("GRSSRow"..line.."FieldSpent"):Hide();
getglobal("GRSSRow"..line.."FieldAdj"):Hide();
getglobal("GRSSRow"..line.."FieldDKP"):Hide();
getglobal("GRSSRow"..line.."FieldHighlight"):Hide();
end
end
end
function GRSSBidsScrollBar_Update()
local line; -- 1 through 10 of our window to scroll
local lineplusoffset; -- an index into our data calculated from the scroll offset
local earned,sent,adj;
FauxScrollFrame_Update(GRSSBidsScrollBar,table.getn(GRSS_Bids),23,16);
for line=1,23 do
lineplusoffset = line + FauxScrollFrame_GetOffset(GRSSBidsScrollBar);
if lineplusoffset <= table.getn(GRSS_Bids) then
getglobal("GRSSBidsRow"..line.."FieldPlayer"):SetText(GRSS_Bids[lineplusoffset].name);
getglobal("GRSSBidsRow"..line.."FieldBid"):SetText(GRSS_Bids[lineplusoffset].bid);
getglobal("GRSSBidsRow"..line.."FieldBidType"):SetText(GRSS_Bids[lineplusoffset].bidtype);
getglobal("GRSSBidsRow"..line.."FieldPlayer"):Show();
getglobal("GRSSBidsRow"..line.."FieldBid"):Show();
getglobal("GRSSBidsRow"..line.."FieldBidType"):Show();
getglobal("GRSSBidsRow"..line.."Delete"):Show();
getglobal("GRSSBidsRow"..line.."FieldHighlight"):Show();
else
getglobal("GRSSBidsRow"..line.."FieldPlayer"):Hide();
getglobal("GRSSBidsRow"..line.."FieldBid"):Hide();
getglobal("GRSSBidsRow"..line.."FieldBidType"):Hide();
getglobal("GRSSBidsRow"..line.."FieldHighlight"):Hide();
getglobal("GRSSBidsRow"..line.."Delete"):Hide();
end
end
end
function nn(v)
if v == nil then
return "nil"
else
return v;
end
end
function GuildRaidSnapShot_OnEvent(this,event,...)
local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 = ...;
if(event == "CHAT_MSG_MONSTER_YELL" --[[or event == "CHAT_MSG_YELL"--]]) then
if GRSS_Auto==1 and GRSS_Yells[arg2] ~= nil then
if string.find(arg1,GRSS_Yells[arg2]) ~= nil then
if GRSS_Yell_Redirect[arg2] ~= nil then
arg2 = GRSS_Yell_Redirect[arg2];
end
if InCombatLockdown() then
GRSS_PendingSnapShotName = arg2;
else
GRSS_TakeSnapShot(arg2);
end
end
end
elseif(event == "CHAT_MSG_RAID_BOSS_EMOTE") then
if GRSS_Auto == 1 then
for i,v in ipairs(GRSS_BossEmote) do
if string.find(arg1,v) then
if InCombatLockdown() then
GRSS_PendingSnapShotName = i;
else
GRSS_TakeSnapShot(i);
end
end
end
end
elseif(event == "PLAYER_REGEN_ENABLED") then
if GRSS_PendingSnapShotName ~= "" then
GRSS_TakeSnapShot(GRSS_PendingSnapShotName);
GRSS_PendingSnapShotName = "";
end
if table.getn(GRSS_ItemQueue) > 0 then
GRSS_NextItemPopup();
end
if table.getn(GRSS_WaitListRequest)>0 then
GRSS_NextWaitListRequest()
end
elseif(event=="PLAYER_DEAD" or event=="CHAT_MSG_COMBAT_FRIENDLY_DEATH") then
GRSS_WipeCheck();
elseif(event=="COMBAT_LOG_EVENT_UNFILTERED") then
if(arg2=="PARTY_KILL" or arg2=="UNIT_DIED") then
if not IsActiveBattlefieldArena() then
local bossname = arg9;
if GRSS_FastBossLookup[bossname] ~= nil and GRSS_Auto == 1 then
if GRSS_Boss_Redirect[bossname] ~= nil then
bossname = GRSS_Boss_Redirect[bossname];
end
if InCombatLockdown() then
GRSS_PendingSnapShotName = bossname;
else
GRSS_TakeSnapShot(bossname);
end
end
end
end
elseif(event=="PLAYER_TARGET_CHANGED") then
local name = UnitName("target");
if name ~= nil and GRSS_FastBossLookup[name]~= nil then
GRSS_WipeCauser = name;
end
elseif(event == "PLAYER_GUILD_UPDATE") then
GuildRoster();
elseif(event == "VARIABLES_LOADED") then
GRSSInviteScrollBar_Update();
GRSS_PendingSnapshotCheck();
GRSS_TimerRunningCheck();
elseif(event == "CALENDAR_OPEN_EVENT" or event=="CALENDAR_UPDATE_EVENT" or event=="CALENDAR_UPDATE_EVENT_LIST" or event=="CALENDAR_NEW_EVENT") then
GRSS_GetCalendar();
GRSS_StoreEventDetails();
elseif(event == "GUILD_ROSTER_UPDATE") then
GRSS_TakeGuildOnly();
elseif(event == "CHAT_MSG_LOOT") then
GRSS_CaptureLoot(arg1);
elseif(event == "RAID_ROSTER_UPDATE") then
GRSS_RaidChange(arg1,arg2);
elseif(event == "LOOT_OPENED") then
GRSS_GetLoot();
elseif(event == "CHAT_MSG_WHISPER") then
GRSS_ProcessWhisper(arg2,arg1,this.language);
elseif(event == "CHAT_MSG_SYSTEM") then
if GRSS_Rolling==1 or GRSS_BidRolls then
local name, roll;
for name, roll in string.gmatch(arg1, "(.+) rolls (%d+) %(1%-"..GRSS_RollNumber.."%)") do
GRSS_RecordRoll(name, roll);
if GRSS_BidRolls==1 then
GRSSSortBy("bidroll");
else
GRSSSortBy("roll");
end
end
end
elseif(event == "ADDON_LOADED") then
UIDropDownMenu_SetText(GRSSRollNumberDropDown,"1-"..GRSSNumNilZero(GRSS_RollNumber));
end
end
function GRSS_IsZoneIgnored()
local zone = GetRealZoneText();
for i,v in pairs(GRSS_ZoneIgnore) do
if v == zone then
return 1;
end
end
return nil;
end
function GRSS_WipeCheck()
if GRSS_Auto and GRSS_AutoWipe==1 and not IsActiveBattlefieldArena() and not GRSS_IsZoneIgnored() then
local num = GetNumRaidMembers();
local is_dead,online,dead,alive,name;
dead = 0;
if num>1 then
for i = 1, num do
name,_,_,_,_,_,_,online,is_dead = GetRaidRosterInfo(i);
if is_dead or not online then
dead = dead + 1
end
end
end
if (dead/num) >= 0.7 then
if(GetTime() > GRSS_LastWipeTime+120) then
GRSS_LastWipeTime = GetTime();
StaticPopup_Show("GRSS_WIPE");
end
end
end
end
function GRSS_RecordRoll(name,roll)
local itemname = GRSSItemName:GetText()
for i,v in pairs(GRSS_DKP) do
if string.lower(v.name)==string.lower(name) or (GRSS_MainOnly[GRSSCurrentSystem] and GRSS_Alts[string.lower(name)]==string.lower(v.name)) then
if GRSS_DKP[i].roll == "" or GRSS_DKP[i].roll == nil then
GRSS_DKP[i].roll = roll;
GRSS_SendWhisper("Your roll of "..roll.." for "..itemname.." has been recorded","WHISPER",nil,name);
end
return;
end
end
temp = {};
temp.name = name;
temp.class = "?";
temp.spent = "";
temp.earned = "";
temp.adj = "";
temp.roll = roll;
temp.total = "?";
GRSS_SendWhisper("Your roll of "..roll.." for "..itemname.." has been recorded","WHISPER",nil,name);
table.insert(GRSS_DKP,1,temp);
--GRSSScrollBar_Update();
end
function GRSS_SendWhisper(msg,msgtype,lang,to)
SendChatMessage(GRSS_Prefix..msg,msgtype,lang,to);
end
-- Will search S for the regular expressions and return the result of the first successful search, or nil if none is found
-- Allows for a briefer way rather than doing if string.find, then return, elseif string.find....
function GRSS_MultiRegex(s,...)
for i,v in ipairs({...}) do
if(string.find(s,v)) then
return string.find(s,v);
end
end
return nil;
end
function GRSS_ProcessWhisper(from,msg,lang)
temp = {};
if(string.find(msg,"^!waitlistwho") or string.find(msg,"^!whowaitlist")) then
local _,waitlist = GRSS_WaitCommaList();
GRSS_SendWhisper("Waiting List: "..waitlist,"WHISPER",lang,from);
elseif(string.find(msg,"^!waitlist")) then
if not GRSS_IsNameQueuedOnWaitList(from) then
GRSS_QueueWaitListRequest(from)
end
if GRSS_IsNameOnWaitingList(from) then
GRSS_SendWhisper("You're already on the waiting list","WHISPER",lang,from);
elseif InCombatLockdown() then
GRSS_SendWhisper("Your request to be added to the waiting list has been received, but I am currently in combat. When I am out of combat, I will be able to respond to your request","WHISPER",lang,from);
elseif GRSS_WaitListRequestBoxOpen==0 then
GRSS_NextWaitListRequest()
end
elseif(string.find(msg,"^!bid") or string.find(msg,"^!req")) then
if GRSS_Bidding == 1 or GRSS_BidRolls==1 then
local bidtype;
local amtsrch = "%s+(%d*)";
s,e,bidtype,amt = GRSS_MultiRegex(msg,
"^!bid(main)"..amtsrch,
"^!bid(off)"..amtsrch,
"^!bid(alt)"..amtsrch,
"^!(bid)"..amtsrch
);
if bidtype=="main" then
bidtype = "Main";
elseif bidtype=="off" then
bidtype = "Offspec";
elseif bidtype=="alt" then
bidtype = "Alt";
else
bidtype = "";
end
name = GRSSExtractPlayerName(from);
temp.name = name;
if GRSS_BidStyle=="Requests" and GRSS_BidRolls==nil then
amt = "R";
else
if amt=="" then
amt = "blank";
else
amt = GRSSNumNilZero(amt);
end
end
temp.bid = amt;
temp.bidtype = bidtype;
table.insert(GRSS_Bids,temp);
GRSSBidsScrollBar_Update();
if GRSS_BidRolls==1 then
GRSS_SendWhisper("Your bid of "..amt.." has been recorded. Remember to also /roll "..GRSS_RollNumber.." if you haven't yet","WHISPER",lang,from);
elseif GRSS_BidStyle=="Silent Non-Auction" then
GRSS_SendWhisper("Your bid of "..amt.." has been recorded","WHISPER",lang,from);
elseif GRSS_BidStyle=="Requests" then
GRSS_SendWhisper("Your request has been recorded","WHISPER",lang,from);
elseif GRSS_BidStyle=="Silent Auction" or GRSS_BidStyle=="Open Auction" then
if tonumber(amt)~=nil and tonumber(amt) > GRSS_HighBid then
GRSS_SendWhisper("You are now the high bidder with "..amt,"WHISPER",lang,from);
GRSS_HighBid = tonumber(amt);
if GRSS_HighBidder ~= name and GRSS_HighBidder ~= "" then
GRSS_SendWhisper("You are no longer the high bidder. The high bid is now "..GRSS_HighBid..".","WHISPER",nil,GRSS_HighBidder);
end
GRSS_HighBidder = name;
if GRSS_BidStyle=="Silent Auction" then
SendChatMessage("The high bid is now "..amt,"RAID");
else
SendChatMessage(GRSS_HighBidder.." is now the high bidder with "..amt,"RAID");
end
elseif tonumber(amt)~=nil and tonumber(amt) < GRSS_HighBid then
GRSS_SendWhisper(amt.." is too low","WHISPER",lang,from);
elseif tonumber(amt)~=nil and tonumber(amt) == GRSS_HighBid then
GRSS_SendWhisper("Your bid of "..amt.." ties you with the high bidder", "WHISPER", lang, from);
else
GRSS_SendWhisper("Your bid was not understood. Please specify a number. (ie: !bid 365)","WHISPER",lang,from);
end
end
local found=false;
for i,v in pairs(GRSS_DKP) do
if string.lower(v.name)==string.lower(name) or (GRSS_MainOnly[GRSSCurrentSystem] and GRSS_Alts[string.lower(name)]==string.lower(v.name)) then
if tonumber(GRSS_DKP[i].bid)==nil or (tonumber(amt) ~= nil and tonumber(GRSS_DKP[i].bid) < tonumber(amt)) then
GRSS_DKP[i].bid = amt;
end
found=true
end
end
if found==false then
temp = {};
temp.name = name;
temp.class = "?";
temp.spent = "";
temp.earned = "";
temp.adj = "";
temp.bid = amt;
temp.total = "?";
table.insert(GRSS_DKP,1,temp);
end
if GRSS_BidRolls==1 then
GRSSSortBy("bidroll");
else
GRSSSortBy("bid");
end
GRSSScrollBar_Update();
else
GRSS_SendWhisper("Sorry, bids are not being received right now", "WHISPER", lang, from);
end
elseif(string.find(msg,"^!dkpclass")) then
s,e,class = string.find(msg,"^!dkpclass%s+(.+)");
if class==nil or class == "" then
GRSS_SendWhisper("You need to specify a class (i.e. !dkpclass mage)", "WHISPER", lang, from);
else
found = false;
local classes = {};
for w in string.gmatch(string.upper(class),"(%a+)") do
classes[w]=w;
end
if string.find(string.lower(class),"death%s*knight") then
classes["DEATH KNIGHT"]="DEATH KNIGHT";
end
for sys in pairs(GRSS_Systems) do
GRSSSortByFull("total",sys);
for i,v in pairs(GRSS_Full_DKP[sys]) do
if classes[string.upper(v.class)] then
local total;
if GRSS_Divide[sys] == nil then
total = tonumber(v.earned) + tonumber(v.adj) - tonumber(v.spent)
else
total = GRSSNumNilZero(v.earned) / GRSSNumNilOne(v.spent);
end
GRSS_SendWhisper("("..sys..") "..v.name.."("..v.class.."): "..total,"WHISPER",lang,from);
found=true;
end
end
end
if found==false then
GRSS_SendWhisper("Sorry, no players were found with the class "..class,"WHISPER",lang,from);
end
end
elseif(string.find(msg,"^!dkpraid")) then
s,e,sysid = string.find(msg,"^!dkpraid%s+(.+)%s*");
if sysid==nil or sys=="" or GRSS_NumberedSystems[GRSSNumNilZero(sysid)]==nil then
GRSS_SendWhisper("You'll need to specify one of the following DKP Systems in the following form...","WHISPER",lang,from);
for sysid,sys in pairs(GRSS_NumberedSystems) do
GRSS_SendWhisper("For "..sys..": !dkpraid "..sysid,"WHISPER",lang,from);
end
else
sys = GRSS_NumberedSystems[GRSSNumNilZero(sysid)];
GRSSSortByFull("total",sys);
RaidTable = GRSS_RaidTable();
GRSS_SendWhisper("Sending DKP for "..sys.." (only showing Raid Members)","WHISPER",lang,from);
for i,v in pairs(GRSS_Full_DKP[sys]) do
if RaidTable[string.upper(v.name)]==1 then
local total = GRSSNumNilZero(v.earned) + GRSSNumNilZero(v.adj) - GRSSNumNilZero(v.spent)
GRSS_SendWhisper(v.name.."("..v.class.."): "..total,"WHISPER",lang,from);
found=true;
end
end
end
elseif(string.find(msg,"^!dkpall")) then
s,e,sysid = string.find(msg,"^!dkpall%s+(.+)%s*");
if sysid==nil or sys=="" or GRSS_NumberedSystems[GRSSNumNilZero(sysid)]==nil then
GRSS_SendWhisper("You'll need to specify one of the following DKP Systems in the following form...","WHISPER",lang,from);
for sysid,sys in pairs(GRSS_NumberedSystems) do
GRSS_SendWhisper("For "..sys..": !dkpall "..sysid,"WHISPER",lang,from);
end
else
local count = 0;
sys = GRSS_NumberedSystems[GRSSNumNilZero(sysid)];
GRSSSortByFull("total",sys);
GRSS_SendWhisper("Sending DKP for "..sys.." (Only showing top 40)","WHISPER",lang,from);
for i,v in pairs(GRSS_Full_DKP[sys]) do
if count < 40 then
local total;
if GRSS_Divide[sys] == nil then
total = GRSSNumNilZero(v.earned) + GRSSNumNilZero(v.adj) - GRSSNumNilZero(v.spent)
else
total = GRSSNumNilZero(v.earned) / GRSSNumNilOne(v.spent);
end
--local total = GRSSNumNilZero(v.earned) + GRSSNumNilZero(v.adj) - GRSSNumNilZero(v.spent)
GRSS_SendWhisper(v.name.."("..v.class.."): "..total,"WHISPER",lang,from);
found=true;
count = count + 1
end
end
end
elseif(string.find(msg,"^!dkp")) then
s,e,name = string.find(msg,"^!dkp%s*(.*)");
if name == "" then
name = from;
end
name = GRSSExtractPlayerName(name);
tosend = GRSSGetPlayerDKP(name);
for i,v in pairs(tosend) do
GRSS_SendWhisper(v, "WHISPER", lang, from);
end
if table.getn(tosend)==0 then
GRSS_SendWhisper("No player named "..name.." found", "WHISPER", lang, from);
end
elseif(string.find(msg,"^!items")) then
s,e,name = string.find(msg,"^!items%s*(.*)%s*");
if name == "" then
playername = string.upper(from);
else
playername = string.upper(name);
end
playername = GRSSExtractPlayerName(playername);
if GRSS_ItemHistory[playername] ~= nil then
for i,v in pairs(GRSS_ItemHistory[playername]) do
GRSS_SendWhisper(v,"WHISPER",lang,from);
end
else
GRSS_SendWhisper("There is no item history for "..playername,"WHISPER",lang,from);
end
elseif(string.find(msg,"^!price%s")) then
s,e,itemraw = string.find(msg,"^!price%s+(.*)%s*");
s,e,color,item = string.find(itemraw, "|c(%x+)|Hitem:%d+:%d+:%d+:%d+|h%[(.-)%]|h|r");
if not s then
item = itemraw
end
found = false;
for sys in pairs(GRSS_Systems) do
for i,v in pairs(GRSS_ItemPrices[sys]) do
if string.find(string.lower(v.name),string.lower(item)) then
if GRSSNumNilZero(v.points) > 0 then
GRSS_SendWhisper("("..sys..") "..v.name..": "..v.points.." points","WHISPER",lang,from);
found = true;
end
end
end
end
if found == false then
GRSS_SendWhisper("Sorry no item by the name of '"..item.." was found","WHISPER",lang,from);
end
elseif(string.find(msg,"^!help") or string.find(msg,"^!%?") or string.find(msg,"^!info") or string.find(msg,"^!commands")) then
if string.upper(from) == string.upper(UnitName("player")) then
for i,v in pairs(GRSSHelpMsg) do
GRSSPrint(v);
end
else
for i,v in pairs(GRSSHelpMsg) do
GRSS_SendWhisper(v,"WHISPER",lang,from);
end
end
end
end
function GRSSExtractPlayerName(playername)
s,_,name = string.find(playername, "(.*)-.*");
if not(s) then
return playername;
else
return name;
end
end
function GRSSFindPlayerSystemIndex_NoAltCheck(playername,sys)
playername = string.lower(playername);
if GRSS_Full_DKP[sys]==nil then
GRSS_Full_DKP[sys] = {};
end
for i,v in pairs(GRSS_Full_DKP[sys]) do
if(string.lower(v.name)==playername) then
return i;
end
end
return -1;
end
function GRSSFindPlayerSystemIndex(playername,sys)
FoundIndex = GRSSFindPlayerSystemIndex_NoAltCheck(playername,sys);
if FoundIndex==-1 and GRSS_MainOnly[sys]==1 and GRSS_Alts[playername] then
local newplayername = string.lower(GRSS_Alts[playername]);
FoundIndex = GRSSFindPlayerSystemIndex_NoAltCheck(newplayername,sys);
end
return FoundIndex;
end
function GRSSLookupPlayerDKP(playername,sys)
local i = GRSSFindPlayerSystemIndex(playername,sys);
if i == -1 then
return 0;
else
local v = GRSS_Full_DKP[sys][i];
if(string.lower(v.name)==playername) then
local total;
if(GRSS_Divide[sys] == nil) then
total = GRSSNumNilZero(v.earned) + GRSSNumNilZero(v.adj) - GRSSNumNilZero(v.spent);
else
if(v.spent == 0) then
v.spent = 1;
end
total = GRSSNumNilZero(v.earned) / GRSSNumNilZero(v.spent);
end
return total;
end
end
end
function GRSSAddPoints(playername,sys,pointtype,points)
if sys==nil then
sys = GRSSCurrentSystem
end
if sys==nil then
return;
end
local i = GRSSFindPlayerSystemIndex(playername,sys);
if i == -1 then
local temp = {};
temp.name = playername;
temp.class = "?";
temp.spent = 0;
temp.earned = 0;
temp.adj = 0;
temp.rank = "?";
temp.rankid = 0;
table.insert(GRSS_Full_DKP[sys],temp);
i = GRSSFindPlayerSystemIndex(playername,sys);
end
if GRSS_Full_DKP[sys][i] == nil then
GRSSPrint("Player '"..playername.."' not found in list '"..sys.."' even after attempting to create. Please report this to DKPSystem.com.");
else
GRSS_Full_DKP[sys][i][pointtype] = GRSSNumNilZero(GRSS_Full_DKP[sys][i][pointtype]) + GRSSNumNilZero(points);
if GRSSCurrentSystem == sys then
GRSSChangeSystem(sys);
end
end
end
function GRSSPlayerPointCost(playername,sys,pointstr)
playername = string.lower(playername);
if pointstr==nil then
return 0;
elseif tonumber(pointstr) then --if the points entered are a number, just return that number
return tonumber(pointstr);
else --if it's entered as a percentage, fetch the current DKP, and return the corresponding percentage
local matches = {string.match(pointstr,"^([%d%.]+)%%$")};
if matches then
local percent = GRSSNumNilZero(matches[1])/100;
local current = GRSSLookupPlayerDKP(playername,sys);
return current * percent;
else
return 0;
end
end
end
function GRSSGetPlayerDKP(players)
local dkp = {};
for sys in pairs(GRSS_Systems) do
for i,v in pairs(GRSS_Full_DKP[sys]) do
for name in string.gmatch(players,"([%S,]+)") do
if string.lower(v.name)==string.lower(name) then
local total;
if GRSS_Divide[sys] == nil then
total = GRSSNumNilZero(v.earned) + GRSSNumNilZero(v.adj) - GRSSNumNilZero(v.spent)
else
total = GRSSNumNilZero(v.earned) / GRSSNumNilOne(v.spent);
end
--total = GRSSNumNilZero(v.earned) + GRSSNumNilZero(v.adj) - GRSSNumNilZero(v.spent);
table.insert(dkp,"("..sys..") "..name.."("..v.class.."): "..total);
end
end
end
end
return dkp;
end
function GRSS_CompareVersions()
if not GRSSNewVersionPrinted then
if GRSSNewestVersion then
if GRSSNewestVersion~=GRSSVersion then
GRSSNewVersionPrinted = true;
GRSSPrint("|c00ff0000There is a newer version of the GuildRaidSnapShot mod ("..GRSSNewestVersion..") available. Please download the newest version from www.dkpsystem.com or run the included GetGRSSDKP.exe program (Windows Only)|r");
end
end
end
end
function GuildRaidSnapShot_SlashHandler(msg)
local newboss;
msglower = string.lower(msg);
if msglower=="" or msglower=="help" or msglower=="?" then
for i,v in pairs(GRSSUsage) do
DEFAULT_CHAT_FRAME:AddMessage(v);
end
for i,v in pairs(GRSSHelpMsg) do
local tellcolor = "|c00ffff00";
local endcolor = "|r";
v = string.gsub(v,"^(.+) = (.+)",tellcolor.."%1"..endcolor.." = %2");
DEFAULT_CHAT_FRAME:AddMessage(v);
end
elseif msglower=="reset" or msglower=="purge" then
GuildRaidSnapShot_SnapShots = {};
GuildRaidSnapShot_Loot = {};
GuildRaidSnapShot_Adj = {};
GRSSPrint(GRSSRed("Snapshots Purged"));
elseif msglower == "noauto" then
GRSS_Auto = 0;
GRSSModePrint("Auto Snapshots",false);
elseif msglower == "yesauto" then
GRSS_Auto = 1;
GRSSModePrint("Auto Snapshots",true);
elseif msglower == "yesloot" then
GRSS_LootCap = 1;
GRSSModePrint("Loot point prompts",true);
elseif msglower == "noloot" then
GRSS_LootCap = 0;
GRSSModePrint("Loot point prompts",false);
elseif msglower == "yessnapshotpopup" or msglower == "yessnapshotpopups" or msglower == "yessnapshotpoints" then
GRSS_RaidPointsPopup = 1;
GRSSModePrint("Raid Snapshot Point Prompts",true);
elseif msglower == "nosnapshotpopup" or msglower == "nosnapshotpopups" or msglower == "nosnapshotpoints" then
GRSS_RaidPointsPopup = 0;
GRSSModePrint("Raid Snapshot Point Prompts",false);
elseif msglower == "yeslootcombat" then
GRSS_LootPromptInCombat = 1;
GRSSModePrint("Loot Prompts In Combat",true);
elseif msglower == "nolootcombat" then
GRSS_LootPromptInCombat = 0;
GRSSModePrint("Loot Prompts In Combat",false);
elseif msglower == "yesold" then
GRSS_EnableOldBosses();
GRSSModePrint("Old Bosses",true);
elseif msglower == "noold" then
GRSS_DisableOldBosses();
GRSSModePrint("Old Bosses",false);
elseif msglower == "show" then
GRSS:Show();
GRSS_CompareVersions();
elseif msglower == "loot" or msglower == "item" then
GRSSLoot:Show();
elseif msglower=="adj" or msglower=="adjustment" then
GRSSAdjShowHideType()
GRSSAdj:Show();
elseif msglower == "invite" or msglower=="waitlist" or msglower=="wait" then
GRSSInvite:Show();
elseif msglower == "starttimer" then
StaticPopup_Show("GRSS_STARTTIMER");
elseif msglower == "stoptimer" then
GRSS_StopTimer();
elseif msglower == "yesscreenshot" then
GRSSModePrint("Screenshots with snapshots",true);
GRSS_TakeScreenshots = 1
elseif msglower == "noscreenshot" then
GRSS_TakeScreenshots = nil
GRSSModePrint("Screenshots with snapshots",false);
elseif msglower == "yeswipe" then
GRSS_AutoWipe = 1;
GRSSModePrint("Wipe Detection",true);
elseif msglower == "nowipe" then
GRSS_AutoWipe = 0;
GRSSModePrint("Wipe Detection",false);
elseif msglower == "noparty" then
GRSS_DoingParty = 0;
GRSSModePrint("Party mode",false);
elseif msglower == "yesparty" then
GRSS_DoingParty = 1;
GRSSModePrint("Party mode",true);
elseif GetNumGroupMembers() > 0 and (IsInRaid() or GRSS_DoingParty == 1) then
GRSS_TakeSnapShot(msg);
else
GRSSPrint("You're not in a raid");
end
end
function GRSSOn()
return GRSSGreen("On");
end
function GRSSOff()
return GRSSRed("Off");
end
function GRSSModePrint(ModeText,tf)
local On;
if tf==true then
On = GRSSOn();
else
On = GRSSOff();
end
GRSSPrint(GRSSYellow(ModeText)..": "..On);
end
function GRSSColor(msg,color)
return "|c00"..color..msg.."|r";
end
function GRSSRed(msg)
return GRSSColor(msg,"ff0000");
end
function GRSSGreen(msg)
return GRSSColor(msg,"00ff00");
end
function GRSSBlue(msg)
return GRSSColor(msg,"0000ff");
end
function GRSSYellow(msg)
return GRSSColor(msg,"ffff00");
end
function GRSS_CaptureLoot(msg)
if GetNumGroupMembers()>0 then
local s, e, player, link = string.find(msg, "([^%s]+) receives loot: (.+)%.");
if(player == nil) then
s, e, link = string.find(msg, "You receive loot: (.+)%.");
if(link ~= nil) then
player = UnitName("player");
end
end
--GRSS_Auto = link;
if(link and player) then
local s, e, color, item = string.find(link, "|c(%x+)|Hitem[:%d%-]+|h%[(.-)%]|h|r");
if(color and item and GRSS_Colors[color]) then
-- Checking to see if the item listed is one we should ignore
for i,v in pairs(GRSS_LootIgnore) do
if string.find(item,v) then
return;
end
end
local lootdate = GRSSRecordItem(GRSSCurrentSystem,player,item,nil);
--loot search
if GRSS_LootCap == 1 then
GRSS_CurrentLootDate = lootdate;
lootindex = table.getn(GuildRaidSnapShot_Loot[lootdate]);
if GRSS_HighBid==0 or GRSS_Highbid == nil then
points = GRSS_GetItemPoints(GuildRaidSnapShot_Loot[lootdate][lootindex].item);
else
points = GRSS_HighBid;
end
GRSS_EnqueueItem(lootdate,lootindex,player,link,points);
if GRSS_ItemBoxOpen==0 and (not(InCombatLockdown()) or GRSS_LootPromptInCombat==1) then
GRSS_NextItemPopup();
end
end
end
end
end
end
function GRSS_TakeSnapShot(name)
local SnapShotName = name.." "..date("%Y-%m-%d %H:%M:%S");
GRSS_LastSnapShotName = SnapShotName;
if GRSS_LastSnapshot == nil then
GRSS_LastSnapshot = 0
end
if GuildRaidSnapShot_SnapShots[SnapShotName]==nil and GetTime() > GRSS_LastSnapshot+4 then
GRSS_LastSnapshot = GetTime();
GuildRaidSnapShot_SnapShots[SnapShotName] = {};
GuildRaidSnapShot_SnapShots[SnapShotName].RealmName = GetRealmName();
GuildRaidSnapShot_SnapShots[SnapShotName].system = GRSSCurrentSystem;
GuildRaidSnapShot_SnapShots[SnapShotName].points = 0;
local OnlineRaid,RaidList = GRSS_RaidCommaList();
GuildRaidSnapShot_SnapShots[SnapShotName]["Raid"] = RaidList;
local OnlineGuild,GuildList = GRSS_GuildCommaList();
GuildRaidSnapShot_SnapShots[SnapShotName]["Guild"] = GuildList;
local OnlineWaitingList,WaitingList = GRSS_WaitCommaList();
GuildRaidSnapShot_SnapShots[SnapShotName]["WaitList"] = WaitingList;
GRSSPrint("SnapShot Taken: "..SnapShotName.." (Guild: "..OnlineGuild.." | Raid: "..OnlineRaid.." | Waiting List: "..OnlineWaitingList..")");
if GRSS_TakeScreenshots==1 then
Screenshot();
end
GRSS_LastSnapShotPoints = GRSS_BossPoints(name,GRSSCurrentSystem);
if(GRSS_RaidPointsPopup==1) then
StaticPopup_Show("GRSS_RAIDPOINTS",name);
end
end
end
function GRSS_BossPoints(bossname,sys)
if GRSS_Dests then
for i,b in pairs(GRSS_Dests) do
if string.lower(b.boss)==string.lower(bossname) then
return b.points;
end
end
end
return "";
end
function GRSS_PlayerRank(player)
end
function GRSS_BossRatio(bossname,sys,player)
local rank = GRSS_PlayerRank(player);
for i,b in pairs(GRSS_Dests) do
if string.lower(b.boss)==string.lower(bossname) then
if b.ratios[sys] then
if b.ratios[sys][rank] then
return b.ratios[sys][rank];
end
end
end
end
return 1;
end
function GRSS_TakeGuildOnly()
local members="", level,class,online,rank,notes;
GRSS_Guild = {};
local n = GetNumGuildMembers();
local NumOnline = 0;
for i = 1, n do
MemName,rank,_,level,class,_,notes,_,_,online = GetGuildRosterInfo(i);
if notes == nil then
notes = "";
end
GRSS_Guild[MemName] = level .. ";" .. class..";"..rank..";;;"..notes;
end
end
function GRSS_TakeGuildNotes()
local members="", notes,num;
num =0;
GuildRoster();
GRSS_Guild = {};
local n = GetNumGuildMembers(true);
local NumOnline = 0;
GuildRaidSnapShot_Notes = {};
for i = 1, n do
MemName,_,_,_,_,_,notes = GetGuildRosterInfo(i);
if notes ~= "" then
num = num + 1;
GuildRaidSnapShot_Notes[MemName] = notes;
end
end
GRSSPrint("Guild notes Snapshot Taken: "..num.." Guild Notes Captured");
end
function GRSS_RaidCommaList()
local members="";
local NumOnline=0;
local zone="";
local con;
local n = GetNumGroupMembers();
if GetNumGroupMembers()>1 then
for i = 1, n do
MemName,_,_,_,_,_,zone,Online = GetRaidRosterInfo(i);
if Online then
if zone==nil then
zone = ""
end
else
zone = "Offline";
end
members = members..MemName..":"..zone;
if i ~= n then
members = members .. ", "
end
NumOnline=NumOnline+1;
end
if GRSS_TakeScreenshots==1 then
if InCombatLockdown() then
GRSSPrint("You're currently in combat, so I can't open the raid window for this snapshot");
else
ToggleFriendsFrame(1);
ToggleFriendsFrame(4);
end
end
end
return NumOnline,members
end
function GRSS_GuildCommaList()
local members="";
local online;
local zone="";
GuildRoster();
local n,_ = GetNumGuildMembers();
local NumOnline = 0;
for i = 1, n do
MemName,_,_,_,_,zone,_,_,online = GetGuildRosterInfo(i);
if zone==nil then
zone = ""
end
if online then
MemName = GRSS_FixName(MemName);
members = members..MemName .. ":" .. zone;
if i ~= n then
members = members .. ", "
end
NumOnline = NumOnline + 1;
end
end
return NumOnline,members;
end
function GRSS_FixName(Name)
local name = "";
for i in string.gmatch(Name, "[^-]*") do
return i;
end
end
function GRSS_WaitCommaList()
local num = table.getn(GRSS_WaitingList);
local waitlist = "";
for i = 1, num do
waitlist = waitlist..GRSS_WaitingList[i]
if i<num then
waitlist = waitlist..", ";
end
end
return num,waitlist;
end
function GRSS_RaidTable()
local members={};
local NumOnline=0;
local con;
local n = GetNumGroupMembers();
if GetNumGroupMembers()>1 then
for i = 1, n do
MemName,_,_,_,_,_,_,Online = GetRaidRosterInfo(i);
if Online==1 then
members[string.upper(MemName)]=1;
end
end
end
return members;
end
function GRSS_GuildTable()
local members={};
local online;
GuildRoster();
local n = GetNumGuildMembers(false);
local NumOnline = 0;
for i = 1, n do
MemName,_,_,_,_,_,_,_,online = GetGuildRosterInfo(i);
if online==1 then
members[string.upper(MemName)]=1;
end
end
return members;
end
function GRSSSystemDropDown_OnLoad(this)
GRSS_Initialize_Data();
GRSSChangeSystem(GRSSCurrentSystem);
UIDropDownMenu_Initialize(this, GRSSSystemDropDown_Initialize);
if GRSS_Systems[GRSSCurrentSystem]~=nil then
UIDropDownMenu_SetText(GRSSSystemDropDown,GRSSCurrentSystem);
else
UIDropDownMenu_SetText(GRSSSystemDropDown,"Select System");
end
UIDropDownMenu_SetWidth(GRSSSystemDropDown,130);
end
function GRSSLootSystemDropDown_OnLoad(this)
--GRSS_Initialize_Data();
UIDropDownMenu_Initialize(this, GRSSLootSystemDropDown_Initialize);
if GRSS_Systems[GRSSCurrentSystem]~=nil then
UIDropDownMenu_SetText(GRSSLootSystemDropDown,GRSSCurrentSystem);
else
UIDropDownMenu_SetText(GRSSLootSystemDropDown,"Select System");
end
UIDropDownMenu_SetWidth(GRSSLootSystemDropDown,130);
end
function GRSSAdjSystemDropDown_OnLoad(this)
--GRSS_Initialize_Data();
UIDropDownMenu_Initialize(this, GRSSAdjSystemDropDown_Initialize);
if GRSS_Systems[GRSSCurrentSystem]~=nil then
UIDropDownMenu_SetText(GRSSAdjSystemDropDown,GRSSCurrentSystem);
else
UIDropDownMenu_SetText(GRSSAdjSystemDropDown,"Select System");
end
UIDropDownMenu_SetWidth(GRSSAdjSystemDropDown,130);
end
function GRSSActionDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSActionDropDown_Initialize);
UIDropDownMenu_SetText(GRSSActionDropDown,"DKP Standings");
UIDropDownMenu_SetWidth(GRSSActionDropDown,110);
end
function GRSSBidStyleDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSBidStyleDropDown_Initialize);
if GRSS_BidStyle == "" then
UIDropDownMenu_SetText(GRSSBidStyleDropDown,"Bidding Style");
else
UIDropDownMenu_SetText(GRSSBidStyleDropDown,GRSS_BidStyle);
end
UIDropDownMenu_SetWidth(GRSSBidStyleDropDown,110);
end
function GRSSBidStyleDropDown_Initialize()
local Actions = {"Silent Auction","Silent Non-Auction","Open Auction","Requests"};
local info = {};
info.notCheckable = nil;
info.keepShownOnClick = nil;
info.func = GRSS_ChangeBidStyle;
for i,v in pairs(Actions) do
info.text = v;
info.value = v;
UIDropDownMenu_AddButton(info);
end
end
function GRSS_ChangeBidStyle(this)
UIDropDownMenu_SetText(GRSSBidStyleDropDown,this.value);
GRSS_BidStyle = this.value;
end
function GRSSSpamDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSSpamDropDown_Initialize);
UIDropDownMenu_SetText(GRSSSpamDropDown,"Spam Chat");
UIDropDownMenu_SetWidth(GRSSSpamDropDown,110);
end
function GRSSAdjTypeDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSAdjTypeDropDown_Initialize);
UIDropDownMenu_SetText(GRSSAdjTypeDropDown,"EP(Earned)");
UIDropDownMenu_SetWidth(GRSSAdjTypeDropDown,90);
end
function GRSSSpamDropDown_Initialize()
local Actions = {"RAID","PARTY","GUILD","SAY","OFFICER"};
local info = {};
info.notCheckable = nil;
info.keepShownOnClick = nil;
info.func = GRSS_ChangeSpam;
for i,v in pairs(Actions) do
info.text = v;
info.value = v;
UIDropDownMenu_AddButton(info);
end
end
function GRSSAdjTypeDropDown_Initialize()
local Actions = {"EP(Earned)","GP(Spent)"};
local info = {};
info.notCheckable = nil;
info.keepShownOnClick = nil;
info.func = GRSS_SetAdjType;
for i,v in pairs(Actions) do
info.text = v;
info.value = v;
UIDropDownMenu_AddButton(info);
end
end
function GRSS_GetAdjType()
local adjtype = UIDropDownMenu_GetText(GRSSAdjTypeDropDown);
if string.find(adjtype,"EP") then
adjtype = "earned";
elseif string.find(adjtype,"GP") then
adjtype = "spent";
else
adjtype = "adj";
end
return adjtype;
end
function GRSS_SetAdjType(this)
UIDropDownMenu_SetText(GRSSAdjTypeDropDown,this.value);
local s,e,adjtype = string.find(this.value,"^(%w+)%(");
end
function GRSS_ChangeSpam(this)
local place = this.value;
SendChatMessage("The following are for the DKP System: "..GRSSCurrentSystem,place);
if table.getn(GRSS_DKP) > 40 then
SendChatMessage("Only showing the top 40",place);
end
local count=0;
for i,v in pairs(GRSS_DKP) do
if count < 40 then
GRSS_SendWhisper(v.name..": "..v.total,place);
count = count + 1;
end
end
end
function GRSSRaidFilterDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSRaidFilterDropDown_Initialize);
if GRSS_Spam == "" then
UIDropDownMenu_SetText(GRSSRaidFilterDropDown,"All");
else
UIDropDownMenu_SetText(GRSSRaidFilterDropDown,GRSS_RaidFilter);
end
UIDropDownMenu_SetWidth(GRSSRaidFilterDropDown,90);
end
function GRSSRaidFilterDropDown_Initialize()
local Actions = {"All","Raid Only"};
local info = {};
info.notCheckable = nil;
info.keepShownOnClick = nil;
info.func = GRSS_ChangeRaidFilter;
for i,v in pairs(Actions) do
info.text = v;
info.value = v;
UIDropDownMenu_AddButton(info);
end
end
function GRSS_ChangeRaidFilter(this)
UIDropDownMenu_SetText(GRSSRaidFilterDropDown,this.value);
GRSS_RaidFilter = this.value;
GRSSChangeSystem(GRSSCurrentSystem);
end
function GRSSClassFilterDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSClassFilterDropDown_Initialize);
if GRSS_BidStyle == "" then
UIDropDownMenu_SetText(GRSSClassFilterDropDown,"All");
else
UIDropDownMenu_SetText(GRSSClassFilterDropDown,GRSS_ClassFilter);
end
UIDropDownMenu_SetWidth(GRSSClassFilterDropDown,90);
end
function GRSSClassFilterDropDown_Initialize()
local Actions = {"All","Druid","Hunter","Mage","Monk","Paladin","Priest","Rogue","Shaman","Warlock","Warrior","Death Knight"};
local info = {};
info.notCheckable = nil;
info.keepShownOnClick = nil;
info.func = GRSS_ChangeClassFilter;
for i,v in pairs(Actions) do
info.text = v;
info.value = v;
UIDropDownMenu_AddButton(info);
end
end
function GRSS_ChangeClassFilter(this)
UIDropDownMenu_SetText(GRSSClassFilterDropDown,this.value);
GRSS_ClassFilter = this.value;
GRSSChangeSystem(GRSSCurrentSystem);
end
function GRSSRollNumberDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSRollNumberDropDown_Initialize);
UIDropDownMenu_SetText(GRSSRollNumberDropDown,"1-"..GRSSNumNilZero(GRSS_RollNumber));
UIDropDownMenu_SetWidth(GRSSRollNumberDropDown,110);
end
function GRSSRollNumberDropDown_Initialize()
local Actions = {"1-100","1-1000","1-1337"};
local info = {};
info.notCheckable = nil;
info.keepShownOnClick = nil;
info.func = GRSS_ChangeRollNumber;
for i,v in pairs(Actions) do
info.text = v;
info.value = v;
UIDropDownMenu_AddButton(info);
end
end
function GRSS_ChangeRollNumber(this)
UIDropDownMenu_SetText(GRSSRollNumberDropDown,this.value);
local s,e,num = string.find(this.value,"1%-(%d+)")
GRSS_RollNumber = num;
end
function GRSSSystemDropDown_OnClick(this)
GRSSCurrentSystem = this.value;
UIDropDownMenu_SetText(GRSSSystemDropDown,this.value);
this.isChecked=true;
GRSSChangeSystem(GRSSCurrentSystem);
end
function GRSSLootSystemDropDown_OnClick(this)
GRSSLootCurrentSystem = this.value;
UIDropDownMenu_SetText(GRSSLootSystemDropDown,this.value);
this.isChecked=true;
end
function GRSSAdjSystemDropDown_OnClick(this)
UIDropDownMenu_SetText(GRSSAdjSystemDropDown,this.value);
GRSSAdjShowHideType()
this.isChecked=true;
end
function GRSSAdjShowHideType()
local system = UIDropDownMenu_GetText(GRSSAdjSystemDropDown);
if GRSS_Divide[system] then
GRSSAdjTypeDropDown:Show();
else
GRSSAdjTypeDropDown:Hide();
end
end
function GRSS_DeleteBid(line)
lineplusoffset = line + FauxScrollFrame_GetOffset(GRSSBidsScrollBar);
amount = GRSS_Bids[lineplusoffset].bid;
name = GRSS_Bids[lineplusoffset].name;
table.remove(GRSS_Bids,lineplusoffset);
playerhigh = 0;
totalhigh = 0;
highbidder = "";
for i,v in pairs(GRSS_Bids) do
if string.lower(v.name)==string.lower(name) then
if tonumber(v.bid)~=nil and tonumber(v.bid) > playerhigh then
playerhigh = tonumber(v.bid);
end
end
if tonumber(v.bid)~=nil and tonumber(v.bid) > totalhigh then
totalhigh = tonumber(v.bid);
highbidder = v.name;
end
end
if GRSS_HighBid ~= totalhigh and GRSS_Bidding==1 then
GRSS_HighBid = totalhigh;
GRSS_HighBidder = highbidder;
if GRSS_BidStyle=="Silent Auction" then
SendChatMessage("The high bid has been changed to "..GRSS_HighBid,"RAID");
elseif GRSS_BidStyle=="Open Auction" then
SendChatMessage(highbidder.." is now the high bidder with "..totalhigh,"RAID");
end
end
for i,v in pairs(GRSS_DKP) do
if string.lower(v.name)==string.lower(name) then
GRSS_DKP[i].bid = playerhigh;
end
end
GRSSBidsScrollBar_Update();
GRSSScrollBar_Update();
end
function GRSSActionDropDown_Initialize()
local Actions = {"DKP Standings","Rolls","Bids","Bid+Roll","DKP+Roll"};
local info = {};
info.notCheckable = nil;
info.keepShownOnClick = nil;
info.func = GRSS_DoAction;
for i,v in pairs(Actions) do
info.text = v;
info.value = v;
UIDropDownMenu_AddButton(info);
end
end
function GRSSSetHeaders(earned,spent,adj,total)
GRSSHeaderEarnedText:SetText(earned);
GRSSHeaderSpentText:SetText(spent);
GRSSHeaderAdjText:SetText(adj);
GRSSHeaderDKPText:SetText(total);
end
function GRSSShowHeaders(t)
if t=="DKP Standings" then
GRSSSetHeaders("Earned","Spent","Adj","Total");
elseif t=="Bids" then
GRSSSetHeaders("","Bid","","DKP");
elseif t=="Rolls" then
GRSSSetHeaders("","Roll","","DKP");
elseif t=="Bid+Roll" then
GRSSSetHeaders("Roll","Bid","Bid+Roll","DKP");
elseif t=="DKP+Roll" then
GRSSSetHeaders("Roll","","DKP+Roll","DKP");
end
end
function GRSS_ActionShow(...)
local hide = {"GRSSBids","GRSSToggleBids","GRSSClearBids","GRSSBidStyleDropDown","GRSSToggleRolls","GRSSClearRolls","GRSSRollNumberDropDown","GRSSRaidFilterDropDown","GRSSClassFilterDropDown","GRSSSpamDropDown","GRSSLootDropDown","GRSSItemName"};
for i,v in pairs(hide) do
getglobal(v):Hide();
end
for i,v in pairs({...}) do
getglobal(v):Show();
end
end
function GRSS_ToggleRolls()
local itemname = GRSSItemName:GetText()
if GRSS_Rolling == 1 then
GRSSToggleRolls:SetText("Start Rolls");
GRSSRollNumberDropDown:Show();
GRSS_Rolling = 0;
GRSS_EnableFunctionalButtons(1);
SendChatMessage("Rolling Ended on "..itemname..". No more rolls will be recorded", "RAID");
SendChatMessage("Rolling Ended on "..itemname..". No more rolls will be recorded", "RAID_WARNING");
else
GRSSToggleRolls:SetText("Stop Rolls");
GRSSRollNumberDropDown:Hide();
GRSS_Rolling = 1;
GRSS_EnableFunctionalButtons(0);
SendChatMessage("Rolling Started on "..itemname..". If you are interested /random "..GRSS_RollNumber..". Rolls with anything but "..GRSS_RollNumber.." will be ignored.", "RAID");
SendChatMessage("Rolling Started on "..itemname..". If you are interested /random "..GRSS_RollNumber..".", "RAID_WARNING");
end
end
function GRSS_EnableFunctionalButtons(tf)
if tf == 1 then
GRSSClearBids:Enable();
GRSSClearRolls:Enable();
GRSSSystemDropDown:Show();
GRSSActionDropDown:Show();
GRSSItemName:Show();
GRSSLootDropDown:Show();
else
GRSSClearBids:Disable();
GRSSClearRolls:Disable();
GRSSBidStyleDropDown:Hide();
GRSSSystemDropDown:Hide();
GRSSActionDropDown:Hide();
GRSSItemName:Hide();
GRSSLootDropDown:Hide();
end
end
function GRSS_ToggleBids()
local player = UnitName("player");
local itemname = GRSSItemName:GetText()
if GRSS_Bidding == 1 then
GRSSToggleBids:SetText("Start Bids");
GRSS_Bidding = nil;
GRSS_BidRolls = nil;
GRSS_EnableFunctionalButtons(1);
if GRSSCurrentAction == "Bid+Roll" then
GRSSRollNumberDropDown:Show();
else
GRSSBidStyleDropDown:Show();
end
msg = "Bidding Ended for "..itemname..". No more bids will be recorded"
else
GRSSToggleBids:SetText("Stop Bids");
GRSS_Bidding = 1;
GRSS_EnableFunctionalButtons(0);
GRSS_HighBid = 0;
if GRSSCurrentAction == "Bid+Roll" then
GRSS_BidRolls = 1;
msg = "Bidding and Rolling started for "..itemname.."! Type /random "..GRSS_RollNumber.." to register your roll. Then to bid: '/w "..player.." !bid X' where X is the amount to bid.";
GRSSRollNumberDropDown:Hide();
else
if GRSS_BidStyle=="Requests" then
msg = "Taking requests for "..itemname..". To request item: /w "..player.." !req";
else
msg = "Bidding Started for "..itemname.."! To bid: '/w "..player.." !bid X' where X is the amount you wish to bid";
end
GRSSBidStyleDropDown:Hide();
end
end
SendChatMessage(msg, "RAID");
SendChatMessage(msg, "RAID_WARNING");
end
function GRSS_ClearBids()
GRSS_Bids = {};
for i,v in pairs(GRSS_DKP) do
GRSS_DKP[i].bid = ""
GRSS_DKP[i].roll = ""
end
GRSSBidsScrollBar_Update();
GRSSScrollBar_Update();
end
function GRSS_ClearRolls()
GRSS_ClearBids();
end
function GRSS_DoAction(this)
GRSSCurrentAction = this.value;
UIDropDownMenu_SetText(GRSSActionDropDown,this.value);
if this.value == "DKP Standings" then
GRSS_ActionShow("GRSSRaidFilterDropDown","GRSSClassFilterDropDown","GRSSSpamDropDown");
elseif this.value == "Rolls" then
GRSS_ActionShow("GRSSToggleRolls","GRSSClearRolls","GRSSRollNumberDropDown","GRSSItemName","GRSSLootDropDown");
elseif this.value == "DKP+Roll" then
GRSS_ActionShow("GRSSToggleRolls","GRSSClearRolls","GRSSRollNumberDropDown","GRSSItemName","GRSSLootDropDown");
elseif this.value == "Bids" or this.value=="Requests" then
GRSS_ActionShow("GRSSBids","GRSSToggleBids","GRSSClearBids","GRSSBidStyleDropDown","GRSSItemName","GRSSLootDropDown");
elseif this.value == "Bid+Roll" then
GRSS_ActionShow("GRSSBids","GRSSToggleBids","GRSSClearBids","GRSSRollNumberDropDown","GRSSItemName","GRSSLootDropDown");
end
GRSSShowHeaders(this.value);
--[[
if this.value == "DKP Standings" then
DKP = true;
elseif this.value == "Rolls" or this.value == "DKP+Roll" then
Rolls = true;
elseif this.value == "Bids" or this.value == "Bid+Roll" then
Bids = true;
end
if Rolls or Bids then
GRSSItemName:Show();
else
GRSSItemName:Hide();
end
GRSSShowHeaders(this.value);
GRSSShowDKP(DKP);
GRSSShowRolls(Rolls);
GRSSShowBids(Bids);
if this.value=="Bid+Roll" then
GRSSRollNumberDropDown:Show();
GRSSBidStyleDropDown:Hide();
end
--]]
GRSSScrollBar_Update();
end
function GRSSSystemDropDown_Initialize()
local info = {};
if (not GRSS_Systems) then GRSS_Systems = {}; end;
for index, sys in pairs(GRSS_Systems) do
info.text = sys;
info.value = sys;
info.func = GRSSSystemDropDown_OnClick;
info.notCheckable = nil;
info.keepShownOnClick = nil;
UIDropDownMenu_AddButton(info);
end
end
function GRSSLootSystemDropDown_Initialize()
local info = {};
if (not GRSS_Systems) then GRSS_Systems = {}; end;
for index, sys in pairs(GRSS_Systems) do
info.text = sys;
info.value = sys;
info.func = GRSSLootSystemDropDown_OnClick;
info.notCheckable = nil;
info.keepShownOnClick = nil;
UIDropDownMenu_AddButton(info);
end
end
function GRSSAdjSystemDropDown_Initialize()
local info = {};
if (not GRSS_Systems) then GRSS_Systems = {}; end;
for index, sys in pairs(GRSS_Systems) do
info.text = sys;
info.value = sys;
info.func = GRSSAdjSystemDropDown_OnClick;
info.notCheckable = nil;
info.keepShownOnClick = nil;
UIDropDownMenu_AddButton(info);
end
end
function GRSSLootDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSLootDropDown_Initialize);
end
function GRSSLootDropDown_Initialize()
local info = {};
if (not GRSS_Loot) then GRSS_Loot = {}; end;
for link in pairs(GRSS_Loot) do
info.text = link;
info.value = link;
info.func = GRSSLootDropDownSelect;
info.notCheckable = nil;
info.keepShownOnClick = nil;
UIDropDownMenu_AddButton(info);
end
end
function GRSSLootDropDown_OnClick()
ToggleDropDownMenu(1, nil, GRSSLootDropDown, "GRSSItemName", 0, 0);
end
function GRSSLootDropDownSelect(this)
GRSSItemName:SetText(this.value);
end
function GRSS_GetLoot()
GRSS_Loot = {};
for i = 1, GetNumLootItems() do
if LootSlotHasItem(i) then
local link = GetLootSlotLink(i);
if link ~= nil then
local s, e, color, item = string.find(link, "|c(%x+)|Hitem[:%d%-]+|h%[(.-)%]|h|r");
if(color and item and GRSS_Colors[color]) then
GRSS_Loot[link]=link;
end
end
end
end
UIDropDownMenu_Initialize(GRSSLootDropDown, GRSSLootDropDown_Initialize);
end
-- Begin the Waiting List/Invite Code
function GRSSInviteDropDown_OnLoad(this)
UIDropDownMenu_Initialize(this, GRSSInviteDropDown_Initialize);
UIDropDownMenu_SetText(GRSSInviteDropDown,"Waiting List");
UIDropDownMenu_SetWidth(GRSSInviteDropDown,110);
end
function GRSSInviteDropDown_Initialize()
local Actions = {"Waiting List","Signup Invites"};
local info = {};
info.notCheckable = nil;
info.keepShownOnClick = nil;
info.func = GRSS_ChangeInvite;
for i,v in pairs(Actions) do
info.text = v;
info.value = v;
UIDropDownMenu_AddButton(info);
end
end
function GRSS_ChangeInvite(this)
UIDropDownMenu_SetText(GRSSInviteDropDown,this.value);
GRSS_InviteType = this.value;
if GRSS_InviteType == "Waiting List" then
GRSSInviteWaitingList:Show();
else
GRSSInviteWaitingList:Hide();
end
GRSSInviteScrollBar_Update();
end
function GRSSInviteScrollBar_Update()
local line; -- 1 through 10 of our window to scroll
local lineplusoffset; -- an index into our data calculated from the scroll offset
if GRSS_InviteType == "Waiting List" then
FauxScrollFrame_Update(GRSSInviteScrollBar,table.getn(GRSS_WaitingList),10,16);
for line=1,10 do
lineplusoffset = line + FauxScrollFrame_GetOffset(GRSSInviteScrollBar);
if lineplusoffset <= table.getn(GRSS_WaitingList) then
getglobal("GRSSInviteRow"..line.."FieldItem"):SetText(GRSS_WaitingList[lineplusoffset]);
getglobal("GRSSInviteRow"..line.."FieldItem"):Show();
getglobal("GRSSInviteRow"..line.."Invite"):Show();
getglobal("GRSSInviteRow"..line.."FieldHighlight"):Show();
getglobal("GRSSInviteRow"..line.."Delete"):Show();
else
getglobal("GRSSInviteRow"..line.."FieldItem"):Hide();
getglobal("GRSSInviteRow"..line.."FieldHighlight"):Hide();
getglobal("GRSSInviteRow"..line.."Invite"):Hide();
getglobal("GRSSInviteRow"..line.."Delete"):Hide();
end
end
else
FauxScrollFrame_Update(GRSSInviteScrollBar,table.getn(GRSS_RaidSignups),10,16);
for line=1,10 do
lineplusoffset = line + FauxScrollFrame_GetOffset(GRSSInviteScrollBar);
if lineplusoffset <= table.getn(GRSS_RaidSignups) then
getglobal("GRSSInviteRow"..line.."FieldItem"):SetText(GRSS_RaidSignups[lineplusoffset].name);
getglobal("GRSSInviteRow"..line.."FieldItem"):Show();
getglobal("GRSSInviteRow"..line.."Invite"):Show();
getglobal("GRSSInviteRow"..line.."FieldHighlight"):Show();
getglobal("GRSSInviteRow"..line.."Delete"):Hide();
else
getglobal("GRSSInviteRow"..line.."FieldItem"):Hide();
getglobal("GRSSInviteRow"..line.."FieldHighlight"):Hide();
getglobal("GRSSInviteRow"..line.."Invite"):Hide();
getglobal("GRSSInviteRow"..line.."Delete"):Hide();
end
end
end
end
function GRSS_InviteLine(n)
if GRSS_InviteType == "Waiting List" then
local lineplusoffset = n + FauxScrollFrame_GetOffset(GRSSInviteScrollBar);
local name = GRSS_WaitingList[lineplusoffset];
InviteUnit(name);
else
local RaidTable = GRSS_RaidTable();
local lineplusoffset = n + FauxScrollFrame_GetOffset(GRSSInviteScrollBar);
for i,v in pairs(GRSS_RaidSignups[lineplusoffset].waiting) do
GRSS_AddNameToWaitingList(v);
end
for i,v in pairs(GRSS_RaidSignups[lineplusoffset].pending) do
GRSS_AddNameToWaitingList(v);
end
for i,v in pairs(GRSS_RaidSignups[lineplusoffset].approved) do
InviteUnit(v);
end
end
end
function GRSS_DeleteInviteLine(n)
if GRSS_InviteType == "Waiting List" then
local lineplusoffset = n + FauxScrollFrame_GetOffset(GRSSInviteScrollBar);
local name = GRSS_WaitingList[lineplusoffset];
GRSS_RemoveFromWaitingList(name);
end
end
function GRSS_RaidChange(arg1,arg2)
local i=1;
local RaidTable = GRSS_RaidTable();
while i <= table.getn(GRSS_WaitingList) do
if RaidTable[string.upper(GRSS_WaitingList[i])]==1 then
table.remove(GRSS_WaitingList,i)
else
i = i + 1
end
end
GRSSInviteScrollBar_Update();
end
function GRSS_RemoveFromWaitingList(name)
local i = 1;
while i <= table.getn(GRSS_WaitingList) do
v = GRSS_WaitingList[i];
if string.upper(v)==string.upper(name) then
table.remove(GRSS_WaitingList,i);
else
i = i + 1
end
end
GRSSInviteScrollBar_Update();
end
function GRSS_IsNameOnWaitingList(name)
for i,v in pairs(GRSS_WaitingList) do
if string.upper(name)==string.upper(v) then
return true;
end
end
return false;
end
function GRSS_AddToWaitingList()
StaticPopup_Show("GRSS_WAITINGLIST");
end
function GRSS_AddNameToWaitingList(name)
for n in string.gmatch(name,"([^;,%s]+)") do
if not GRSS_IsNameOnWaitingList(n) then
table.insert(GRSS_WaitingList,n);
end
end
GRSSInviteScrollBar_Update();
end
function GRSS_IsNameQueuedOnWaitList(name)
for i,v in pairs(GRSS_WaitListRequest) do
if string.upper(name)==string.upper(v) then
return true;
end
end
return false;
end
function GRSS_QueueWaitListRequest(name)
table.insert(GRSS_WaitListRequest,1,name);
end
function GRSS_NextWaitListRequest()
local n = table.getn(GRSS_WaitListRequest);
if n > 0 then
local name = GRSS_WaitListRequest[n];
StaticPopup_Show("GRSS_AUTOWAITLIST",name);
end
end
function GRSSPrint(msg)
DEFAULT_CHAT_FRAME:AddMessage("GRSS: "..msg);
end
| mit |
amirjoker/Telecloner | plugins/save.lua | 13 | 2829 | local function save_value(msg, name, value)
if (not name or not value) then
return "Usage: !set var_name value"
end
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return "ذخیره شد "..name
end
end
local function run(msg, matches)
if not is_momod(msg) then
return "فقط برای ادمین مجاز است"
end
local name = string.sub(matches[1], 1, 50)
local value = string.sub(matches[2], 1, 1000)
local name1 = user_print_name(msg.from)
savelog(msg.to.id, name1.." ["..msg.from.id.."] saved ["..name.."] as > "..value )
local text = save_value(msg, name, value)
return text
end
return {
patterns = {
"^[!/]save ([^%s]+) (.+)$",
},
run = run
}
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/csCreateTicket.lua | 4 | 2135 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
CsCreateTicketCommand = {
name = "cscreateticket",
}
AddCommand(CsCreateTicketCommand)
| agpl-3.0 |
ozhanf/ozhan | plugins/wiki.lua | 735 | 4364 | -- 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 |
excessive/obtuse-tanuki | states/gameplay.lua | 2 | 9146 | local tiny = require "tiny"
local gui = require "quickie"
local material = require "material-love"
local errors = require "errors"
local avatar = require "avatar"
local utils = require "utils"
local cpml = require "cpml"
local utils = require "utils"
local camera = require "camera3d"
return function()
local gs = tiny.system()
gs.name = "gameplay"
function gs:enter(from, world, client, account, character)
print(cpml.quat(0, 0, 0, 1) * cpml.quat.rotate(3.14/2, cpml.vec3(0, 0, 1)))
self.client = assert(client)
self.world = assert(world)
self.realm = assert(client)
self.account = assert(account)
self.character = assert(character)
self.dx, self.dy = 0, 0
self.channel = require("systems.client_channel")(self.world)
self.channel.active = false
self.users = {}
self.chat_log = {}
self.show_user_settings = false
gui.keyboard.clearFocus()
self.camera = camera(cpml.vec3(0, 0, 0))
self.world:addSystem(require("systems.mesh_loader")(self.world))
self.world:addSystem(require("systems.input")(self.world))
self.world:addSystem(require("systems.movement")(self.camera))
self.world:addSystem(require("systems.hit")(self.camera))
self.world:addSystem(require("systems.render")(self.camera))
-- queue object updates for the next frame
self.world:addSystem(require("systems.cache")(self.world))
self.signals = {}
function self:register()
self.signals["connect"] = Signal.register("connect", function(s)
assert(s == "channel")
self.channel.active = true
console.i("Connected to channel server")
end)
self.signals["disconnect"] = Signal.register("disconnect", function(s, transfer)
console.i("Disconnected from %s server", s)
love.event.quit()
-- if s == "channel" then
-- -- TODO: change to another channel, we have a problem
-- console.e("Disconnected from channel server!")
-- return
-- end
--
-- error(s)
end)
self.signals["recv-client-channel-handoff"] = Signal.register("recv-client-channel-handoff", function(server, data)
assert(data.token)
assert(data.host)
assert(data.port)
self.world:addSystem(self.channel)
self.channel:connect(data.host, data.port)
self.channel:send_identify {
token = data.token,
alias_id = self.character.alias_id
}
end)
--[[
FROM: client_realm:recv_new_character
Receive new character data.
--]]
self.signals["recv-new-character"] = Signal.register("recv-new-character", function(server, character)
console.i("Received Character information from %s for %s", server, character.alias)
assert(character.avatar)
assert(character.avatar_id)
assert(character.alias)
assert(character.alias_id)
assert(character.position)
character.avatar_base64 = character.avatar
character.avatar = avatar.decode(character.avatar_base64)
character.replicate = true
character.id = character.alias_id
character.position = cpml.vec3(character.position)
character.orientation = cpml.quat(0, 0, 0, 1)
character.velocity = cpml.vec3()
character.rot_velocity = cpml.quat(0, 0, 0, 1)
character.scale = cpml.vec3(1, 1, 1)
character.needs_reload = true
if self.character.alias_id == character.alias_id then
self.character = character
character.possessed = true
local plane = {
id = -2,
position = cpml.vec3(0, 0, -0.1),
orientation = cpml.quat(0, 0, 0, 1),
velocity = cpml.vec3(),
rot_velocity = cpml.quat(0, 0, 0, 1),
scale = cpml.vec3(1, 1, 1),
model = "plane",
needs_reload = true
}
self.world:addEntity(plane)
debug_arrow = {
id = -1,
position = cpml.vec3(0, 5, 0),
orientation = cpml.quat(0, 0, 0, 1),
velocity = cpml.vec3(),
rot_velocity = cpml.quat(0, 0, 0, 1),
scale = cpml.vec3(1, 1, 1),
model = "arrow",
needs_reload = true
}
self.world:addEntity(debug_arrow)
end
self.world:addEntity(character)
table.insert(self.users, character)
end)
self.signals["recv-remove-character"] = Signal.register("recv-remove-character", function(server, character)
-- print("received character remove")
for i, user in ipairs(self.users) do
if user.alias_id == character.alias_id then
self.world:removeEntity(user)
table.remove(self.users, i)
break
end
end
end)
self.signals["recv-character-update"] = Signal.register("recv-character-update", function(server, character)
for _, user in ipairs(self.users) do
if user.alias_id == character.old_alias_id or user.alias_id == character.alias_id then
character.old_alias_id = nil
if character.avatar then
character.avatar_base64 = character.avatar
character.avatar = avatar.decode(character.avatar)
end
for i, item in pairs(character) do
user[i] = item
end
break
end
end
end)
self.signals["recv-chat"] = Signal.register("recv-chat", function(server, data)
if data.channel == "YELL" then
console.es("[%s] <%s> %s", data.channel, data.alias, data.line)
else
if data.id == self.character.alias_id then
console.ds("[%s] <%s> %s", data.channel, data.alias, data.line)
else
console.is("[%s] <%s> %s", data.channel, data.alias, data.line)
end
end
table.insert(self.chat_log, data)
end)
self.signals["recv-error"] = Signal.register("recv-error", function(server, code)
-- this should reset the world automatically, I think
-- if code == errors.INVALID_LOGIN then
-- register.logout(true)
-- register.login()
-- end
end)
self.signals["send-avatar"] = Signal.register("send-avatar", function(data)
self.character.avatar_base64 = assert(data.avatar)
self.character.avatar = assert(data.encoded)
self.client:send({
type = "character_update",
avatar = data.avatar
})
end)
end
function self:unregister()
for k, v in pairs(self.signals) do
Signal.remove(k, v)
end
end
self:register()
end
function gs:resume(from, ...)
-- if from.name == "change_avatar" then
-- local avatar = select(1, ...)
-- if avatar then
-- self.character.avatar = avatar
-- end
-- end
end
function gs:leave()
self:unregister()
end
function gs:update(dt)
if not self.channel.active then
gui.group { grow = "down", pos = { 20, 20 }, function()
love.graphics.setFont(material.noto("body1"))
gui.Label { text = "Connecting..." }
end }
gui.core.draw()
return
end
local w, h = love.graphics.getDimensions()
gui.group { grow = "down", pos = { 20, 20 }, function()
love.graphics.setFont(material.noto("title"))
if self.character.avatar then
love.graphics.draw(self.character.avatar, 20, 20, 0, 1, 1)
end
gui.group.push { grow = "down", pos = { 84, 0 } }
gui.Label { text = self.character.alias }
love.graphics.setFont(material.noto("body1"))
gui.group.push { grow = "down" }
gui.Label { text = self.character.subtitle }
gui.group.pop {}
gui.group.pop {}
end}
-- character list
gui.group { grow = "down", pos = { w - 400, 20 }, function()
local i = 1
for _, u in pairs(gs.users) do
while true do -- pseudo-continue
if u.alias_id == self.character.alias_id then
break
end
gui.Label { text = u.alias }
if u.avatar then
local spacing = 20
love.graphics.draw(u.avatar, w - 432 - 5, 20+(i-1)*spacing, 0, 0.5, 0.5)
end
i = i + 1
break end
end
end}
-- settings/session commands
gui.group { grow = "down", pos = { w - 170, 20 }, function()
if gui.Button { text = "Settings" } then
self.show_user_settings = not self.show_user_settings
end
if self.show_user_settings then
gui.group.push { grow = "down" }
gui.Label { text = "Nick" }
gui.Input { info = { text = self.character.alias } }
if gui.Checkbox { text = "Show name", checked = self.account.show_name, size = { "tight" } } then
self.account.show_name = not self.account.show_name
end
if gui.Checkbox { text = "Show stats", checked = self.account.show_stats, size = { "tight" } } then
self.account.show_stats = not self.account.show_stats
end
if gui.Button { text = "Change Avatar" } then
Gamestate.push(require("states.change_avatar")(), self.world, self.character.avatar_base64)
end
gui.group.pop {}
end
-- gui.group.getRect {} -- #rekt
-- if gui.Button { text = "Logout" } then
-- perform.logout()
-- end
-- if gui.Button { text = "Exit" } then
-- love.event.quit()
-- end
end }
gui.core.draw()
end
function gs:textinput(s)
gui.keyboard.textinput(s)
end
function gs:mousemoved(x, y, dx, dy)
self.dx, self.dy = -dx, -dy
end
function gs:keypressed(key, scan, is_repeat)
gui.keyboard.pressed(key)
if key == "g" then
love.mouse.setRelativeMode(not love.mouse.getRelativeMode())
end
end
return gs
end
| mit |
DBarney/luvit | tests/to-convert/test-http.lua | 5 | 1504 | --[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require("helper")
local http = require('http')
local HOST = "127.0.0.1"
local PORT = process.env.PORT or 10080
local server = nil
local client = nil
server = http.createServer(function(request, response)
p('server:onConnection')
p(request)
assert(request.method == "GET")
assert(request.url == "/foo")
-- Fails because header parsing is busted
-- assert(request.headers.bar == "cats")
p(response)
response:write("Hello")
response:finish()
server:close()
end)
server:listen(PORT, HOST, function()
local req = http.request({
host = HOST,
port = PORT,
path = "/foo",
headers = {bar = "cats"}
}, function(response)
p('client:onResponse')
p(response)
assert(response.status_code == 200)
assert(response.version_major == 1)
assert(response.version_minor == 1)
-- TODO: fix refcount so this isn't needed.
process.exit()
end)
req:done()
end)
| apache-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/decline.lua | 4 | 2114 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
DeclineCommand = {
name = "decline",
}
AddCommand(DeclineCommand)
| agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/loot/items/wearables/bracelet/bracelet_s03_l.lua | 4 | 1273 | bracelet_s03_l = {
-- Golden Bracelet
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/wearables/bracelet/bracelet_s03_l.iff",
craftingValues = {},
skillMods = {},
customizationStringNames = {"/private/index_color_1","/private/index_color_2"},
customizationValues = {
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119}
},
junkDealerTypeNeeded = JUNKCLOTHESANDJEWELLERY,
junkMinValue = 40,
junkMaxValue = 80
}
addLootItemTemplate("bracelet_s03_l", bracelet_s03_l) | agpl-3.0 |
LeMagnesium/minetest-minetestforfun-server | mods/mesecons/mesecons/legacy.lua | 13 | 1399 | -- Ugly hack to prevent breaking compatibility with other mods
-- Just remove the following two functions to delete the hack, to be done when other mods have updated
function mesecon.receptor_on(self, pos, rules)
if (self.receptor_on) then
print("[Mesecons] Warning: A mod with mesecon support called mesecon:receptor_on.")
print("[Mesecons] If you are the programmer of this mod, please update it ")
print("[Mesecons] to use mesecon.receptor_on instead. mesecon:* is deprecated")
print("[Mesecons] Otherwise, please make sure you're running the latest version")
print("[Mesecons] of that mod and inform the mod creator.")
else
rules = pos
pos = self
end
mesecon.queue:add_action(pos, "receptor_on", {rules}, nil, rules)
end
function mesecon.receptor_off(self, pos, rules)
if (self.receptor_off) then
print("[Mesecons] Warning: A mod with mesecon support called mesecon:receptor_off.")
print("[Mesecons] If you are the programmer of this mod, please update it ")
print("[Mesecons] to use mesecon.receptor_off instead. mesecon:* is deprecated")
print("[Mesecons] Otherwise, please make sure you're running the latest version")
print("[Mesecons] of that mod and inform the mod creator.")
else
rules = pos
pos = self
end
mesecon.queue:add_action(pos, "receptor_off", {rules}, nil, rules)
end
| unlicense |
braydondavis/Nerd-Gaming-Public | resources/NGModshop/vehicle.funcs.server.lua | 4 | 2061 |
function isVehicleInModShop( vehicle )
for k,v in ipairs( modShops ) do
if modShops[ k ].veh == vehicle then
return true
end
end
return false
end
function getVehicleInModShop( marker )
for k,v in ipairs( modShops ) do
if modShops[ k ].marker == marker then
return modShops[ k ].veh
end
end
return false
end
function getVehicleModShop( vehicle )
for k,v in ipairs( modShops ) do
if modShops[ k ].veh == vehicle then
return modShops[ k ].marker
end
end
return false
end
function getVehicleTuner( vehicle )
if not isVehicleInModShop( vehicle ) then return false end
return getVehicleController( vehicle )
end
function setModShopBusy( marker, vehicle, busy )
if busy == true or busy == false then
for k, v in ipairs( modShops ) do
if modShops[ k ].marker == marker then
modShops[ k ].veh = busy
return true
end
end
end
for k, v in ipairs( modShops ) do
if modShops[ k ].marker == marker then
modShops[ k ].veh = vehicle
return true
end
end
return false
end
function getItemPrice( itemid )
if not itemid then return false end
if itemid > 1193 or itemid < 1000 then
return false
elseif type( itemid ) ~= 'number' then
return false
end
return vehicleUpgrades.prices[ itemid - 999 ]
end
function getItemName( itemid )
if not itemid then return false end
if itemid > 1193 or itemid < 1000 then
return false
elseif type( itemid ) ~= 'number' then
return false
end
return vehicleUpgrades.names[ itemid - 999 ]
end
function getItemIDFromName( itemname )
if not itemname then
return false
elseif type( itemname ) ~= 'string' then
return false
end
for k,v in ipairs( vehicleUpgrades.names ) do
if v == itemname then
return k + 999
end
end
return false
end
| mit |
hfjgjfg/sx | plugins/ingroup.lua | 527 | 44020 | do
-- Check Member
local function check_member_autorealm(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)] = {
group_type = 'Realm',
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 realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(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)] = {
group_type = 'Realm',
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 realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(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)] = {
group_type = 'Group',
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)] = {
group_type = 'Group',
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_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(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
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
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
--End Check Member
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 leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
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.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
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 set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
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 is_group(msg) 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 realmadd(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 is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
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 is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(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 is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{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 promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, '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 demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_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
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return '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)
--vardump(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
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(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_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 not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
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
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(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
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(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] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) 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' and matches[2] 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] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
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] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(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
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
aqasaeed/farzad | plugins/ingroup.lua | 527 | 44020 | do
-- Check Member
local function check_member_autorealm(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)] = {
group_type = 'Realm',
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 realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(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)] = {
group_type = 'Realm',
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 realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(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)] = {
group_type = 'Group',
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)] = {
group_type = 'Group',
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_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(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
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
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
--End Check Member
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 leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
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.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
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 set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
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 is_group(msg) 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 realmadd(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 is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
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 is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(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 is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{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 promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, '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 demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_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
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return '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)
--vardump(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
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(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_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 not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
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
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(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
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(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] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) 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' and matches[2] 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] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
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] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(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
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
mohammad8/mohammad | plugins/ingroup.lua | 527 | 44020 | do
-- Check Member
local function check_member_autorealm(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)] = {
group_type = 'Realm',
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 realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(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)] = {
group_type = 'Realm',
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 realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(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)] = {
group_type = 'Group',
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)] = {
group_type = 'Group',
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_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(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
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
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
--End Check Member
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 leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
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.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
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 set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
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 is_group(msg) 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 realmadd(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 is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
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 is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(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 is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{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 promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, '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 demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_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
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return '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)
--vardump(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
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(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_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 not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
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
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(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
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(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] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) 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' and matches[2] 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] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
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] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(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
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
braydondavis/Nerd-Gaming-Public | resources/[no_ng_tag]/admin/client/colorpicker/colorpicker.lua | 7 | 9602 | sw, sh = guiGetScreenSize()
pickerTable = {}
colorPicker = {}
colorPicker.__index = colorPicker
function openPicker(id, start, title)
if id and not pickerTable[id] then
pickerTable[id] = colorPicker.create(id, start, title)
pickerTable[id]:updateColor()
return true
end
return false
end
function closePicker(id)
if id and pickerTable[id] then
pickerTable[id]:destroy()
return true
end
return false
end
function colorPicker.create(id, start, title)
local cp = {}
setmetatable(cp, colorPicker)
cp.id = id
cp.color = {}
cp.color.h, cp.color.s, cp.color.v, cp.color.r, cp.color.g, cp.color.b, cp.color.hex = 0, 1, 1, 255, 0, 0, "#FF0000"
cp.color.white = tocolor(255,255,255,255)
cp.color.black = tocolor(0,0,0,255)
cp.color.current = tocolor(255,0,0,255)
cp.color.huecurrent = tocolor(255,0,0,255)
if start and getColorFromString(start) then
cp.color.h, cp.color.s, cp.color.v = rgb2hsv(getColorFromString(start))
end
cp.gui = {}
cp.gui.width = 416
cp.gui.height = 304
cp.gui.snaptreshold = 0.02
cp.gui.window = guiCreateWindow((sw-cp.gui.width)/2, (sh-cp.gui.height)/2, cp.gui.width, cp.gui.height, tostring(title or "COLORPICKER"), false)
cp.gui.svmap = guiCreateStaticImage(16, 32, 256, 256, "client/colorpicker/blank.png", false, cp.gui.window)
cp.gui.hbar = guiCreateStaticImage(288, 32, 32, 256, "client/colorpicker/blank.png", false, cp.gui.window)
cp.gui.blank = guiCreateStaticImage(336, 32, 64, 64, "client/colorpicker/blank.png", false, cp.gui.window)
cp.gui.edith = guiCreateLabel(338, 106, 64, 20, "H: 0°", false, cp.gui.window)
cp.gui.edits = guiCreateLabel(338, 126, 64, 20, "S: 100%", false, cp.gui.window)
cp.gui.editv = guiCreateLabel(338, 146, 64, 20, "V: 100%", false, cp.gui.window)
cp.gui.editr = guiCreateLabel(338, 171, 64, 20, "R: 255", false, cp.gui.window)
cp.gui.editg = guiCreateLabel(338, 191, 64, 20, "G: 0", false, cp.gui.window)
cp.gui.editb = guiCreateLabel(338, 211, 64, 20, "B: 0", false, cp.gui.window)
cp.gui.okb = guiCreateButton(336, 235, 64, 24, "OK", false, cp.gui.window)
cp.gui.closeb = guiCreateButton(336, 265, 64, 24, "Cancel", false, cp.gui.window)
guiWindowSetSizable(cp.gui.window, false)
cp.handlers = {}
cp.handlers.mouseDown = function() cp:mouseDown() end
cp.handlers.mouseSnap = function() cp:mouseSnap() end
cp.handlers.mouseUp = function(b,s) cp:mouseUp(b,s) end
cp.handlers.mouseMove = function(x,y) cp:mouseMove(x,y) end
cp.handlers.render = function() cp:render() end
cp.handlers.guiFocus = function() cp:guiFocus() end
cp.handlers.guiBlur = function() cp:guiBlur() end
cp.handlers.pickColor = function() cp:pickColor() end
cp.handlers.destroy = function() cp:destroy() end
addEventHandler("onClientGUIMouseDown", cp.gui.svmap, cp.handlers.mouseDown, false)
addEventHandler("onClientMouseLeave", cp.gui.svmap, cp.handlers.mouseSnap, false)
addEventHandler("onClientMouseMove", cp.gui.svmap, cp.handlers.mouseMove, false)
addEventHandler("onClientGUIMouseDown", cp.gui.hbar, cp.handlers.mouseDown, false)
addEventHandler("onClientMouseMove", cp.gui.hbar, cp.handlers.mouseMove, false)
addEventHandler("onClientClick", root, cp.handlers.mouseUp)
addEventHandler("onClientGUIMouseUp", root, cp.handlers.mouseUp)
addEventHandler("onClientRender", root, cp.handlers.render)
addEventHandler("onClientGUIFocus", cp.gui.window, cp.handlers.guiFocus, false)
addEventHandler("onClientGUIBlur", cp.gui.window, cp.handlers.guiBlur, false)
addEventHandler("onClientGUIClick", cp.gui.okb, cp.handlers.pickColor, false)
addEventHandler("onClientGUIClick", cp.gui.closeb, cp.handlers.destroy, false)
showCursor(true)
return cp
end
function colorPicker:render()
-- if not self.gui.focus then return end
local x,y = guiGetPosition(self.gui.window, false)
dxDrawRectangle(x+16, y+32, 256, 256, self.color.huecurrent, self.gui.focus)
dxDrawImage(x+16, y+32, 256, 256, "client/colorpicker/sv.png", 0, 0, 0, self.color.white, self.gui.focus)
dxDrawImage(x+288, y+32, 32, 256, "client/colorpicker/h.png", 0, 0, 0, self.color.white, self.gui.focus)
dxDrawImageSection(x+8+math.floor(256*self.color.s), y+24+(256-math.floor(256*self.color.v)), 16, 16, 0, 0, 16, 16, "client/colorpicker/cursor.png", 0, 0, 0, self.color.white, self.gui.focus)
dxDrawImageSection(x+280, y+24+(256-math.floor(256*self.color.h)), 48, 16, 16, 0, 48, 16, "client/colorpicker/cursor.png", 0, 0, 0, self.color.huecurrent, self.gui.focus)
dxDrawRectangle(x+336, y+32, 64, 64, self.color.current, self.gui.focus)
dxDrawText(self.color.hex, x+336, y+32, x+400, y+96, self.color.v < 0.5 and self.color.white or self.color.black, 1, "default", "center", "center", true, true, self.gui.focus)
end
function colorPicker:mouseDown()
if source == self.gui.svmap or source == self.gui.hbar then
self.gui.track = source
local cx, cy = getCursorPosition()
self:mouseMove(sw*cx, sh*cy)
end
end
function colorPicker:mouseUp(button, state)
if not state or state ~= "down" then
if self.gui.track then
triggerEvent("onColorPickerChange", root, self.id, self.color.hex, self.color.r, self.color.g, self.color.b)
end
self.gui.track = false
end
end
function colorPicker:mouseMove(x,y)
if self.gui.track and source == self.gui.track then
local gx,gy = guiGetPosition(self.gui.window, false)
if source == self.gui.svmap then
local offsetx, offsety = x - (gx + 16), y - (gy + 32)
self.color.s = offsetx/255
self.color.v = (255-offsety)/255
elseif source == self.gui.hbar then
local offset = y - (gy + 32)
self.color.h = (255-offset)/255
end
self:updateColor()
end
end
function colorPicker:mouseSnap()
if self.gui.track and source == self.gui.track then
if self.color.s < self.gui.snaptreshold or self.color.s > 1-self.gui.snaptreshold then self.color.s = math.round(self.color.s) end
if self.color.v < self.gui.snaptreshold or self.color.v > 1-self.gui.snaptreshold then self.color.v = math.round(self.color.v) end
self:updateColor()
end
end
function colorPicker:updateColor()
self.color.r, self.color.g, self.color.b = hsv2rgb(self.color.h, self.color.s, self.color.v)
self.color.current = tocolor(self.color.r, self.color.g, self.color.b,255)
self.color.huecurrent = tocolor(hsv2rgb(self.color.h, 1, 1))
self.color.hex = string.format("#%02X%02X%02X", self.color.r, self.color.g, self.color.b)
guiSetText(self.gui.edith, "H: "..tostring(math.round(self.color.h*360)).."°")
guiSetText(self.gui.edits, "S: "..tostring(math.round(self.color.s*100)).."%")
guiSetText(self.gui.editv, "V: "..tostring(math.round(self.color.v*100)).."%")
guiSetText(self.gui.editr, "R: "..tostring(self.color.r))
guiSetText(self.gui.editg, "G: "..tostring(self.color.g))
guiSetText(self.gui.editb, "B: "..tostring(self.color.b))
end
function colorPicker:guiFocus()
self.gui.focus = true
guiSetAlpha(self.gui.window, 1)
end
function colorPicker:guiBlur()
self.gui.focus = false
guiSetAlpha(self.gui.window, 0.5)
end
function colorPicker:pickColor()
triggerEvent("onColorPickerOK", root, self.id, self.color.hex, self.color.r, self.color.g, self.color.b)
self:destroy()
end
function colorPicker:destroy()
removeEventHandler("onClientGUIMouseDown", self.gui.svmap, self.handlers.mouseDown)
removeEventHandler("onClientMouseLeave", self.gui.svmap, self.handlers.mouseSnap)
removeEventHandler("onClientMouseMove", self.gui.svmap, self.handlers.mouseMove)
removeEventHandler("onClientGUIMouseDown", self.gui.hbar, self.handlers.mouseDown)
removeEventHandler("onClientMouseMove", self.gui.hbar, self.handlers.mouseMove)
removeEventHandler("onClientClick", root, self.handlers.mouseUp)
removeEventHandler("onClientGUIMouseUp", root, self.handlers.mouseUp)
removeEventHandler("onClientRender", root, self.handlers.render)
removeEventHandler("onClientGUIFocus", self.gui.window, self.handlers.guiFocus)
removeEventHandler("onClientGUIBlur", self.gui.window, self.handlers.guiBlur)
removeEventHandler("onClientGUIClick", self.gui.okb, self.handlers.pickColor)
removeEventHandler("onClientGUIClick", self.gui.closeb, self.handlers.destroy)
destroyElement(self.gui.window)
pickerTable[self.id] = nil
setmetatable(self, nil)
--showCursor(areThereAnyPickers())
end
function areThereAnyPickers()
for _ in pairs(pickerTable) do
return true
end
return false
end
function hsv2rgb(h, s, v)
local r, g, b
local i = math.floor(h * 6)
local f = h * 6 - i
local p = v * (1 - s)
local q = v * (1 - f * s)
local t = v * (1 - (1 - f) * s)
local switch = i % 6
if switch == 0 then
r = v g = t b = p
elseif switch == 1 then
r = q g = v b = p
elseif switch == 2 then
r = p g = v b = t
elseif switch == 3 then
r = p g = q b = v
elseif switch == 4 then
r = t g = p b = v
elseif switch == 5 then
r = v g = p b = q
end
return math.floor(r*255), math.floor(g*255), math.floor(b*255)
end
function rgb2hsv(r, g, b)
r, g, b = r/255, g/255, b/255
local max, min = math.max(r, g, b), math.min(r, g, b)
local h, s
local v = max
local d = max - min
s = max == 0 and 0 or d/max
if max == min then
h = 0
elseif max == r then
h = (g - b) / d + (g < b and 6 or 0)
elseif max == g then
h = (b - r) / d + 2
elseif max == b then
h = (r - g) / d + 4
end
h = h/6
return h, s, v
end
function math.round(v)
return math.floor(v+0.5)
end
addEvent("onColorPickerOK", true)
addEvent("onColorPickerChange", true) | mit |
glaubitz/ion3-debian | mod_query/mod_query_chdir.lua | 7 | 1311 | --
-- ion/query/mod_query_chdir.lua
--
-- Copyright (c) Tuomo Valkonen 2004-2009.
--
-- See the included file LICENSE for details.
--
local function simplify_path(path)
local npath=string.gsub(path, "([^/]+)/+%.%./+", "")
if npath~=path then
return simplify_path(npath)
else
return string.gsub(string.gsub(path, "([^/]+)/+%.%.$", ""), "/+", "/")
end
end
local function relative_path(path)
return not string.find(path, "^/")
end
local function empty_path(path)
return (not path or path=="")
end
local function ws_chdir(mplex, params)
local nwd=params[1]
ws=assert(ioncore.find_manager(mplex, "WGroupWS"))
if not empty_path(nwd) and relative_path(nwd) then
local owd=ioncore.get_dir_for(ws)
if empty_path(owd) then
owd=os.getenv("PWD")
end
if owd then
nwd=owd.."/"..nwd
end
end
local ok, err=ioncore.chdir_for(ws, nwd and simplify_path(nwd))
if not ok then
mod_query.warn(mplex, err)
end
end
local function ws_showdir(mplex, params)
local dir=ioncore.get_dir_for(mplex)
if empty_path(dir) then
dir=os.getenv("PWD")
end
mod_query.message(mplex, dir or "(?)")
end
mod_query.defcmd("cd", ws_chdir)
mod_query.defcmd("pwd", ws_showdir)
| lgpl-2.1 |
aiq/basexx | test/bit_spec.lua | 2 | 1062 | basexx = require( "basexx" )
describe( "should handle bitfields strings", function()
it( "should convert data to a bitfields string", function()
assert.is.same( "01000001010000110100010001000011",
basexx.to_bit( "ACDC" ) )
end)
it( "should read data from a bitfields string", function()
assert.is.same( "ACDC",
basexx.from_bit( "01000001010000110100010001000011" ) )
end)
it( "should read data with o instead of 0", function()
assert.is.same( "AC", basexx.from_bit( "o1ooooo1o1oooo11" ) )
assert.is.same( "AC", basexx.from_bit( "OioooooiOiooooii" ) )
end)
it( "should allow to ignore characters in a bitfield string", function()
assert.is.same( "AC", basexx.from_bit( "o1ooooo1 o1oooo11", " " ) )
end)
it( "should handle wrong characters without a crash", function()
local res, err = basexx.from_bit( "o1oo*ooo1*o1oo*oo11" )
assert.is.falsy( res )
assert.is.same( "unexpected character at position 5: '*'", err )
end)
end)
| mit |
code4craft/moonlink | lua/set.lua | 1 | 1477 | --
-- User: code4crafter@gmail.com
-- Date: 13-7-28
-- Time: 下午12:15
--
-- lua redis module https://github.com/agentzh/lua-resty-redis
-- http luad module http://wiki.nginx.org/HttpLuaModule
local redis = require"resty.redis"
local red = redis:new()
local server = "127.0.0.1"
local host = "http://127.0.0.1:8080/"
--connect
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect(server, 6379)
if not ok then
ngx.log(ngx.INFO, "failed to connect: ", err)
ngx.say("failed to connect: ", err)
return
end
--ngx.log(ngx.req.get_uri_args())
--ngx.say(ngx.req.get_uri_args(1))
length = 7
function short(url)
local shortUrl = ngx.md5(url):sub(1, length)
return shortUrl
end
local args = ngx.req.get_uri_args()
if not args["url"] then
ngx.status = 400
ngx.say("Please specific url!")
return
end
local url = args["url"]
if not url:match("^http[s]?://") then
ngx.status = 400
ngx.say("Unsupport url!")
return
end
local shortUrl
local tempUrl = url
while not shortUrl do
shortUrl = short(tempUrl)
local res, err = red:get(shortUrl)
if res==ngx.null then
red:set(shortUrl, url)
break
elseif res==url then
break
end
tempUrl = tempUrl .. "X"
shortUrl = nil
end
ngx.status = 200
ngx.say(host..shortUrl)
-- keepalive
local ok, err = red:set_keepalive(0, 100)
if ok then
ngx.log(ngx.INFO, "Sucessfully keepalive", err)
else
ngx.log(ngx.ERR, "Failed to keepalive", err)
end | bsd-3-clause |
yimogod/boom | trunk/t-engine4/game/engines/engine/Zone.lua | 1 | 37856 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2015 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local Savefile = require "engine.Savefile"
local Dialog = require "engine.ui.Dialog"
local Map = require "engine.Map"
local Astar = require "engine.Astar"
local forceprint = print
local print = function() end
--- Defines a zone: a set of levels, with depth, npcs, objects, level generator, ...
module(..., package.seeall, class.make)
_no_save_fields = {temp_memory_levels=true, _tmp_data=true}
-- Keep a list of currently existing maps
-- this is a weak table so it doesn't prevents GC
__zone_store = {}
setmetatable(__zone_store, {__mode="k"})
--- List of rules to run through when applying an ego to an entity.
_M.ego_rules = {}
--- Adds an ego rule.
-- Static method
function _M:addEgoRule(kind, rule)
self.ego_rules[kind] = self.ego_rules[kind] or {}
table.insert(self.ego_rules[kind], rule)
end
--- Setup classes to use for level generation
-- Static method
-- @param t table that contains the name of the classes to use
-- @usage Required fields:
-- npc_class (default engine.Actor)
-- grid_class (default engine.Grid)
-- object_class (default engine.Object)
function _M:setup(t)
self.map_class = require(t.map_class or "engine.Map")
self.level_class = require(t.level_class or "engine.Level")
self.npc_class = require(t.npc_class or "engine.Actor")
self.grid_class = require(t.grid_class or "engine.Grid")
self.trap_class = require(t.trap_class or "engine.Trap")
self.object_class = require(t.object_class or "engine.Object")
self.on_setup = t.on_setup
self.ood_factor = t.ood_factor or 3
end
--- Set a cache of the last visited zones
-- Static method
-- Zones will be kept in memory (up to max last zones) and the cache will be used to reload, removing the need for disk load, thus speeding up loading
function _M:enableLastPersistZones(max)
_M.persist_last_zones = { config = {max=max} }
end
function _M:addLastPersistZone(zone)
while #_M.persist_last_zones > _M.persist_last_zones.config.max do
local id = table.remove(_M.persist_last_zones)
forceprint("[ZONE] forgetting old zone", id)
local zone = _M.persist_last_zones[id]
_M.persist_last_zones[id] = nil
end
_M.persist_last_zones[zone.short_name] = zone
table.insert(_M.persist_last_zones, 1, zone.short_name)
end
function _M:removeLastPersistZone(id)
for i = 1, #_M.persist_last_zones do
if _M.persist_last_zones[i] == id then
table.remove(_M.persist_last_zones, i)
forceprint("[ZONE] using old zone", id)
_M.persist_last_zones[id] = nil
return
end
end
end
--- Loads a zone definition
-- @param short_name the short name of the zone to load, if should correspond to a directory in your module data/zones/short_name/ with a zone.lua, npcs.lua, grids.lua and objects.lua files inside
function _M:init(short_name, dynamic)
__zone_store[self] = true
if _M.persist_last_zones and _M.persist_last_zones[short_name] then
local zone = _M.persist_last_zones[short_name]
forceprint("[ZONE] loading from last persistent", short_name, zone)
_M:removeLastPersistZone(short_name)
self:replaceWith(zone)
_M:addLastPersistZone(self)
return
end
self.short_name = short_name
self.specific_base_level = self.specific_base_level or {}
if not self:load(dynamic) then
self.level_range = self.level_range or {1,1}
if type(self.level_range) == "number" then self.level_range = {self.level_range, self.level_range} end
self.level_scheme = self.level_scheme or "fixed"
assert(self.max_level, "no zone max level")
self.levels = self.levels or {}
if not dynamic then self:loadBaseLists() end
if self.on_setup then self:on_setup() end
self:updateBaseLevel()
forceprint("Initiated zone", self.name, "with base_level", self.base_level)
else
if self.update_base_level_on_enter then self:updateBaseLevel() end
forceprint("Loaded zone", self.name, "with base_level", self.base_level)
end
if _M.persist_last_zones then
forceprint("[ZONE] persisting to persist_last_zones", self.short_name)
_M:addLastPersistZone(self)
end
self._tmp_data = {}
end
--- Computes the current base level based on the zone infos
function _M:updateBaseLevel()
-- Determine a zone base level
self.base_level = self.level_range[1]
if self.level_scheme == "player" then
local plev = game:getPlayer().level
self.base_level = util.bound(plev, self.level_range[1], self.level_range[2])
end
end
--- Returns the base folder containing the zone
function _M:getBaseName()
local name = self.short_name
local base = "/data"
local _, _, addon, rname = name:find("^([^+]+)%+(.+)$")
if addon and rname then
base = "/data-"..addon
name = rname
end
return base.."/zones/"..name.."/"
end
--- Loads basic entities lists
local _load_zone = nil
function _M:loadBaseLists()
_load_zone = self
self.npc_list = self.npc_class:loadList(self:getBaseName().."npcs.lua")
self.grid_list = self.grid_class:loadList(self:getBaseName().."grids.lua")
self.object_list = self.object_class:loadList(self:getBaseName().."objects.lua")
self.trap_list = self.trap_class:loadList(self:getBaseName().."traps.lua")
_load_zone = nil
end
--- Gets the currently loading zone
function _M:getCurrentLoadingZone()
return _load_zone
end
--- Leaves a zone
-- Saves the zone to a .teaz file if requested with persistent="zone" flag
function _M:leave()
if type(self.persistent) == "string" and self.persistent == "zone" then savefile_pipe:push(game.save_name, "zone", self) end
for id, level in pairs(self.memory_levels or {}) do
level.map:close()
forceprint("[ZONE] Closed level map", id)
end
for id, level in pairs(self.temp_memory_levels or {}) do
level.map:close()
forceprint("[ZONE] Closed level map", id)
end
forceprint("[ZONE] Left zone", self.name)
game.level = nil
end
function _M:level_adjust_level(level, type)
return self.base_level + (self.specific_base_level[type] or 0) + (level.level - 1) + (add_level or 0)
end
function _M:adjustComputeRaritiesLevel(level, type, lev)
return lev
end
--- Parses the npc/objects list and compute rarities for random generation
-- ONLY entities with a rarity properties will be considered.<br/>
-- This means that to get a never-random entity you simply do not put a rarity property on it.
function _M:computeRarities(type, list, level, filter, add_level, rarity_field)
rarity_field = rarity_field or "rarity"
local r = { total=0 }
print("******************", level.level, type)
local lev = self:level_adjust_level(level, self, type) + (add_level or 0)
lev = self:adjustComputeRaritiesLevel(level, type, lev)
for i, e in ipairs(list) do
if e[rarity_field] and e.level_range and (not filter or filter(e)) then
-- print("computing rarity of", e.name)
local max = 10000
if lev < e.level_range[1] then max = 10000 / (self.ood_factor * (e.level_range[1] - lev))
elseif e.level_range[2] and lev > e.level_range[2] then max = 10000 / (lev - e.level_range[2])
end
local genprob = math.floor(max / e[rarity_field])
print(("Entity(%30s) got %3d (=%3d / %3d) chance to generate. Level range(%2d-%2s), current %2d"):format(e.name, math.floor(genprob), math.floor(max), e[rarity_field], e.level_range[1], e.level_range[2] or "--", lev))
-- Generate and store egos list if needed
if e.egos and e.egos_chance then
if _G.type(e.egos_chance) == "number" then e.egos_chance = {e.egos_chance} end
for ie, edata in pairs(e.egos_chance) do
local etype = ie
if _G.type(ie) == "number" then etype = "" end
if not level:getEntitiesList(type.."/"..e.egos..":"..etype) then
self:generateEgoEntities(level, type, etype, e.egos, e.__CLASSNAME)
end
end
end
-- Generate and store addons list if needed
if e.addons then
if not level:getEntitiesList(type.."/"..e.addons..":addon") then
self:generateEgoEntities(level, type, "addon", e.addons, e.__CLASSNAME)
end
end
if genprob > 0 then
-- genprob = math.ceil(genprob / 10 * math.sqrt(genprob))
r.total = r.total + genprob
r[#r+1] = { e=e, genprob=r.total, level_diff = lev - level.level }
end
end
end
table.sort(r, function(a, b) return a.genprob < b.genprob end)
local prev = 0
local tperc = 0
for i, ee in ipairs(r) do
local perc = 100 * (ee.genprob - prev) / r.total
tperc = tperc + perc
print(("entity chance %2d : chance(%4d : %4.5f%%): %s"):format(i, ee.genprob, perc, ee.e.name))
prev = ee.genprob
end
print("*DONE", r.total, tperc.."%")
return r
end
--- Checks an entity against a filter
function _M:checkFilter(e, filter, type)
if e.unique and game.uniques[e.__CLASSNAME.."/"..e.unique] then print("refused unique", e.name, e.__CLASSNAME.."/"..e.unique) return false end
if not filter then return true end
if filter.ignore and self:checkFilter(e, filter.ignore, type) then return false end
print("Checking filter", filter.type, filter.subtype, "::", e.type,e.subtype,e.name)
if filter.type and filter.type ~= e.type then return false end
if filter.subtype and filter.subtype ~= e.subtype then return false end
if filter.name and filter.name ~= e.name then return false end
if filter.define_as and filter.define_as ~= e.define_as then return false end
if filter.unique and not e.unique then return false end
if filter.properties then
for i = 1, #filter.properties do if not e[filter.properties[i]] then return false end end
end
if filter.not_properties then
for i = 1, #filter.not_properties do if e[filter.not_properties[i]] then return false end end
end
if e.checkFilter and not e:checkFilter(filter) then return false end
if filter.special and not filter.special(e) then return false end
if self.check_filter and not self:check_filter(e, filter, type) then return false end
if filter.max_ood and resolvers.current_level and e.level_range and resolvers.current_level + filter.max_ood < e.level_range[1] then print("Refused max_ood", e.name, e.level_range[1]) return false end
if e.unique then print("accepted unique", e.name, e.__CLASSNAME.."/"..e.unique) end
return true
end
--- Return a string describing the filter
function _M:filterToString(filter)
local ps = ""
for what, check in pairs(filter) do
ps = ps .. what.."="..check..","
end
return ps
end
--- Picks an entity from a computed probability list
function _M:pickEntity(list)
if #list == 0 then return nil end
local r = rng.range(1, list.total)
for i = 1, #list do
-- print("test", r, ":=:", list[i].genprob)
if r <= list[i].genprob then
-- print(" * select", list[i].e.name)
return list[i].e
end
end
return nil
end
--- Compute posible egos for this list
function _M:generateEgoEntities(level, type, etype, e_egos, e___CLASSNAME)
print("Generating specific ego list", type.."/"..e_egos..":"..etype)
local egos = self:getEgosList(level, type, e_egos, e___CLASSNAME)
if egos then
local egos_prob = self:computeRarities(type, egos, level, etype ~= "" and function(e) return e[etype] end or nil)
level:setEntitiesList(type.."/"..e_egos..":"..etype, egos_prob)
level:setEntitiesList(type.."/base/"..e_egos..":"..etype, egos)
return egos_prob
end
end
--- Gets the possible egos
function _M:getEgosList(level, type, group, class)
-- Already loaded ? use it
local list = level:getEntitiesList(type.."/"..group)
if list then return list end
-- otherwise loads it and store it
list = require(class):loadList(group, true)
level:setEntitiesList(type.."/"..group, list)
return list
end
function _M:getEntities(level, type)
local list = level:getEntitiesList(type)
if not list then
if type == "actor" then level:setEntitiesList("actor", self:computeRarities("actor", self.npc_list, level, nil))
elseif type == "object" then level:setEntitiesList("object", self:computeRarities("object", self.object_list, level, nil))
elseif type == "trap" then level:setEntitiesList("trap", self:computeRarities("trap", self.trap_list, level, nil))
end
list = level:getEntitiesList(type)
end
return list
end
--- Picks and resolve an entity
-- @param level a Level object to generate for
-- @param type one of "object" "terrain" "actor" "trap"
-- @param filter a filter table
-- @param force_level if not nil forces the current level for resolvers to this one
-- @param prob_filter if true a new probability list based on this filter will be generated, ensuring to find objects better but at a slightly slower cost (maybe)
-- @return the fully resolved entity, ready to be used on a level. Or nil if a filter was given an nothing found
function _M:makeEntity(level, type, filter, force_level, prob_filter)
resolvers.current_level = self.base_level + level.level - 1
if force_level then resolvers.current_level = force_level end
if prob_filter == nil then prob_filter = util.getval(self.default_prob_filter, self, type) end
if filter == nil then filter = util.getval(self.default_filter, self, level, type) end
if filter and self.alter_filter then filter = util.getval(self.alter_filter, self, level, type, filter) end
local e
-- No probability list, use the default one and apply filter
if not prob_filter then
local list = self:getEntities(level, type)
local tries = filter and filter.nb_tries or 500
-- CRUDE ! Brute force ! Make me smarter !
while tries > 0 do
e = self:pickEntity(list)
if e and self:checkFilter(e, filter, type) then break end
tries = tries - 1
end
if tries == 0 then return nil end
-- Generate a specific probability list, slower to generate but no need to "try and be lucky"
elseif filter then
local base_list = nil
if filter.base_list then
if _G.type(filter.base_list) == "table" then base_list = filter.base_list
else
local _, _, class, file = filter.base_list:find("(.*):(.*)")
if class and file then
base_list = require(class):loadList(file)
end
end
elseif type == "actor" then base_list = self.npc_list
elseif type == "object" then base_list = self.object_list
elseif type == "trap" then base_list = self.trap_list
else base_list = self:getEntities(level, type) if not base_list then return nil end end
local list = self:computeRarities(type, base_list, level, function(e) return self:checkFilter(e, filter, type) end, filter.add_levels, filter.special_rarity)
e = self:pickEntity(list)
print("[MAKE ENTITY] prob list generation", e and e.name, "from list size", #list)
if not e then return nil end
-- No filter
else
local list = self:getEntities(level, type)
local tries = filter and filter.nb_tries or 50 -- A little crude here too but we only check 50 times, this is simply to prevent duplicate uniques
while tries > 0 do
e = self:pickEntity(list)
if e and self:checkFilter(e, nil, type) then break end
tries = tries - 1
end
if tries == 0 then return nil end
end
if filter then e.force_ego = filter.force_ego end
if filter and self.post_filter then e = util.getval(self.post_filter, self, level, type, e, filter) or e end
e = self:finishEntity(level, type, e, (filter and filter.ego_filter) or (filter and filter.ego_chance))
e.__forced_level = filter and filter.add_levels
return e
end
--- Find a given entity and resolve it
-- @return the fully resolved entity, ready to be used on a level. Or nil if a filter was given an nothing found
function _M:makeEntityByName(level, type, name, force_unique)
resolvers.current_level = self.base_level + level.level - 1
local e
if _G.type(type) == "table" then e = type[name] type = type.__real_type or type
elseif type == "actor" then e = self.npc_list[name]
elseif type == "object" then e = self.object_list[name]
elseif type == "grid" or type == "terrain" then e = self.grid_list[name]
elseif type == "trap" then e = self.trap_list[name]
end
if not e then return nil end
local forced = false
if e.unique and game.uniques[e.__CLASSNAME.."/"..e.unique] then
if not force_unique then
forceprint("Refused unique by name", e.name, e.__CLASSNAME.."/"..e.unique)
return nil
else
forced = true
end
end
e = self:finishEntity(level, type, e)
return e, forced
end
local pick_ego = function(self, level, e, eegos, egos_list, type, picked_etype, etype, ego_filter)
picked_etype[etype] = true
if _G.type(etype) == "number" then etype = "" end
local egos = e.egos and level:getEntitiesList(type.."/"..e.egos..":"..etype)
if not egos then egos = self:generateEgoEntities(level, type, etype, eegos, e.__CLASSNAME) end
if self.ego_filter then ego_filter = self.ego_filter(self, level, type, etype, e, ego_filter, egos_list, picked_etype) end
-- Filter the egos if needed
if ego_filter then
local list = {}
for z = 1, #egos do list[#list+1] = egos[z].e end
egos = self:computeRarities(type, list, level, function(e) return self:checkFilter(e, ego_filter) end, ego_filter.add_levels, ego_filter.special_rarity)
end
egos_list[#egos_list+1] = self:pickEntity(egos)
if egos_list[#egos_list] then print("Picked ego", type.."/"..eegos..":"..etype, ":=>", egos_list[#egos_list].name) else print("Picked ego", type.."/"..eegos..":"..etype, ":=>", #egos_list) end
end
-- Applies a single ego to a (pre-resolved) entity
-- May be in need to resolve afterwards
function _M:applyEgo(e, ego, type, no_name_change)
if not e.__original then e.__original = e:clone() end
print("ego", ego.__CLASSNAME, ego.name, getmetatable(ego))
ego = ego:clone()
local newname = e.name
if not no_name_change then
local display = ego.display_string or ego.name
if ego.prefix or ego.display_prefix then newname = display .. e.name
else newname = e.name .. display end
end
print("applying ego", ego.name, "to ", e.name, "::", newname, "///", e.unided_name, ego.unided_name)
-- The ego requested instant resolving before merge ?
if ego.instant_resolve then ego:resolve(nil, nil, e) end
if ego.instant_resolve == "last" then ego:resolve(nil, true, e) end
ego.instant_resolve = nil
local save_ego = ego:clone() -- AFTER resolve, no rerolls
ego.unided_name = nil
ego.__CLASSNAME = nil
ego.__ATOMIC = nil
-- Void the uid, we dont want to erase the base entity's one
ego.uid = nil
ego.rarity = nil
ego.level_range = nil
-- Merge according to Object's ego rules.
table.ruleMergeAppendAdd(e, ego, self.ego_rules[type] or {})
e.name = newname
if not ego.fake_ego then
e.egoed = true
e.egos_number = (e.egos_number or 0) + 1
end
e.ego_list = e.ego_list or {}
e.ego_list[#e.ego_list + 1] = {save_ego, type, no_name_change}
end
-- WARNING the thing may be in need of re-identifying after this
local function reapplyEgos(self, e)
if not e.__original then return e end
local id = e.isIdentified and e:isIdentified()
local brandNew = e.__original -- it will be cloned upon first ego application
if e.ego_list and #e.ego_list > 0 then
for _, ego_args in ipairs(e.ego_list) do
self:applyEgo(brandNew, unpack(ego_args))
end
end
e:replaceWith(brandNew)
if e.identify then e:identify(id) end
end
-- Remove an ego
function _M:removeEgo(e, ego)
local idx = nil
for i, v in ipairs(e.ego_list or {}) do
if v[1] == ego then
idx = i
end
end
if not idx then return end
table.remove(e.ego_list, idx)
reapplyEgos(self, e)
return ego
end
function _M:replaceEgo(e, ego1, ego2, type, no_name_change)
if not e.ego_list or not ego1 then self:applyEgo(e, ego2, type, no_name_change) return e end
local idx = nil
for i, v in ipairs(e.ego_list) do
if v[1] == ego1 then
idx = i
end
end
idx = idx or #e.ego_list + 1
e.ego_list[idx] = {ego2, type, no_name_change}
reapplyEgos(self, e)
return e
end
function _M:getEgoByName(e, ego_name)
for i, v in ipairs(e.ego_list or {}) do
if v[1].name == ego_name then return v[1] end
end
end
function _M:removeEgoByName(e, ego_name)
for i, v in ipairs(e.ego_list or {}) do
if v[1].name == ego_name then return self:removeEgo(e, v[1]) end
end
end
function _M:setEntityEgoList(e, list)
e.ego_list = table.clone(list)
reapplyEgos(self, e)
return e
end
--- Finishes generating an entity
function _M:finishEntity(level, type, e, ego_filter)
e = e:clone()
e:resolve()
-- Add "addon" properties, always
if not e.unique and e.addons then
local egos_list = {}
pick_ego(self, level, e, e.addons, egos_list, type, {}, "addon", nil)
if #egos_list > 0 then
for ie, ego in ipairs(egos_list) do
self:applyEgo(e, ego, type)
end
-- Re-resolve with the (possibly) new resolvers
e:resolve()
end
e.addons = nil
end
-- Add "ego" properties, sometimes
if not e.unique and e.egos and (e.force_ego or e.egos_chance) then
local egos_list = {}
local ego_chance = 0
if _G.type(ego_filter) == "number" then ego_chance = ego_filter; ego_filter = nil
elseif _G.type(ego_filter) == "table" then ego_chance = ego_filter.ego_chance or 0
else ego_filter = nil
end
if not e.force_ego then
if _G.type(e.egos_chance) == "number" then e.egos_chance = {e.egos_chance} end
if not ego_filter or not ego_filter.tries then
--------------------------------------
-- Natural ego
--------------------------------------
-- Pick an ego, then an other and so until we get no more
local chance_decay = 1
local picked_etype = {}
local etype = e.ego_first_type and e.ego_first_type or rng.tableIndex(e.egos_chance, picked_etype)
local echance = etype and e.egos_chance[etype]
while etype and rng.percent(util.bound(echance / chance_decay + (ego_chance or 0), 0, 100)) do
pick_ego(self, level, e, e.egos, egos_list, type, picked_etype, etype, ego_filter)
etype = rng.tableIndex(e.egos_chance, picked_etype)
echance = e.egos_chance[etype]
if e.egos_chance_decay then chance_decay = chance_decay * e.egos_chance_decay end
end
else
--------------------------------------
-- Semi Natural ego
--------------------------------------
-- Pick an ego, then an other and so until we get no more
local picked_etype = {}
for i = 1, #ego_filter.tries do
local try = ego_filter.tries[i]
local etype = (i == 1 and e.ego_first_type and e.ego_first_type) or rng.tableIndex(e.egos_chance, picked_etype)
-- forceprint("EGO TRY", i, ":", etype, echance, try)
if not etype then break end
local echance = etype and try[etype]
pick_ego(self, level, e, e.egos, egos_list, type, picked_etype, etype, try)
end
end
else
--------------------------------------
-- Forced ego
--------------------------------------
local name = e.force_ego
if _G.type(name) == "table" then name = rng.table(name) end
print("Forcing ego", name)
local egos = level:getEntitiesList(type.."/base/"..e.egos..":")
egos_list = {egos[name]}
e.force_ego = nil
end
if #egos_list > 0 then
for ie, ego in ipairs(egos_list) do
self:applyEgo(e, ego, type)
end
-- Re-resolve with the (possibly) new resolvers
e:resolve()
end
if not ego_filter or not ego_filter.keep_egos then
e.egos = nil e.egos_chance = nil e.force_ego = nil
end
end
-- Generate a stack ?
if e.generate_stack then
local s = {}
while e.generate_stack > 0 do
s[#s+1] = e:clone()
e.generate_stack = e.generate_stack - 1
end
for i = 1, #s do e:stack(s[i], true) end
end
e:resolve(nil, true)
e:check("finish", e, self, level)
return e
end
--- Do the various stuff needed to setup an entity on the level
-- Grids do not really need that, this is mostly done for traps, objects and actors<br/>
-- This will do all the correct initializations and setup required
-- @param level the level on which to add the entity
-- @param e the entity to add
-- @param typ the type of entity, one of "actor", "object", "trap" or "terrain"
-- @param x the coordinates where to add it. This CAN be null in which case it wont be added to the map
-- @param y the coordinates where to add it. This CAN be null in which case it wont be added to the map
function _M:addEntity(level, e, typ, x, y, no_added)
if typ == "actor" then
-- We are additing it, this means there is no old position
e.x = nil
e.y = nil
if x and y then e:move(x, y, true) end
level:addEntity(e, nil, true)
if not no_added then e:added() end
-- Levelup ?
if self.actor_adjust_level and e.forceLevelup then
local newlevel = self:actor_adjust_level(level, e)
e:forceLevelup(newlevel + (e.__forced_level or 0))
end
elseif typ == "projectile" then
-- We are additing it, this means there is no old position
e.x = nil
e.y = nil
if x and y then e:move(x, y, true) end
if e.src then level:addEntity(e, e.src, true)
else level:addEntity(e, nil, true) end
if not no_added then e:added() end
elseif typ == "object" then
if x and y then level.map:addObject(x, y, e) end
if not no_added then e:added() end
elseif typ == "trap" then
if x and y then level.map(x, y, Map.TRAP, e) end
if not no_added then e:added() end
elseif typ == "terrain" or typ == "grid" then
if x and y then level.map(x, y, Map.TERRAIN, e) end
end
e:check("addedToLevel", level, x, y)
e:check("on_added", level, x, y)
end
--- If we are loaded we need a new uid
function _M:loaded()
__zone_store[self] = true
self._tmp_data = {}
if type(self.reload_lists) ~= "boolean" or self.reload_lists then
self:loadBaseLists()
end
if self.on_loaded then self:on_loaded() end
end
function _M:load(dynamic)
local ret = true
-- Try to load from a savefile
local data = savefile_pipe:doLoad(game.save_name, "zone", nil, self.short_name)
if not data and not dynamic then
local f, err = loadfile(self:getBaseName().."zone.lua")
if err then error(err) end
setfenv(f, setmetatable({self=self, short_name=self.short_name}, {__index=_G}))
data = f()
ret = false
if type(data.reload_lists) ~= "boolean" or data.reload_lists then
self._no_save_fields = table.clone(self._no_save_fields, true)
self._no_save_fields.npc_list = true
self._no_save_fields.grid_list = true
self._no_save_fields.object_list = true
self._no_save_fields.trap_list = true
end
for k, e in pairs(data) do self[k] = e end
self:onLoadZoneFile(self:getBaseName())
self:triggerHook{"Zone:create", dynamic=dynamic}
if self.on_loaded then self:on_loaded() end
elseif not data and dynamic then
data = dynamic
ret = false
for k, e in pairs(data) do self[k] = e end
self:triggerHook{"Zone:create", dynamic=dynamic}
if self.on_loaded then self:on_loaded() end
else
for k, e in pairs(data) do self[k] = e end
end
return ret
end
--- Called when the zone file is loaded
-- Does nothing, overload it
function _M:onLoadZoneFile(basedir)
end
local recurs = function(t)
local nt = {}
for k, e in pairs(nt) do if k ~= "__CLASSNAME" and k ~= "__ATOMIC" then nt[k] = e end end
return nt
end
function _M:getLevelData(lev)
local res = table.clone(self, true, self._no_save_fields)
if self.levels[lev] then
table.merge(res, self.levels[lev], true, self._no_save_fields)
end
if res.alter_level_data then res.alter_level_data(self, lev, res) end
-- Make sure it is not considered a class
res.__CLASSNAME = nil
res.__ATOMIC = nil
return res
end
--- Leave the level, forgetting uniques and such
function _M:leaveLevel(no_close, lev, old_lev)
-- Before doing anything else, close the current level
if not no_close and game.level and game.level.map then
game:leaveLevel(game.level, lev, old_lev)
if type(game.level.data.persistent) == "string" and game.level.data.persistent == "zone_temporary" then
print("[LEVEL] persisting to zone memory (temporary)", game.level.id)
self.temp_memory_levels = self.temp_memory_levels or {}
self.temp_memory_levels[game.level.level] = game.level
elseif type(game.level.data.persistent) == "string" and game.level.data.persistent == "zone" and not self.save_per_level then
print("[LEVEL] persisting to zone memory", game.level.id)
self.memory_levels = self.memory_levels or {}
self.memory_levels[game.level.level] = game.level
elseif type(game.level.data.persistent) == "string" and game.level.data.persistent == "memory" then
print("[LEVEL] persisting to memory", game.level.id)
game.memory_levels = game.memory_levels or {}
game.memory_levels[game.level.id] = game.level
elseif game.level.data.persistent then
print("[LEVEL] persisting to disk file", game.level.id)
savefile_pipe:push(game.save_name, "level", game.level)
game.level.map:close()
else
game.level:removed()
game.level.map:close()
end
end
end
--- Asks the zone to generate a level of level "lev"
-- @param lev the level (from 1 to zone.max_level)
-- @return a Level object
function _M:getLevel(game, lev, old_lev, no_close)
self:leaveLevel(no_close, lev, old_lev)
local level_data = self:getLevelData(lev)
local levelid = self.short_name.."-"..lev
local level
local new_level = false
-- Load persistent level?
if type(level_data.persistent) == "string" and level_data.persistent == "zone_temporary" then
forceprint("Loading zone temporary level", self.short_name, lev)
local popup = Dialog:simpleWaiter("Loading level", "Please wait while loading the level...", nil, 10000)
core.display.forceRedraw()
self.temp_memory_levels = self.temp_memory_levels or {}
level = self.temp_memory_levels[lev]
if level then
-- Setup the level in the game
game:setLevel(level)
-- Recreate the map because it could have been saved with a different tileset or whatever
-- This is not needed in case of a direct to file persistance becuase the map IS recreated each time anyway
level.map:recreate()
end
popup:done()
elseif type(level_data.persistent) == "string" and level_data.persistent == "zone" and not self.save_per_level then
forceprint("Loading zone persistance level", self.short_name, lev)
local popup = Dialog:simpleWaiter("Loading level", "Please wait while loading the level...", nil, 10000)
core.display.forceRedraw()
self.memory_levels = self.memory_levels or {}
level = self.memory_levels[lev]
if level then
-- Setup the level in the game
game:setLevel(level)
-- Recreate the map because it could have been saved with a different tileset or whatever
-- This is not needed in case of a direct to file persistance becuase the map IS recreated each time anyway
level.map:recreate()
end
popup:done()
elseif type(level_data.persistent) == "string" and level_data.persistent == "memory" then
forceprint("Loading memory persistance level", self.short_name, lev)
local popup = Dialog:simpleWaiter("Loading level", "Please wait while loading the level...", nil, 10000)
core.display.forceRedraw()
game.memory_levels = game.memory_levels or {}
level = game.memory_levels[levelid]
if level then
-- Setup the level in the game
game:setLevel(level)
-- Recreate the map because it could have been saved with a different tileset or whatever
-- This is not needed in case of a direct to file persistance becuase the map IS recreated each time anyway
level.map:recreate()
end
popup:done()
elseif level_data.persistent then
forceprint("Loading level persistance level", self.short_name, lev)
local popup = Dialog:simpleWaiter("Loading level", "Please wait while loading the level...", nil, 10000)
core.display.forceRedraw()
-- Try to load from a savefile
level = savefile_pipe:doLoad(game.save_name, "level", nil, self.short_name, lev)
if level then
-- Setup the level in the game
game:setLevel(level)
end
popup:done()
end
-- In any cases, make one if none was found
if not level then
forceprint("Creating level", self.short_name, lev)
local popup = Dialog:simpleWaiter("Generating level", "Please wait while generating the level...", nil, 10000)
core.display.forceRedraw()
level = self:newLevel(level_data, lev, old_lev, game)
new_level = true
popup:done()
end
-- Clean up things
collectgarbage("collect")
-- Re-open the level if needed (the method does the check itself)
level.map:reopen()
return level, new_level
end
function _M:getGenerator(what, level, spots)
assert(level.data.generator[what], "requested zone generator of type "..tostring(what).." but it is not defined")
assert(level.data.generator[what].class, "requested zone generator of type "..tostring(what).." but it has no class field")
print("[GENERATOR] requiring", what, level.data.generator and level.data.generator[what] and level.data.generator[what].class)
if not level.data.generator[what].zoneclass then
return require(level.data.generator[what].class).new(
self,
level.map,
level,
spots
)
else
local base = require(level.data.generator[what].class)
local c = class.inherit(base){}
local name = self:getBaseName().."generator"..what:capitalize()..".lua"
print("[ZONE] Custom zone generator for "..what.." loading from "..name)
local add = loadfile(name)
setfenv(add, setmetatable({
_M = c,
baseGenerator = base,
Zone = _M,
Map = Map,
}, {__index=_G}))
add()
return c.new(
self,
level.map,
level,
spots
)
end
end
function _M:newLevel(level_data, lev, old_lev, game)
local map = self.map_class.new(level_data.width, level_data.height)
map.updateMap = function() end
if level_data.all_lited then map:liteAll(0, 0, map.w, map.h) end
if level_data.all_remembered then map:rememberAll(0, 0, map.w, map.h) end
-- Setup the entities list
local level = self.level_class.new(lev, map)
level:setEntitiesList("actor", self:computeRarities("actor", self.npc_list, level, nil))
level:setEntitiesList("object", self:computeRarities("object", self.object_list, level, nil))
level:setEntitiesList("trap", self:computeRarities("trap", self.trap_list, level, nil))
-- Save level data
level.data = level_data or {}
level.id = self.short_name.."-"..lev
-- Setup the level in the game
game:setLevel(level)
-- Generate the map
local generator = self:getGenerator("map", level, level_data.generator.map)
local ux, uy, dx, dy, spots = generator:generate(lev, old_lev)
if level.force_recreate then
level:removed()
return self:newLevel(level_data, lev, old_lev, game)
end
spots = spots or {}
for i = 1, #spots do print("[NEW LEVEL] spot", spots[i].x, spots[i].y, spots[i].type, spots[i].subtype) end
level.default_up = {x=ux, y=uy}
level.default_down = {x=dx, y=dy}
level.spots = spots
-- Call a map finisher
if level_data.post_process_map then
level_data.post_process_map(level, self)
if level.force_recreate then
level:removed()
return self:newLevel(level_data, lev, old_lev, game)
end
end
-- Add the entities we are told to
for i = 0, map.w - 1 do for j = 0, map.h - 1 do
if map.room_map[i] and map.room_map[i][j] and map.room_map[i][j].add_entities then
for z = 1, #map.room_map[i][j].add_entities do
local ae = map.room_map[i][j].add_entities[z]
self:addEntity(level, ae[2], ae[1], i, j, true)
end
end
end end
-- Now update it all in one go (faster than letter the generators do it since they usualy overlay multiple terrains)
map.updateMap = nil
map:redisplay()
-- Generate actors
if level_data.generator.actor and level_data.generator.actor.class then
local generator = self:getGenerator("actor", level, spots)
generator:generate()
end
-- Generate objects
if level_data.generator.object and level_data.generator.object.class then
local generator = self:getGenerator("object", level, spots)
generator:generate()
end
-- Generate traps
if level_data.generator.trap and level_data.generator.trap.class then
local generator = self:getGenerator("trap", level, spots)
generator:generate()
end
-- Adjust shown & obscure colors
if level_data.color_shown then map:setShown(unpack(level_data.color_shown)) end
if level_data.color_obscure then map:setObscure(unpack(level_data.color_obscure)) end
-- Call a finisher
if level_data.post_process then
level_data.post_process(level, self)
if level.force_recreate then
level:removed()
return self:newLevel(level_data, lev, old_lev, game)
end
end
-- Delete the room_map, now useless
map.room_map = nil
-- Check for connectivity from entrance to exit
local a = Astar.new(map, game:getPlayer())
if not level_data.no_level_connectivity then
print("[LEVEL GENERATION] checking entrance to exit A*", ux, uy, "to", dx, dy)
if ux and uy and dx and dy and (ux ~= dx or uy ~= dy) and not a:calc(ux, uy, dx, dy) then
forceprint("Level unconnected, no way from entrance to exit", ux, uy, "to", dx, dy)
level:removed()
return self:newLevel(level_data, lev, old_lev, game)
end
end
for i = 1, #spots do
local spot = spots[i]
if spot.check_connectivity then
local cx, cy
if type(spot.check_connectivity) == "string" and spot.check_connectivity == "entrance" then cx, cy = ux, uy
elseif type(spot.check_connectivity) == "string" and spot.check_connectivity == "exit" then cx, cy = dx, dy
else cx, cy = spot.check_connectivity.x, spot.check_connectivity.y
end
print("[LEVEL GENERATION] checking A*", spot.x, spot.y, "to", cx, cy)
if spot.x and spot.y and cx and cy and (spot.x ~= cx or spot.y ~= cy) and not a:calc(spot.x, spot.y, cx, cy) then
forceprint("Level unconnected, no way from", spot.x, spot.y, "to", cx, cy)
level:removed()
return self:newLevel(level_data, lev, old_lev, game)
end
end
end
return level
end
| apache-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/strongDisease.lua | 2 | 2318 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
StrongDiseaseCommand = {
name = "strongdisease",
combatSpam = "attack",
dotEffects = {
DotEffect(
DISEASED,
{ "resistance_disease", "poison_disease_resist" },
HEALTH,
true,
125,
60,
80,
405,
45
)
}
}
AddCommand(StrongDiseaseCommand)
| agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/faction/imperial/serverobjects.lua | 2 | 7058 | includeFile("faction/imperial/assault_trooper.lua")
includeFile("faction/imperial/assault_trooper_squad_leader.lua")
includeFile("faction/imperial/at_at.lua")
includeFile("faction/imperial/at_st.lua")
includeFile("faction/imperial/bombardier.lua")
includeFile("faction/imperial/civilian_patrolman.lua")
includeFile("faction/imperial/civil_patrol_captain.lua")
includeFile("faction/imperial/civil_patrol_commander.lua")
includeFile("faction/imperial/civil_patrol_corporal.lua")
includeFile("faction/imperial/civil_patrol_sergeant.lua")
includeFile("faction/imperial/command_security_guard.lua")
includeFile("faction/imperial/comm_operator.lua")
includeFile("faction/imperial/compforce_trooper.lua")
includeFile("faction/imperial/corporal_sova.lua")
includeFile("faction/imperial/crackdown_command_security_guard.lua")
includeFile("faction/imperial/crackdown_comm_operator.lua")
includeFile("faction/imperial/crackdown_elite_dark_trooper.lua")
includeFile("faction/imperial/crackdown_elite_sand_trooper.lua")
includeFile("faction/imperial/crackdown_dark_trooper.lua")
includeFile("faction/imperial/crackdown_imperial_army_captain.lua")
includeFile("faction/imperial/crackdown_imperial_colonel.lua")
includeFile("faction/imperial/crackdown_imperial_corporal.lua")
includeFile("faction/imperial/crackdown_imperial_exterminator.lua")
includeFile("faction/imperial/crackdown_imperial_first_lieutenant.lua")
includeFile("faction/imperial/crackdown_imperial_master_sergeant.lua")
includeFile("faction/imperial/crackdown_imperial_medic.lua")
includeFile("faction/imperial/crackdown_imperial_noncom.lua")
includeFile("faction/imperial/crackdown_imperial_sergeant.lua")
includeFile("faction/imperial/crackdown_imperial_sharpshooter.lua")
includeFile("faction/imperial/crackdown_imperial_warrant_officer_li.lua")
includeFile("faction/imperial/crackdown_imperial_warrant_officer_ii.lua")
includeFile("faction/imperial/crackdown_sand_trooper.lua")
includeFile("faction/imperial/crackdown_scout_trooper.lua")
includeFile("faction/imperial/crackdown_sand_trooper_hard.lua")
includeFile("faction/imperial/crackdown_scout_trooper_hard.lua")
includeFile("faction/imperial/crackdown_specialist_noncom.lua")
includeFile("faction/imperial/crackdown_storm_commando.lua")
includeFile("faction/imperial/crackdown_stormtrooper_bombardier.lua")
includeFile("faction/imperial/crackdown_stormtrooper_captain.lua")
includeFile("faction/imperial/crackdown_stormtrooper.lua")
includeFile("faction/imperial/crackdown_stormtrooper_medic.lua")
includeFile("faction/imperial/crackdown_stormtrooper_rifleman.lua")
includeFile("faction/imperial/crackdown_stormtrooper_sniper.lua")
includeFile("faction/imperial/crackdown_stormtrooper_squad_leader.lua")
includeFile("faction/imperial/crackdown_swamp_trooper.lua")
includeFile("faction/imperial/dark_trooper.lua")
includeFile("faction/imperial/darknovatrooper.lua")
includeFile("faction/imperial/detention_security_guard.lua")
includeFile("faction/imperial/droid_corps_junior_technician.lua")
includeFile("faction/imperial/elite_sand_trooper.lua")
includeFile("faction/imperial/emperors_hand.lua")
includeFile("faction/imperial/general_otto.lua")
includeFile("faction/imperial/gunner.lua")
includeFile("faction/imperial/high_colonel.lua")
includeFile("faction/imperial/imperial_army_captain.lua")
includeFile("faction/imperial/imperial_brigadier_general.lua")
includeFile("faction/imperial/imperial_cadet.lua")
includeFile("faction/imperial/imperial_cadet_squadleader.lua")
includeFile("faction/imperial/imperial_captain.lua")
includeFile("faction/imperial/imperial_colonel.lua")
includeFile("faction/imperial/imperial_corporal.lua")
includeFile("faction/imperial/imperial_first_lieutenant.lua")
includeFile("faction/imperial/imperial_general.lua")
includeFile("faction/imperial/imperial_high_general.lua")
includeFile("faction/imperial/imperial_inquisitor.lua")
includeFile("faction/imperial/imperial_lance_corporal.lua")
includeFile("faction/imperial/imperial_lieutenant_colonel.lua")
includeFile("faction/imperial/imperial_lieutenant_general.lua")
includeFile("faction/imperial/imperial_major_general.lua")
includeFile("faction/imperial/imperial_major.lua")
includeFile("faction/imperial/imperial_master_sergeant.lua")
includeFile("faction/imperial/imperial_medic.lua")
includeFile("faction/imperial/imperial_moff.lua")
includeFile("faction/imperial/imperial_noncom.lua")
includeFile("faction/imperial/imperial_officer.lua")
includeFile("faction/imperial/imperial_pilot.lua")
includeFile("faction/imperial/imperial_private.lua")
includeFile("faction/imperial/imperial_probe_drone.lua")
includeFile("faction/imperial/imperial_recruiter.lua")
includeFile("faction/imperial/imperial_scientist.lua")
includeFile("faction/imperial/imperial_second_lieutenant.lua")
includeFile("faction/imperial/imperial_senior_cadet.lua")
includeFile("faction/imperial/imperial_sergeant.lua")
includeFile("faction/imperial/imperial_sergeant_major.lua")
includeFile("faction/imperial/imperial_sharpshooter.lua")
includeFile("faction/imperial/imperial_staff_corporal.lua")
includeFile("faction/imperial/imperial_staff_sergeant.lua")
includeFile("faction/imperial/imperial_stealth_operative.lua")
includeFile("faction/imperial/imperial_surface_marshall.lua")
includeFile("faction/imperial/imperial_trooper.lua")
includeFile("faction/imperial/imperial_warrant_officer_ii.lua")
includeFile("faction/imperial/imperial_warrant_officer_i.lua")
includeFile("faction/imperial/imprisoned_imperial_officer.lua")
includeFile("faction/imperial/lance_bombardier.lua")
includeFile("faction/imperial/lesser_prophet_of_the_dark_side.lua")
includeFile("faction/imperial/master_prophet_of_the_dark_side.lua")
includeFile("faction/imperial/prophet_of_the_dark_side.lua")
includeFile("faction/imperial/royal_imperial_guard.lua")
includeFile("faction/imperial/sand_trooper.lua")
includeFile("faction/imperial/scout_trooper.lua")
includeFile("faction/imperial/senior_prophet_of_the_dark_side.lua")
includeFile("faction/imperial/signalman.lua")
includeFile("faction/imperial/specialist_noncom.lua")
includeFile("faction/imperial/special_missions_engineer.lua")
includeFile("faction/imperial/storm_commando.lua")
includeFile("faction/imperial/stormtrooper_black_hole.lua")
includeFile("faction/imperial/stormtrooper_black_hole_squad_leader.lua")
includeFile("faction/imperial/stormtrooper_bombardier.lua")
includeFile("faction/imperial/stormtrooper_captain.lua")
includeFile("faction/imperial/stormtrooper_colonel.lua")
includeFile("faction/imperial/stormtrooper_commando.lua")
includeFile("faction/imperial/stormtrooper_groupleader.lua")
includeFile("faction/imperial/stormtrooper.lua")
includeFile("faction/imperial/stormtrooper_major.lua")
includeFile("faction/imperial/stormtrooper_medic.lua")
includeFile("faction/imperial/stormtrooper_rifleman.lua")
includeFile("faction/imperial/stormtrooper_sniper.lua")
includeFile("faction/imperial/stormtrooper_squad_leader.lua")
includeFile("faction/imperial/veteran_compforce_trooper.lua")
includeFile("faction/imperial/warden_vinzel_heylon.lua")
| agpl-3.0 |
alinofel/zooz11 | plugins/anti_spam.lua | 2 | 5437 | --An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
--Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
--Save stats on Redis
if msg.to.type == 'channel' then
-- User is on channel
local hash = 'channel:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
if msg.to.type == 'user' then
-- User is on chat
local hash = 'PM:'..msg.from.id
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is on or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
--Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
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'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
local chat = msg.to.id
local whitelist = "whitelist"
local is_whitelisted = redis:sismember(whitelist, user)
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
if is_whitelisted == true then
return msg
end
local receiver = get_receiver(msg)
if msg.to.type == 'user' then
local max_msg = 7 * 1
print(msgs)
if msgs >= max_msg then
print("Pass2")
send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.")
savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.")
block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private
end
end
if kicktable[user] == true then
return
end
delete_msg(msg.id, ok_cb, false)
kick_user(user, chat)
local username = msg.from.username
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", "")
if msg.to.type == 'chat' or msg.to.type == 'channel' then
if username then
savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "ممنوع التكرار هنا تم طردك😑🔥\n\n معرفك :@"..username.."\n\n الايدي : "..msg.from.id.."")
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "ممنوع التكرار هنا تم طردك😑🔥\n\n معرفك :@"..username.."\n\n الايدي : "..msg.from.id.."")
end
end
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
if msg.from.username ~= nil then
username = msg.from.username
else
username = "---"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
local GBan_log = 'GBan_log'
local GBan_log = data[tostring(GBan_log)]
for k,v in pairs(GBan_log) do
log_SuperGroup = v
gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)"
--send it to log group/channel
send_large_msg(log_SuperGroup, gban_text)
end
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function zooz()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = zooz,
pre_process = pre_process
}
end
| gpl-2.0 |
yimogod/boom | trunk/t-engine4/game/engines/engine/Calendar.lua | 1 | 3072 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2015 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
--- Defines factions
module(..., package.seeall, class.make)
seconds_per_turn = 10
MINUTE = 60 / seconds_per_turn
HOUR = MINUTE * 60
DAY = HOUR * 24
YEAR = DAY * 365
DAY_START = HOUR * 6
--- Create a calendar
-- @param definition the file to load that returns a table containing calendar months
-- @param datestring a string to format the date when requested, in the format "%s %s %s %d %d", standing for, day, month, year, hour, minute
function _M:init(definition, datestring, start_year, start_day, start_hour)
local data = dofile(definition)
self.calendar = {}
local days = 0
for _, e in ipairs(data) do
if not e[3] then e[3] = 0 end
table.insert(self.calendar, { days=days, name=e[2], length=e[1], offset=e[3] })
days = days + e[1]
end
assert(days == 365, "Calendar incomplete, days ends at "..days.." instead of 365")
self.datestring = datestring
self.start_year = start_year
self.start_day = start_day or 1
self.start_hour = start_hour or 8
end
function _M:getTimeDate(turn, dstr)
local doy, year = self:getDayOfYear(turn)
local hour, min = self:getTimeOfDay(turn)
return (dstr or self.datestring):format(tostring(self:getDayOfMonth(doy)):ordinal(), self:getMonthName(doy), tostring(year):ordinal(), hour, min)
end
function _M:getDayOfYear(turn)
local d, y
turn = turn + self.start_hour * self.HOUR
d = math.floor(turn / self.DAY) + (self.start_day - 1)
y = math.floor(d / 365)
d = math.floor(d % 365)
return d, self.start_year + y
end
function _M:getTimeOfDay(turn)
local hour, min
turn = turn + self.start_hour * self.HOUR
min = math.floor((turn % self.DAY) / self.MINUTE)
hour = math.floor(min / 60)
min = math.floor(min % 60)
return hour, min
end
function _M:getMonthNum(dayofyear)
local i = #self.calendar
-- Find the period name
while ((i > 1) and (dayofyear < self.calendar[i].days)) do
i = i - 1
end
return i
end
function _M:getMonthName(dayofyear)
local month = self:getMonthNum(dayofyear)
return self.calendar[month].name
end
function _M:getDayOfMonth(dayofyear)
local month = self:getMonthNum(dayofyear)
return dayofyear - self.calendar[month].days + 1 + self.calendar[month].offset
end
function _M:getMonthLength(dayofyear)
local month = self:getMonthNum(dayofyear)
return self.calendar[month].length
end
| apache-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/endor/masterful_jinda_warrior.lua | 2 | 1236 | masterful_jinda_warrior = Creature:new {
objectName = "@mob/creature_names:masterful_jinda_warrior",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "jinda_tribe",
faction = "",
level = 42,
chanceHit = 0.44,
damageMin = 365,
damageMax = 440,
baseXp = 4188,
baseHAM = 8900,
baseHAMmax = 10900,
armor = 1,
resists = {40,40,30,30,30,30,30,30,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {
"object/mobile/jinda_male.iff",
"object/mobile/jinda_female.iff",
"object/mobile/jinda_male_01.iff",
"object/mobile/jinda_female_01.iff"},
lootGroups = {
{
groups = {
{group = "ewok", chance = 8100000},
{group = "wearables_uncommon", chance = 1000000},
{group = "armor_attachments", chance = 450000},
{group = "clothing_attachments", chance = 450000}
},
lootChance = 1840000
}
},
weapons = {"ewok_weapons"},
conversationTemplate = "",
attacks = merge(riflemanmaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(masterful_jinda_warrior, "masterful_jinda_warrior")
| agpl-3.0 |
Inquiryel/HPW_Rewrite-SBS | lua/hpwrewrite/misc/fakebsod.lua | 2 | 1910 | if SERVER then return end
local text = [[
A problem has been detected and windows has been shut down to prevent damage
to your computer
The problem seems to be caused by the following file: hl2.exe
GMOD_LUA_PANIC
If this is the first time you've seen this stop error screen,
restart your computer. If this screen appears again, follow
these steps:
Check to make sure any new hardware or software is properly installed.
If this is a new installation, ask your hardware or software manufacturer
for any Windows updates you might need.
If problems continue, disable or remove any newly installed hardware
or software. Disable BIOS memory options such as caching or shadowing.
If you need to use safe mode to remove or disable components, restart
your computer, press F8 to select Advanced Startup Options, and then
select Safe Mode.
Technical Information:
*** STOP: 0x00000539
*** hl2.exe - Address 0x474D4F44 base at 0x474D4F44 DateStamp 0x00000000
]]
local arr = string.Explode("\n", text)
local blue = Color(0, 0, 130)
local white = Color(255, 255, 255)
surface.CreateFont("HPW_BSOD", { font = "Lucida Console", size = 16, weight = 1 })
local function EndBsod()
hook.Remove("DrawOverlay", "hpwrewrite_fakebsod")
hook.Remove("Think", "hpwrewrite_fakebsod")
surface.PlaySound("vo/ravenholm/madlaugh04.wav")
end
local function CallBsod()
if not system.IsWindows() then return end -- yes
hook.Add("DrawOverlay", "hpwrewrite_fakebsod", function()
draw.RoundedBox(0, 0, 0, ScrW(), ScrH(), blue)
for k, v in pairs(arr) do
draw.SimpleText(v, "HPW_BSOD", 0, k*18, white)
end
end)
hook.Add("Think", "hpwrewrite_fakebsod", function() RunConsoleCommand("stopsound") end)
timer.Create("hpwrewrite_fakebsodstop", 5, 1, function()
EndBsod()
end)
end
net.Receive("hpwrewrite_BSODFAKESTART", function()
CallBsod()
end)
net.Receive("hpwrewrite_BSODFAKESTOP", function()
EndBsod()
end) | mit |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/saberSlash2.lua | 1 | 2886 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
SaberSlash2Command = {
name = "saberslash2",
damageMultiplier = 2.5,
speedMultiplier = 2.0,
forceCostMultiplier = 2.0,
dotEffects = {
DotEffect(
BLEEDING,
{ "resistance_bleeding", "bleed_resist" },
HEALTH,
true,
100,
100,
75,
60
),
DotEffect(
BLEEDING,
{ "resistance_bleeding", "bleed_resist" },
ACTION,
true,
100,
100,
75,
60
),
DotEffect(
BLEEDING,
{ "resistance_bleeding", "bleed_resist" },
MIND,
true,
100,
100,
75,
60
),
},
stateEffects = {
StateEffect(
POSTUREDOWN_EFFECT,
{ "postureDownRecovery" },
{ "posture_change_down_defense" },
{},
100,
0,
0
)
},
combatSpam = "saberslash2",
poolsToDamage = RANDOM_ATTRIBUTE,
weaponType = JEDIWEAPON,
range = -1
}
AddCommand(SaberSlash2Command)
| agpl-3.0 |
Blizzard/premake-core | modules/vstudio/tests/vc200x/test_resource_compiler.lua | 16 | 1315 | --
-- tests/actions/vstudio/vc200x/test_resource_compiler.lua
-- Validate generation the VCResourceCompilerTool element in Visual Studio 200x C/C++ projects.
-- Copyright (c) 2012-2013 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("vs200x_resource_compiler")
local vc200x = p.vstudio.vc200x
--
-- Setup/teardown
--
local wks, prj
function suite.setup()
p.action.set("vs2008")
wks, prj = test.createWorkspace()
end
local function prepare()
local cfg = test.getconfig(prj, "Debug")
vc200x.VCResourceCompilerTool(cfg)
end
--
-- Verify the basic structure of the compiler block with no flags or settings.
--
function suite.looksGood_onDefaultSettings()
prepare()
test.capture [[
<Tool
Name="VCResourceCompilerTool"
/>
]]
end
--
-- Both includedirs and resincludedirs should be used.
--
function suite.usesBothIncludeAndResIncludeDirs()
includedirs { "../include" }
resincludedirs { "../res/include" }
prepare()
test.capture [[
<Tool
Name="VCResourceCompilerTool"
AdditionalIncludeDirectories="..\include;..\res\include"
/>
]]
end
--
-- Test locale conversion to culture codes.
--
function suite.culture_en_NZ()
locale "en-NZ"
prepare()
test.capture [[
<Tool
Name="VCResourceCompilerTool"
Culture="5129"
/>
]]
end
| bsd-3-clause |
mafiesto4/Game1 | MyGame/MyGame/cocos2d/plugin/luabindings/auto/api/AgentManager.lua | 146 | 1798 |
--------------------------------
-- @module AgentManager
-- @parent_module plugin
--------------------------------
--
-- @function [parent=#AgentManager] getSocialPlugin
-- @param self
-- @return plugin::ProtocolSocial#plugin::ProtocolSocial ret (return value: cc.plugin::ProtocolSocial)
--------------------------------
--
-- @function [parent=#AgentManager] getAdsPlugin
-- @param self
-- @return plugin::ProtocolAds#plugin::ProtocolAds ret (return value: cc.plugin::ProtocolAds)
--------------------------------
--
-- @function [parent=#AgentManager] purge
-- @param self
--------------------------------
--
-- @function [parent=#AgentManager] getUserPlugin
-- @param self
-- @return plugin::ProtocolUser#plugin::ProtocolUser ret (return value: cc.plugin::ProtocolUser)
--------------------------------
--
-- @function [parent=#AgentManager] getIAPPlugin
-- @param self
-- @return plugin::ProtocolIAP#plugin::ProtocolIAP ret (return value: cc.plugin::ProtocolIAP)
--------------------------------
--
-- @function [parent=#AgentManager] getSharePlugin
-- @param self
-- @return plugin::ProtocolShare#plugin::ProtocolShare ret (return value: cc.plugin::ProtocolShare)
--------------------------------
--
-- @function [parent=#AgentManager] getAnalyticsPlugin
-- @param self
-- @return plugin::ProtocolAnalytics#plugin::ProtocolAnalytics ret (return value: cc.plugin::ProtocolAnalytics)
--------------------------------
--
-- @function [parent=#AgentManager] destroyInstance
-- @param self
--------------------------------
--
-- @function [parent=#AgentManager] getInstance
-- @param self
-- @return plugin::AgentManager#plugin::AgentManager ret (return value: cc.plugin::AgentManager)
return nil
| gpl-2.0 |
shitz/InterruptCoordinator | libs/GeminiLogging.lua | 1 | 4627 | -------------------------------------------------------------------------------
-- GeminiLogging
-- Copyright (c) NCsoft. All rights reserved
-- Author: draftomatic
-- Logging library (loosely) based on LuaLogging.
-- Comes with appenders for GeminiConsole and Print() Debug Channel.
-------------------------------------------------------------------------------
local inspect
local GeminiLogging = {}
function GeminiLogging:OnLoad()
inspect = Apollo.GetPackage("Drafto:Lib:inspect-1.2").tPackage
self.console = Apollo.GetAddon("GeminiConsole")
-- The GeminiLogging.DEBUG Level designates fine-grained informational events that are most useful to debug an application
self.DEBUG = "DEBUG"
-- The GeminiLogging.INFO level designates informational messages that highlight the progress of the application at coarse-grained level
self.INFO = "INFO"
-- The WARN level designates potentially harmful situations
self.WARN = "WARN"
-- The ERROR level designates error events that might still allow the application to continue running
self.ERROR = "ERROR"
-- The FATAL level designates very severe error events that will presumably lead the application to abort
self.FATAL = "FATAL"
-- Data structures for levels
self.LEVEL = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
self.MAX_LEVELS = #self.LEVEL
-- Enumerate levels
for i=1,self.MAX_LEVELS do
self.LEVEL[self.LEVEL[i]] = i
end
end
function GeminiLogging:OnDependencyError(strDep, strError)
if strDep == "GeminiConsole" then return true end
Print("GeminiLogging couldn't load " .. strDep .. ". Fatal error: " .. strError)
return false
end
-- Factory method for loggers
function GeminiLogging:GetLogger(opt)
-- Default options
if not opt then
opt = {
level = self.INFO,
pattern = "%d %n %c %l - %m",
appender = "GeminiConsole"
}
end
-- Initialize logger object
local logger = {}
-- Set appender
if type(opt.appender) == "string" then
logger.append = self:GetAppender(opt.appender)
if not logger.append then
Print("Invalid appender")
return nil
end
elseif type(opt.appender) == "function" then
logger.append = opt.appender
else
Print("Invalid appender")
return nil
end
-- Set pattern
logger.pattern = opt.pattern
-- Set level
logger.level = opt.level
local order = self.LEVEL[logger.level]
-- Set logger functions (debug, info, etc.) based on level option
for i=1,self.MAX_LEVELS do
local upperName = self.LEVEL[i]
local name = upperName:lower()
if i >= order then
logger[name] = function(self, message, opt)
local debugInfo = debug.getinfo(2) -- Get debug info for caller of log function
--Print(inspect(debug.getinfo(3)))
--local caller = debugInfo.name or ""
local dir, file, ext = string.match(debugInfo.short_src, "(.-)([^\\]-([^%.]+))$")
local caller = file or ""
caller = string.gsub(caller, "." .. ext, "")
local line = debugInfo.currentline or "-"
logger:append(GeminiLogging.PrepareLogMessage(logger, message, upperName, caller, line)) -- Give the appender the level string
end
else
logger[name] = function() end -- noop if level is too high
end
end
return logger
end
function GeminiLogging:PrepareLogMessage(message, level, caller, line)
if type(message) ~= "string" then
if type(message) == "userdata" then
message = inspect(getmetatable(message))
else
message = inspect(message)
end
end
local logMsg = self.pattern
message = string.gsub(message, "%%", "%%%%")
logMsg = string.gsub(logMsg, "%%d", os.date("%I:%M:%S%p")) -- only time, in 12-hour AM/PM format. This could be configurable...
logMsg = string.gsub(logMsg, "%%l", level)
logMsg = string.gsub(logMsg, "%%c", caller)
logMsg = string.gsub(logMsg, "%%n", line)
logMsg = string.gsub(logMsg, "%%m", message)
return logMsg
end
-------------------------------------------------------------------------------
-- Default Appenders
-------------------------------------------------------------------------------
--[[local tLevelColors = {
DEBUG = "FF4DDEFF",
INFO = "FF52FF4D",
WARN = "FFFFF04D",
ERROR = "FFFFA04D",
FATAL = "FFFF4D4D"
}--]]
function GeminiLogging:GetAppender(name)
if nTimeStart == nil then nTimeStart = os.time() end
if name == "GeminiConsole" then
return function(self, message, level)
if GeminiLogging.console ~= nil then
GeminiLogging.console:Append(message)
else
Print(message)
end
end
else
return function(self, message, level)
Print(message)
end
end
return nil
end
Apollo.RegisterPackage(GeminiLogging, "Gemini:Logging-1.2", 1, {"Drafto:Lib:inspect-1.2", "GeminiConsole"})
| apache-2.0 |
szczukot/domoticz | dzVents/runtime/tests/testVariable.lua | 10 | 4896 | local _ = require 'lodash'
local scriptPath = ''
package.path = package.path .. ";../?.lua;" .. scriptPath .. '/?.lua'
local testData = require('tstData')
local LOG_INFO = 2
local LOG_DEBUG = 3
local LOG_ERROR = 1
local xVar = 11
local yVar = 12
local zVar = 13
local aVar = 14
local bVar = 15
local cVar = 17
local spacedVar = 16
describe('variables', function()
local Variable
local commandArray = {}
local domoticz = {
settings = { ['Domoticz url'] = 'url' },
sendCommand = function(command, value)
table.insert(commandArray, { [command] = value })
return commandArray[#commandArray], command, value
end,
}
setup(function()
_G.logLevel = 1
_G.domoticzData = testData.domoticzData
_G.globalvariables = {
Security = 'sec',
['script_path'] = scriptPath,
['currentTime'] = '2017-08-17 12:13:14.123'
}
TimedCommand = require('TimedCommand')
commandArray = {}
Variable = require('Variable')
end)
before_each(function()
commandArray = {}
end)
teardown(function()
Variable = nil
end)
it('should instantiate', function()
local var = Variable(domoticz, testData.domoticzData[xVar])
assert.is_not_nil(var)
assert.is_false(var.isHTTPResponse)
assert.is_true(var.isVariable)
assert.is_false(var.isTimer)
assert.is_false(var.isScene)
assert.is_false(var.isDevice)
assert.is_false(var.isGroup)
assert.is_false(var.isSecurity)
end)
it('should have properties', function()
local var = Variable(domoticz, testData.domoticzData[yVar])
assert.is_same(2.3, var.nValue)
assert.is_same(2.3, var.value)
assert.is_same('2017-04-18 20:16:23', var.lastUpdate.raw)
assert.is_same('y', var.name)
end)
it('should have cast to number', function()
local var = Variable(domoticz, testData.domoticzData[yVar])
assert.is_same('number', type(var.nValue))
end)
it('should set a new float value', function()
local var = Variable(domoticz, testData.domoticzData[yVar])
var.set(12.5)
assert.is_same(1, _.size(commandArray))
assert.is_same({ ['Variable'] = { idx = 2, value='12.5', _trigger=true } }, commandArray[1])
end)
it('should set a new integer value', function()
local var = Variable(domoticz, testData.domoticzData[xVar])
var.set(12)
assert.is_same(1, _.size(commandArray))
assert.is_same({ ['Variable'] = { idx = 1, value='12', _trigger=true } }, commandArray[1])
end)
it('should set a new string value', function()
local var = Variable(domoticz, testData.domoticzData[zVar])
var.set('dzVents')
assert.is_same(1, _.size(commandArray))
assert.is_same({ ['Variable'] = { idx = 3, value='dzVents', _trigger=true } }, commandArray[1])
end)
it('should set a new date value', function()
local var = Variable(domoticz, testData.domoticzData[aVar])
var.set('12/12/2012')
assert.is_same(1, _.size(commandArray))
assert.is_same({ ['Variable'] = { idx = 4, value='12/12/2012', _trigger=true } }, commandArray[1])
end)
it('should set a new time value', function()
local var = Variable(domoticz, testData.domoticzData[bVar])
var.set('12:34')
assert.is_same(1, _.size(commandArray))
assert.is_same({ ['Variable'] = { idx = 5, value='12:34', _trigger=true } }, commandArray[1])
end)
it('should not fail when trying to cast a string', function()
local var = Variable(domoticz, testData.domoticzData[zVar])
assert.is_nil(var.nValue)
assert.is_same('some value', var.value)
end)
it('should have different types', function()
local var = Variable(domoticz, testData.domoticzData[zVar])
assert.is_same('string', var.type)
assert.is_same('string', type(var.value))
end)
it('should have a date type (/)', function()
local var = Variable(domoticz, testData.domoticzData[aVar])
assert.is_same('date', var.type)
assert.is_same(2017, var.date.year)
assert.is_same(3, var.date.day)
assert.is_same(12, var.date.month)
end)
it('should have a date type (-)', function()
local var = Variable(domoticz, testData.domoticzData[cVar])
assert.is_same('date', var.type)
assert.is_same(2017, var.date.year)
assert.is_same(3, var.date.day)
assert.is_same(12, var.date.month)
end)
it('should have a time type', function()
local var = Variable(domoticz, testData.domoticzData[bVar])
assert.is_same('time', var.type)
assert.is_same(19, var.time.hour)
assert.is_same(34, var.time.min)
end)
it('should set a make a timed command', function()
local var = Variable(domoticz, testData.domoticzData[zVar])
var.set('dzVents').afterSec(5)
assert.is_same(1, _.size(commandArray))
assert.is_same({ ['Variable'] = { idx = 3, value='dzVents', _trigger = true, _after = 5 } }, commandArray[1])
end)
it('should have a cancelQueuedCommands method', function()
local var = Variable(domoticz, testData.domoticzData[zVar])
var.cancelQueuedCommands()
assert.is_same({
{ ['Cancel'] = { type = 'variable', idx = 3 } }
}, commandArray)
end)
end)
| gpl-3.0 |
bellinat0r/Epiar | Resources/Scripts/ai.lua | 2 | 17315 | -- This script defines the AI State Machines
--[[
An AI StateMachine must have the form:
StateMachine = {
State = function(id,x,y,angle,speed,vector) ... end,
...
}
All StateMachines must have a "default" state. This is their initial state.
States transition by returning a string of the new State's name.
States that do not return new state names will stay in the same state.
--]]
AIData = {}
function FindADestination(id,x,y,angle,speed,vector)
-- Choose a planet
local cur_ship = Epiar.getSprite(id)
if AIData[id].destinationName ~= nil and AIData[id].alwaysGateTravel == true then
return GateTraveler.ComputingRoute(id,x,y,angle,speed,vector)
end
local planetNames = Epiar.planetNames()
local destination = Planet.Get(planetNames[ math.random(#planetNames) ])
AIData[id].destination = destination:GetID()
AIData[id].destinationName = destination:GetName()
return "Travelling"
end
function okayTarget(cur_ship, ship)
-- if friendly (merciful) mode is on and the nearest target is the player, forbid this target
if PLAYER ~= nil and PLAYER:GetID() == ship:GetID() then
if cur_ship:GetMerciful() == 1 then
-- The PLAYER has been spared... For now...
return false
end
if PLAYER:GetFavor( cur_ship:GetAlliance() ) > 500 then
-- The PLAYER is a god to their people!
return false
end
end
if Fleets:fleetmates( cur_ship:GetID(), ship:GetID() ) then
return false
end
if AIData[ship:GetID()] ~= nil then
-- If the ship in question is accompanying either this ship or whichever one we are
-- accompanying, don't attack it.
if AIData[ship:GetID()].accompany == cur_ship:GetID() or
AIData[ship:GetID()].accompany == AIData[cur_ship:GetID()].accompany then
return false
end
end
return true
end
function setAccompany(id, accid)
if AIData[id] == nil then
AIData[id] = { }
end
if Epiar.getSprite(accid) ~= nil then
AIData[id].accompany = accid
else
AIData[id].accompany = -1
end
end
function setHuntHostile(id, tid)
if AIData[id] == nil then
AIData[id] = { }
end
local cur_ship = Epiar.getSprite(id)
local target_ship = Epiar.getSprite(tid)
if cur_ship ~= nil and target_ship ~= nil and okayTarget(cur_ship, target_ship) then
AIData[id].target = tid
AIData[id].hostile = 1
AIData[id].foundTarget = 0
end
end
-- Gate Traveler AI to be used by others
GateTraveler = {
default = function(id,x,y,angle,speed,vector)
print "WARNING: GateTraveler default state was invoked. This should not happen."
local cur_ship = Epiar.getSprite(id)
cur_ship:Explode()
return "default"
end,
ComputingRoute = function(id,x,y,angle,speed,vector)
if AIData[id].Autopilot == nil then
AIData[id].Autopilot = APInit( "AI", id )
end
if AIData[id].Autopilot.spcr == nil then
AIData[id].Autopilot:compute( AIData[id].destinationName )
else
local finished = AIData[id].Autopilot.spcrTick()
if finished then
return "GateTravelling"
else
return "ComputingRoute"
end
end
end,
GateTravelling = function(id,x,y,angle,speed,vector)
local cur_ship = Epiar.getSprite(id)
if AIData[id].Autopilot == nil then
return "default"
end
if AIData[id].Autopilot.AllowAccel ~= false then
cur_ship:Accelerate()
end
local enroute = AIData[id].Autopilot:autoAngle()
if enroute then return "GateTravelling" end
AIData[id].destination = -1
AIData[id].destinationName = nil
return "Travelling" -- Once the autopilot finishes up, revert back to standard Travelling state
end
}
--- Hunter AI
Hunter = {
default = function(id,x,y,angle,speed,vector)
if AIData[id] == nil then
AIData[id] = { }
end
if AIData[id].foundTarget == 1 then
AIData[id].hostile = 0
AIData[id].foundTarget = 0
end
return "New_Planet"
end,
New_Planet = FindADestination,
Hunting = function(id,x,y,angle,speed,vector)
-- Approach the target
local cur_ship = Epiar.getSprite(id)
local tx,ty,dist
local target = Epiar.getSprite( AIData[id].target )
if target~=nil then
tx,ty = target:GetPosition()
dist = distfrom(tx,ty,x,y)
else
AIData[id].hostile = 0
return "default"
end
cur_ship:Rotate( cur_ship:directionTowards(tx,ty) )
if math.abs(cur_ship:directionTowards(tx,ty)) == 0 then
cur_ship:Accelerate()
end
if dist<400 then
return "Killing"
end
if dist>1000 and AIData[id].hostile == 0 then
return "default"
end
return "Hunting"
end,
Killing = function(id,x,y,angle,speed,vector)
-- Attack the target
local cur_ship = Epiar.getSprite(id)
local tx,ty,dist
local target = Epiar.getSprite( AIData[id].target )
if target==nil or target:GetHull()==0 then
--The AI has destroyed the enemy.
--HUD.newAlert(string.format("%s #%d:Victory is Mine!",cur_ship:GetModelName(),id))
return "default"
else
tx,ty = target:GetPosition()
dist = distfrom(tx,ty,x,y)
end
if AIData[id].hostile == 1 and AIData[id].foundTarget == 0 then
AIData[id].foundTarget = 1
local machine, state = cur_ship:GetState()
--HUD.newAlert(string.format("%s %s: Die, %s!", machine, cur_ship:GetModelName(), target:GetName()))
end
cur_ship:Rotate( cur_ship:directionTowards(tx,ty) )
local fireResult = cur_ship:FirePrimary( AIData[id].target )
-- if this firing group isn't doing anything, switch
if fireResult == 3 or fireResult == 4 then -- FireNoAmmo or FireEmptyGroup
cur_ship:FireSecondary()
end
if dist>200 then
if cur_ship:directionTowards(tx,ty) == 0 then
cur_ship:Accelerate()
end
end
if dist>300 then
return "Hunting"
end
end,
ComputingRoute = GateTraveler.ComputingRoute,
GateTravelling = GateTraveler.GateTravelling,
Travelling = function(id,x,y,angle,speed,vector)
-- Find a new target
local cur_ship = Epiar.getSprite(id)
local closeShip= Epiar.nearestShip(cur_ship,1000)
local targetShip= nil
if AIData[id].target ~= nil then targetShip = Epiar.getSprite(AIData[id].target) end
if targetShip~=nil and okayTarget(cur_ship, targetShip) and AIData[id].hostile == 1 then
return "Hunting"
elseif closeShip~=nil and okayTarget(cur_ship, closeShip) then
AIData[id].hostile = 0
AIData[id].target = closeShip:GetID()
return "Hunting"
end
--print (string.format ("%s %s not hunting anything target %d\n", cur_ship:GetState(), AIData[id].target))
AIData[id].hostile = 0
local p = Epiar.getSprite( AIData[id].destination )
local px,py = p:GetPosition()
cur_ship:Rotate( cur_ship:directionTowards(px,py) )
cur_ship:Accelerate()
if distfrom(px,py,x,y) < 800 then
return "New_Planet"
end
end,
}
--- Trader AI
Trader = {
Hunting = Hunter.Hunting,
Killing = Hunter.Killing,
Docking = function(id,x,y,angle,speed,vector)
if AIData[id].hostile == 1 then return "Hunting" end
-- Stop on this planet
local cur_ship = Epiar.getSprite(id)
local p = Epiar.getSprite( AIData[id].destination )
local px,py = p:GetPosition()
local dist = distfrom(px,py,x,y)
if speed > 0.5 then
cur_ship:Rotate( - cur_ship:directionTowards( cur_ship:GetMomentumAngle() ) )
if dist>100 and math.abs(180 - math.abs(cur_ship:GetMomentumAngle() - cur_ship:GetAngle())) <= 10 then
cur_ship:Accelerate()
end
end
-- If we drift away, then find a new planet
if dist > 800 then
return "New_Planet"
end
end,
ComputingRoute = GateTraveler.ComputingRoute,
GateTravelling = GateTraveler.GateTravelling,
Travelling = function(id,x,y,angle,speed,vector)
if AIData[id].hostile == 1 then return "Hunting" end
-- Get to the planet
local cur_ship = Epiar.getSprite(id)
local p = Epiar.getSprite( AIData[id].destination )
if p == nil then return "New_Planet" end
local px,py = p:GetPosition()
cur_ship:Rotate( cur_ship:directionTowards(px,py) )
cur_ship:Accelerate()
if distfrom(px,py,x,y) < 800 then
return "New_Planet"
end
end,
New_Planet = FindADestination,
default = function(id,x,y,angle,speed,vector,state)
if AIData[id] == nil then AIData[id] = { } end
local cur_ship = Epiar.getSprite(id)
local traderNames = { "S.S. Epiar", "S.S. Honorable", "S.S. Marvelous", "S.S. Delight",
"S.S. Honeycomb", "S.S. Woodpecker", "S.S. Crow", "S.S. Condor",
"S.S. Windowpane", "S.S. Marketplace", "S.S. Baker", "S.S. Momentous",
"S.S. Robinson", "S.S. Andersonville", "S.S. Ash", "S.S. Maple",
"S.S. Mangrove", "S.S. Cheetah", "S.S. Apricot", "S.S Amicable",
"S.S. Schumacher", "S.S. Bluebird", "S.S. Bluejay", "S.S. Hummingbird",
"S.S. Nightcap", "S.S. Starsplash", "S.S. Starrunner", "S.S. Starfinder" }
cur_ship:SetName(traderNames[math.random(#traderNames)])
return "New_Planet"
end,
}
Patrol = {
default = function(id,x,y,angle,speed,vector)
local cur_ship = Epiar.getSprite(id)
AIData[id] = {}
destination = Epiar.nearestPlanet(cur_ship,4096)
if destination==nil then
return "New_Planet"
end
AIData[id].destination = destination:GetID()
return "Travelling"
end,
New_Planet = FindADestination,
Hunting = Hunter.Hunting,
Killing = Hunter.Killing,
ComputingRoute = GateTraveler.ComputingRoute,
GateTravelling = GateTraveler.GateTravelling,
Travelling = function(id,x,y,angle,speed,vector)
if AIData[id].hostile == 1 then return "Hunting" end
local cur_ship = Epiar.getSprite(id)
local p = Epiar.getSprite( AIData[id].destination )
if p == nil then return "default" end
local px,py = p:GetPosition()
cur_ship:Rotate( cur_ship:directionTowards(px,py) )
cur_ship:Accelerate()
if distfrom(px,py,x,y) < 1000 then
return "Orbiting"
end
end,
Orbiting = function(id,x,y,angle,speed,vector)
if AIData[id].hostile == 1 then return "Hunting" end
local cur_ship = Epiar.getSprite(id)
local p = Epiar.getSprite( AIData[id].destination )
local px,py = p:GetPosition()
local dist = distfrom(px,py,x,y)
cur_ship:Accelerate()
cur_ship:Rotate( cur_ship:directionTowards(px,py) +90)
if dist > 1500 then
return "TooFar"
end
if dist < 500 then
return "TooClose"
end
local ship= Epiar.nearestShip(cur_ship,1000)
if ship~=nil and okayTarget(cur_ship, ship) then
local machine, state = ship:GetState()
-- Kill all Agressive Hunters and Pirates
if machine=="Hunter" or machine=="Pirate" then
AIData[id].target = ship:GetID()
return "Hunting"
elseif machine=="Escort" then
-- If the Escort's leader is a Hunter or Pirate, kill the Escort
local leader = Epiar.getSprite(AIData[ ship:GetID() ].accompany)
local machine, state = leader:GetState()
if machine=="Hunter" or machine=="Pirate" then
AIData[id].target = ship:GetID()
return "Hunting"
end
end
end
end,
TooClose = function(id,x,y,angle,speed,vector)
if AIData[id].hostile == 1 then return "Hunting" end
local cur_ship = Epiar.getSprite(id)
local p = Epiar.getSprite( AIData[id].destination )
local px,py = p:GetPosition()
cur_ship:Rotate( - cur_ship:directionTowards(px,py) )
cur_ship:Accelerate()
if distfrom(px,py,x,y) > 800 then
return "Orbiting"
end
end,
TooFar = function(id,x,y,angle,speed,vector)
if AIData[id].hostile == 1 then return "Hunting" end
local cur_ship = Epiar.getSprite(id)
local p = Epiar.getSprite( AIData[id].destination )
local px,py = p:GetPosition()
cur_ship:Rotate( cur_ship:directionTowards(px,py) )
cur_ship:Accelerate()
if distfrom(px,py,x,y) < 1300 then
return "Orbiting"
end
end,
}
Bully = {
default = Patrol.default,
New_Planet = FindADestination,
ComputingRoute = GateTraveler.ComputingRoute,
GateTravelling = GateTraveler.GateTravelling,
Travelling = Patrol.Travelling,
TooClose = Patrol.TooClose,
TooFar = Patrol.TooFar,
Hunting = Hunter.Hunting,
Killing = Hunter.Killing,
Orbiting = function(id,x,y,angle,speed,vector)
if AIData[id].hostile == 1 then return "Hunting" end
local cur_ship = Epiar.getSprite(id)
local p = Epiar.getSprite( AIData[id].destination )
local px,py = p:GetPosition()
local dist = distfrom(px,py,x,y)
local ship= Epiar.nearestShip(cur_ship,900)
if (ship~=nil) and (ship:GetID() ~= id) and (ship:GetHull() <= 0.9) and (okayTarget(cur_ship, ship)) then
AIData[id].target = ship:GetID()
return "Hunting"
end
if dist > 1500 then
return "TooFar"
end
if dist < 500 then
return "TooClose"
end
cur_ship:Rotate( cur_ship:directionTowards(px,py) +90)
cur_ship:Accelerate()
end,
}
Pirate = Hunter
Escort = {
default = function(id,x,y,angle,speed,vector)
if AIData[id] == nil then
AIData[id] = { }
AIData[id].accompany = -1
end
AIData[id].target = -1
local cur_ship = Epiar.getSprite(id)
if AIData[id].initFor ~= nil then
-- -1 in the pay field means "don't check / don't alter"
Epiar.getSprite(AIData[id].initFor):AddHiredEscort(cur_ship:GetModelName(), -1, id)
end
-- Create some variation in how escort pilots behave
local mass = Epiar.getSprite(id):GetMass()
AIData[id].farThreshold = 225 * mass + math.random(50)
AIData[id].nearThreshold = 100 * mass + math.random(40)
local myFleet = Fleets:getShipFleet(id)
if myFleet ~= nil then setAccompany(id, myFleet:getLeader() ) end
if AIData[id].accompany >= 0 then return "Accompanying" end
return "New_Planet"
end,
ComputingRoute = GateTraveler.ComputingRoute,
GateTravelling = GateTraveler.GateTravelling,
Travelling = function(id,x,y,angle,speed,vector)
if AIData[id].accompany > -1 then return "Accompanying" end
return Patrol.Travelling(id,x,y,angle,speed,vector)
end,
New_Planet = FindADestination,
Orbiting = function(id,x,y,angle,speed,vector)
if AIData[id].accompany > -1 then return "Accompanying" end
return Patrol.Orbiting(id,x,y,angle,speed,vector)
end,
TooClose = function(id,x,y,angle,speed,vector)
if AIData[id].accompany > -1 then return "Accompanying" end
return Patrol.TooClose(id,x,y,angle,speed,vector)
end,
TooFar = function(id,x,y,angle,speed,vector)
if AIData[id].accompany > -1 then return "Accompanying" end
return Patrol.TooFar(id,x,y,angle,speed,vector)
end,
Hunting = function(id,x,y,angle,speed,vector)
local myFleet = Fleets:getShipFleet(id)
if myFleet ~= nil then
local prox = myFleet:fleetmateProx(id)
if prox ~= nil and prox < 45 then return "NewPattern" end
end
return Hunter.Hunting(id,x,y,angle,speed,vector)
end,
Killing = function(id,x,y,angle,speed,vector)
local myFleet = Fleets:getShipFleet(id)
if myFleet ~= nil then
local prox = myFleet:fleetmateProx(id)
if prox ~= nil and prox < 45 then return "NewPattern" end
end
return Hunter.Killing(id,x,y,angle,speed,vector)
end,
NewPattern = function(id,x,y,angle,speed,vector)
local cur_ship = Epiar.getSprite(id)
local momentumAngle = cur_ship:GetMomentumAngle()
if AIData[id].correctAgainst == nil then
AIData[id].correctAgainst = momentumAngle
AIData[id].correctOffset = math.random(-90,90)
end
cur_ship:Rotate( cur_ship:directionTowards( AIData[id].correctAgainst + AIData[id].correctOffset ) )
cur_ship:Accelerate()
if cur_ship:directionTowards( AIData[id].correctAgainst + AIData[id].correctOffset ) == 0 then
AIData[id].correctAgainst = nil
AIData[id].correctOffset = nil
return "Hunting"
end
end,
HoldingPosition = function(id,x,y,angle,speed,vector)
local ns = AIData[id].nextState
if ns ~= nil then
AIData[id].nextState = nil
return ns
end
local cur_ship = Epiar.getSprite(id)
local inverseMomentumOffset = - cur_ship:directionTowards( cur_ship:GetMomentumAngle() )
cur_ship:Rotate( inverseMomentumOffset )
if math.abs( cur_ship:directionTowards( cur_ship:GetMomentumAngle() ) ) >= 176 and speed > 0.1 then
cur_ship:Accelerate()
end
return "HoldingPosition"
end,
Accompanying = function(id,x,y,angle,speed,vector)
local cur_ship = Epiar.getSprite(id)
local acc = AIData[id].accompany
local accompanySprite
if acc > -1 then
accompanySprite = Epiar.getSprite(AIData[id].accompany)
if AIData[id].hostile == 1 then return "Hunting" end
local ns = AIData[id].nextState
if ns ~= nil then
AIData[id].nextState = nil
return ns
end
else
if AIData[id].destination ~= nil and AIData[id].destination > -1 then
return "Travelling"
else
return "New_Planet"
end
end
local ax = 0
local ay = 0
local distance
if accompanySprite~=nil and accompanySprite:GetHull() > 0 then
ax,ay = accompanySprite:GetPosition()
local aitype, aitask = accompanySprite:GetState()
if aitask == "Hunting" or aitask == "Killing" then
AIData[id].target = AIData[AIData[id].accompany].target
return "Hunting"
end
else
AIData[id].accompany = -1
AIData[id].hostile = -1
return "default"
end
distance = distfrom(ax,ay,x,y)
local accelDir = cur_ship:directionTowards(ax,ay)
local inverseMomentumDir = - cur_ship:directionTowards( cur_ship:GetMomentumAngle() )
if distance > AIData[id].farThreshold then
cur_ship:Rotate( accelDir )
if accelDir == 0 then
cur_ship:Accelerate()
end
else
if distance > AIData[id].nearThreshold then
cur_ship:Rotate( accelDir )
if distance % (math.sqrt(AIData[id].farThreshold - distance) + 1) < 2 and
accelDir == 0 then
cur_ship:Accelerate()
end
else
cur_ship:Rotate( inverseMomentumDir )
--if math.abs(inverseMomentumDir) < 35 then
-- cur_ship:Accelerate()
--end
end
end
return "Accompanying"
end,
}
| gpl-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/drainForce.lua | 2 | 2269 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
DrainForceCommand = {
name = "drainforce",
animationCRC = hashCode("force_drain_1"),
combatSpam = "forcedrain_hit",
poolsToDamage = NONE,
damage = 100, --Force drained
range = 32
}
AddCommand(DrainForceCommand)
| agpl-3.0 |
excessive/obtuse-tanuki | libs/hump/signal.lua | 2 | 2710 | --[[
Copyright (c) 2012-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 Registry = {}
Registry.__index = function(self, key)
return Registry[key] or (function()
local t = {}
rawset(self, key, t)
return t
end)()
end
function Registry:register(s, f)
self[s][f] = f
return f
end
function Registry:emit(s, ...)
for f in pairs(self[s]) do
f(...)
end
end
function Registry:remove(s, ...)
local f = {...}
for i = 1, #f do
self[s][f[i]] = nil
end
end
function Registry:clear(...)
local s = {...}
for i = 1, #s do
self[s[i]] = {}
end
end
function Registry:emit_pattern(p, ...)
for s in pairs(self) do
if s:match(p) then self:emit(s, ...) end
end
end
function Registry:remove_pattern(p, ...)
for s in pairs(self) do
if s:match(p) then self:remove(s, ...) end
end
end
function Registry:clear_pattern(p)
for s in pairs(self) do
if s:match(p) then self[s] = {} end
end
end
local function new()
return setmetatable({}, Registry)
end
local default = new()
return setmetatable({
new = new,
register = function(...) return default:register(...) end,
emit = function(...) default:emit(...) end,
remove = function(...) default:remove(...) end,
clear = function(...) default:clear(...) end,
emit_pattern = function(...) default:emit_pattern(...) end,
remove_pattern = function(...) default:remove_pattern(...) end,
clear_pattern = function(...) default:clear_pattern(...) end,
}, {__call = new})
| mit |
TylerL-uxai/SamsBday | Resources/scripts/out.lua | 6 | 3744 | a = {}
a["bg_day"]={width=288, height=512, x=0, y=0}
a["bg_night"]={width=288, height=512, x=292, y=0}
a["bird0_0"]={width=48, height=48, x=0, y=970}
a["bird0_1"]={width=48, height=48, x=56, y=970}
a["bird0_2"]={width=48, height=48, x=112, y=970}
a["bird1_0"]={width=48, height=48, x=168, y=970}
a["bird1_1"]={width=48, height=48, x=224, y=646}
a["bird1_2"]={width=48, height=48, x=224, y=698}
a["bird2_0"]={width=48, height=48, x=224, y=750}
a["bird2_1"]={width=48, height=48, x=224, y=802}
a["bird2_2"]={width=48, height=48, x=224, y=854}
a["black"]={width=32, height=32, x=584, y=412}
a["blink_00"]={width=10, height=10, x=276, y=682}
a["blink_01"]={width=10, height=10, x=276, y=734}
a["blink_02"]={width=10, height=10, x=276, y=786}
a["brand_copyright"]={width=126, height=14, x=884, y=182}
a["button_menu"]={width=80, height=28, x=924, y=52}
a["button_ok"]={width=80, height=28, x=924, y=84}
a["button_pause"]={width=26, height=28, x=242, y=612}
a["button_play"]={width=116, height=70, x=702, y=234}
a["button_rate"]={width=74, height=48, x=924, y=0}
a["button_resume"]={width=26, height=28, x=668, y=284}
a["button_score"]={width=116, height=70, x=822, y=234}
a["button_share"]={width=80, height=28, x=584, y=284}
a["font_048"]={width=24, height=44, x=992, y=116}
a["font_049"]={width=16, height=44, x=272, y=906}
a["font_050"]={width=24, height=44, x=584, y=316}
a["font_051"]={width=24, height=44, x=612, y=316}
a["font_052"]={width=24, height=44, x=640, y=316}
a["font_053"]={width=24, height=44, x=668, y=316}
a["font_054"]={width=24, height=44, x=584, y=364}
a["font_055"]={width=24, height=44, x=612, y=364}
a["font_056"]={width=24, height=44, x=640, y=364}
a["font_057"]={width=24, height=44, x=668, y=364}
a["land"]={width=336, height=112, x=584, y=0}
a["medals_0"]={width=44, height=44, x=242, y=516}
a["medals_1"]={width=44, height=44, x=242, y=564}
a["medals_2"]={width=44, height=44, x=224, y=906}
a["medals_3"]={width=44, height=44, x=224, y=954}
a["new"]={width=32, height=14, x=224, y=1002}
a["number_context_00"]={width=12, height=14, x=276, y=646}
a["number_context_01"]={width=12, height=14, x=276, y=664}
a["number_context_02"]={width=12, height=14, x=276, y=698}
a["number_context_03"]={width=12, height=14, x=276, y=716}
a["number_context_04"]={width=12, height=14, x=276, y=750}
a["number_context_05"]={width=12, height=14, x=276, y=768}
a["number_context_06"]={width=12, height=14, x=276, y=802}
a["number_context_07"]={width=12, height=14, x=276, y=820}
a["number_context_08"]={width=12, height=14, x=276, y=854}
a["number_context_09"]={width=12, height=14, x=276, y=872}
a["number_context_10"]={width=12, height=14, x=992, y=164}
a["number_score_00"]={width=16, height=20, x=272, y=612}
a["number_score_01"]={width=16, height=20, x=272, y=954}
a["number_score_02"]={width=16, height=20, x=272, y=978}
a["number_score_03"]={width=16, height=20, x=260, y=1002}
a["number_score_04"]={width=16, height=20, x=1002, y=0}
a["number_score_05"]={width=16, height=20, x=1002, y=24}
a["number_score_06"]={width=16, height=20, x=1008, y=52}
a["number_score_07"]={width=16, height=20, x=1008, y=84}
a["number_score_08"]={width=16, height=20, x=584, y=484}
a["number_score_09"]={width=16, height=20, x=620, y=412}
a["pipe2_down"]={width=52, height=320, x=0, y=646}
a["pipe2_up"]={width=52, height=320, x=56, y=646}
a["pipe_down"]={width=52, height=320, x=112, y=646}
a["pipe_up"]={width=52, height=320, x=168, y=646}
a["score_panel"]={width=238, height=126, x=0, y=516}
a["text_game_over"]={width=204, height=54, x=784, y=116}
a["text_ready"]={width=196, height=62, x=584, y=116}
a["title"]={width=178, height=48, x=702, y=182}
a["tutorial"]={width=114, height=98, x=584, y=182}
a["white"]={width=32, height=32, x=584, y=448}
| mit |
amirhoseinkarimi2233/uzzbot | 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 |
liuyang1/dotfiles | awesome34/screen.lua | 1 | 2191 | ---------------------------------------------------------------------------
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008 Julien Danjou
-- @release v3.4.13
---------------------------------------------------------------------------
-- Grab environment we need
local capi =
{
mouse = mouse,
screen = screen,
client = client
}
local util = require("awful.util")
local client = require("awful.client")
--- Screen module for awful
module("awful.screen")
local data = {}
data.padding = {}
--- Give the focus to a screen, and move pointer.
-- @param screen Screen number.
function focus(screen)
if screen > capi.screen.count() then screen = capi.mouse.screen end
local c = client.focus.history.get(screen, 0)
if c then capi.client.focus = c end
-- Move the mouse on the screen
capi.mouse.screen = screen
end
function focus_center(screen)
if screen > capi.screen.count() then screen = capi.mouse.screen end
local c = client.focus.history.get(screen, 0)
if c then capi.client.focus = c end
-- Move the mouse on center of the screen
capi.mouse.screen = screen
local geo = capi.screen[screen].geometry
capi.mouse.coords({x = geo.x + geo.width/2, y = geo.y + geo.height/2})
end
function focus_relative_center(i)
return focus_center(util.cycle(capi.screen.count(), capi.mouse.screen + i))
end
--- Give the focus to a screen, and move pointer, but relative to the current
-- focused screen.
-- @param i Value to add to the current focused screen index. 1 will focus next
-- screen, -1 would focus the previous one.
function focus_relative(i)
return focus(util.cycle(capi.screen.count(), capi.mouse.screen + i))
end
--- Get or set the screen padding.
-- @param screen The screen object to change the padding on
-- @param padding The padding, an table with 'top', 'left', 'right' and/or
-- 'bottom'. Can be nil if you only want to retrieve padding
function padding(screen, padding)
if padding then
data.padding[screen] = padding
screen:emit_signal("padding")
end
return data.padding[screen]
end
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| mit |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/corellia/sharnaff_reckless_ravager.lua | 2 | 1064 | sharnaff_reckless_ravager = Creature:new {
objectName = "@mob/creature_names:sharnaff_reckless_ravager",
socialGroup = "sharnaff",
faction = "",
level = 34,
chanceHit = 0.41,
damageMin = 315,
damageMax = 340,
baseXp = 3460,
baseHAM = 8800,
baseHAMmax = 10800,
armor = 0,
resists = {115,115,20,120,120,120,120,120,-1},
meatType = "meat_carnivore",
meatAmount = 450,
hideType = "hide_scaley",
hideAmount = 300,
boneType = "bone_mammal",
boneAmount = 180,
milk = 0,
tamingChance = 0.05,
ferocity = 8,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = CARNIVORE,
templates = {"object/mobile/sharnaff_hue.iff"},
controlDeviceTemplate = "object/intangible/pet/sharnaff_hue.iff",
lootGroups = {
{
groups = {
{group = "sharnaff_common", chance = 10000000}
},
lootChance = 1680000
}
},
weapons = {},
conversationTemplate = "",
attacks = {
{"dizzyattack",""},
{"knockdownattack",""}
}
}
CreatureTemplates:addCreatureTemplate(sharnaff_reckless_ravager, "sharnaff_reckless_ravager")
| agpl-3.0 |
TylerL-uxai/SamsBday | cocos2d/external/lua/luajit/src/src/jit/bcsave.lua | 78 | 18123 | ----------------------------------------------------------------------------
-- LuaJIT module to save/list bytecode.
--
-- Copyright (C) 2005-2013 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module saves or lists the bytecode for an input file.
-- It's run by the -b command line option.
--
------------------------------------------------------------------------------
local jit = require("jit")
assert(jit.version_num == 20001, "LuaJIT core/library version mismatch")
local bit = require("bit")
-- Symbol name prefix for LuaJIT bytecode.
local LJBC_PREFIX = "luaJIT_BC_"
------------------------------------------------------------------------------
local function usage()
io.stderr:write[[
Save LuaJIT bytecode: luajit -b[options] input output
-l Only list bytecode.
-s Strip debug info (default).
-g Keep debug info.
-n name Set module name (default: auto-detect from input name).
-t type Set output file type (default: auto-detect from output name).
-a arch Override architecture for object files (default: native).
-o os Override OS for object files (default: native).
-e chunk Use chunk string as input.
-- Stop handling options.
- Use stdin as input and/or stdout as output.
File types: c h obj o raw (default)
]]
os.exit(1)
end
local function check(ok, ...)
if ok then return ok, ... end
io.stderr:write("luajit: ", ...)
io.stderr:write("\n")
os.exit(1)
end
local function readfile(input)
if type(input) == "function" then return input end
if input == "-" then input = nil end
return check(loadfile(input))
end
local function savefile(name, mode)
if name == "-" then return io.stdout end
return check(io.open(name, mode))
end
------------------------------------------------------------------------------
local map_type = {
raw = "raw", c = "c", h = "h", o = "obj", obj = "obj",
}
local map_arch = {
x86 = true, x64 = true, arm = true, ppc = true, ppcspe = true,
mips = true, mipsel = true,
}
local map_os = {
linux = true, windows = true, osx = true, freebsd = true, netbsd = true,
openbsd = true, solaris = true,
}
local function checkarg(str, map, err)
str = string.lower(str)
local s = check(map[str], "unknown ", err)
return s == true and str or s
end
local function detecttype(str)
local ext = string.match(string.lower(str), "%.(%a+)$")
return map_type[ext] or "raw"
end
local function checkmodname(str)
check(string.match(str, "^[%w_.%-]+$"), "bad module name")
return string.gsub(str, "[%.%-]", "_")
end
local function detectmodname(str)
if type(str) == "string" then
local tail = string.match(str, "[^/\\]+$")
if tail then str = tail end
local head = string.match(str, "^(.*)%.[^.]*$")
if head then str = head end
str = string.match(str, "^[%w_.%-]+")
else
str = nil
end
check(str, "cannot derive module name, use -n name")
return string.gsub(str, "[%.%-]", "_")
end
------------------------------------------------------------------------------
local function bcsave_tail(fp, output, s)
local ok, err = fp:write(s)
if ok and output ~= "-" then ok, err = fp:close() end
check(ok, "cannot write ", output, ": ", err)
end
local function bcsave_raw(output, s)
local fp = savefile(output, "wb")
bcsave_tail(fp, output, s)
end
local function bcsave_c(ctx, output, s)
local fp = savefile(output, "w")
if ctx.type == "c" then
fp:write(string.format([[
#ifdef _cplusplus
extern "C"
#endif
#ifdef _WIN32
__declspec(dllexport)
#endif
const char %s%s[] = {
]], LJBC_PREFIX, ctx.modname))
else
fp:write(string.format([[
#define %s%s_SIZE %d
static const char %s%s[] = {
]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname))
end
local t, n, m = {}, 0, 0
for i=1,#s do
local b = tostring(string.byte(s, i))
m = m + #b + 1
if m > 78 then
fp:write(table.concat(t, ",", 1, n), ",\n")
n, m = 0, #b + 1
end
n = n + 1
t[n] = b
end
bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n")
end
local function bcsave_elfobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct {
uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7];
uint16_t type, machine;
uint32_t version;
uint32_t entry, phofs, shofs;
uint32_t flags;
uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx;
} ELF32header;
typedef struct {
uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7];
uint16_t type, machine;
uint32_t version;
uint64_t entry, phofs, shofs;
uint32_t flags;
uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx;
} ELF64header;
typedef struct {
uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize;
} ELF32sectheader;
typedef struct {
uint32_t name, type;
uint64_t flags, addr, ofs, size;
uint32_t link, info;
uint64_t align, entsize;
} ELF64sectheader;
typedef struct {
uint32_t name, value, size;
uint8_t info, other;
uint16_t sectidx;
} ELF32symbol;
typedef struct {
uint32_t name;
uint8_t info, other;
uint16_t sectidx;
uint64_t value, size;
} ELF64symbol;
typedef struct {
ELF32header hdr;
ELF32sectheader sect[6];
ELF32symbol sym[2];
uint8_t space[4096];
} ELF32obj;
typedef struct {
ELF64header hdr;
ELF64sectheader sect[6];
ELF64symbol sym[2];
uint8_t space[4096];
} ELF64obj;
]]
local symname = LJBC_PREFIX..ctx.modname
local is64, isbe = false, false
if ctx.arch == "x64" then
is64 = true
elseif ctx.arch == "ppc" or ctx.arch == "ppcspe" or ctx.arch == "mips" then
isbe = true
end
-- Handle different host/target endianess.
local function f32(x) return x end
local f16, fofs = f32, f32
if ffi.abi("be") ~= isbe then
f32 = bit.bswap
function f16(x) return bit.rshift(bit.bswap(x), 16) end
if is64 then
local two32 = ffi.cast("int64_t", 2^32)
function fofs(x) return bit.bswap(x)*two32 end
else
fofs = f32
end
end
-- Create ELF object and fill in header.
local o = ffi.new(is64 and "ELF64obj" or "ELF32obj")
local hdr = o.hdr
if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi.
local bf = assert(io.open("/bin/ls", "rb"))
local bs = bf:read(9)
bf:close()
ffi.copy(o, bs, 9)
check(hdr.emagic[0] == 127, "no support for writing native object files")
else
hdr.emagic = "\127ELF"
hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0
end
hdr.eclass = is64 and 2 or 1
hdr.eendian = isbe and 2 or 1
hdr.eversion = 1
hdr.type = f16(1)
hdr.machine = f16(({ x86=3, x64=62, arm=40, ppc=20, ppcspe=20, mips=8, mipsel=8 })[ctx.arch])
if ctx.arch == "mips" or ctx.arch == "mipsel" then
hdr.flags = 0x50001006
end
hdr.version = f32(1)
hdr.shofs = fofs(ffi.offsetof(o, "sect"))
hdr.ehsize = f16(ffi.sizeof(hdr))
hdr.shentsize = f16(ffi.sizeof(o.sect[0]))
hdr.shnum = f16(6)
hdr.shstridx = f16(2)
-- Fill in sections and symbols.
local sofs, ofs = ffi.offsetof(o, "space"), 1
for i,name in ipairs{
".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack",
} do
local sect = o.sect[i]
sect.align = fofs(1)
sect.name = f32(ofs)
ffi.copy(o.space+ofs, name)
ofs = ofs + #name+1
end
o.sect[1].type = f32(2) -- .symtab
o.sect[1].link = f32(3)
o.sect[1].info = f32(1)
o.sect[1].align = fofs(8)
o.sect[1].ofs = fofs(ffi.offsetof(o, "sym"))
o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0]))
o.sect[1].size = fofs(ffi.sizeof(o.sym))
o.sym[1].name = f32(1)
o.sym[1].sectidx = f16(4)
o.sym[1].size = fofs(#s)
o.sym[1].info = 17
o.sect[2].type = f32(3) -- .shstrtab
o.sect[2].ofs = fofs(sofs)
o.sect[2].size = fofs(ofs)
o.sect[3].type = f32(3) -- .strtab
o.sect[3].ofs = fofs(sofs + ofs)
o.sect[3].size = fofs(#symname+1)
ffi.copy(o.space+ofs+1, symname)
ofs = ofs + #symname + 2
o.sect[4].type = f32(1) -- .rodata
o.sect[4].flags = fofs(2)
o.sect[4].ofs = fofs(sofs + ofs)
o.sect[4].size = fofs(#s)
o.sect[5].type = f32(1) -- .note.GNU-stack
o.sect[5].ofs = fofs(sofs + ofs + #s)
-- Write ELF object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs))
bcsave_tail(fp, output, s)
end
local function bcsave_peobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct {
uint16_t arch, nsects;
uint32_t time, symtabofs, nsyms;
uint16_t opthdrsz, flags;
} PEheader;
typedef struct {
char name[8];
uint32_t vsize, vaddr, size, ofs, relocofs, lineofs;
uint16_t nreloc, nline;
uint32_t flags;
} PEsection;
typedef struct __attribute((packed)) {
union {
char name[8];
uint32_t nameref[2];
};
uint32_t value;
int16_t sect;
uint16_t type;
uint8_t scl, naux;
} PEsym;
typedef struct __attribute((packed)) {
uint32_t size;
uint16_t nreloc, nline;
uint32_t cksum;
uint16_t assoc;
uint8_t comdatsel, unused[3];
} PEsymaux;
typedef struct {
PEheader hdr;
PEsection sect[2];
// Must be an even number of symbol structs.
PEsym sym0;
PEsymaux sym0aux;
PEsym sym1;
PEsymaux sym1aux;
PEsym sym2;
PEsym sym3;
uint32_t strtabsize;
uint8_t space[4096];
} PEobj;
]]
local symname = LJBC_PREFIX..ctx.modname
local is64 = false
if ctx.arch == "x86" then
symname = "_"..symname
elseif ctx.arch == "x64" then
is64 = true
end
local symexport = " /EXPORT:"..symname..",DATA "
-- The file format is always little-endian. Swap if the host is big-endian.
local function f32(x) return x end
local f16 = f32
if ffi.abi("be") then
f32 = bit.bswap
function f16(x) return bit.rshift(bit.bswap(x), 16) end
end
-- Create PE object and fill in header.
local o = ffi.new("PEobj")
local hdr = o.hdr
hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch])
hdr.nsects = f16(2)
hdr.symtabofs = f32(ffi.offsetof(o, "sym0"))
hdr.nsyms = f32(6)
-- Fill in sections and symbols.
o.sect[0].name = ".drectve"
o.sect[0].size = f32(#symexport)
o.sect[0].flags = f32(0x00100a00)
o.sym0.sect = f16(1)
o.sym0.scl = 3
o.sym0.name = ".drectve"
o.sym0.naux = 1
o.sym0aux.size = f32(#symexport)
o.sect[1].name = ".rdata"
o.sect[1].size = f32(#s)
o.sect[1].flags = f32(0x40300040)
o.sym1.sect = f16(2)
o.sym1.scl = 3
o.sym1.name = ".rdata"
o.sym1.naux = 1
o.sym1aux.size = f32(#s)
o.sym2.sect = f16(2)
o.sym2.scl = 2
o.sym2.nameref[1] = f32(4)
o.sym3.sect = f16(-1)
o.sym3.scl = 2
o.sym3.value = f32(1)
o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant.
ffi.copy(o.space, symname)
local ofs = #symname + 1
o.strtabsize = f32(ofs + 4)
o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs)
ffi.copy(o.space + ofs, symexport)
ofs = ofs + #symexport
o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs)
-- Write PE object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs))
bcsave_tail(fp, output, s)
end
local function bcsave_machobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct
{
uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags;
} mach_header;
typedef struct
{
mach_header; uint32_t reserved;
} mach_header_64;
typedef struct {
uint32_t cmd, cmdsize;
char segname[16];
uint32_t vmaddr, vmsize, fileoff, filesize;
uint32_t maxprot, initprot, nsects, flags;
} mach_segment_command;
typedef struct {
uint32_t cmd, cmdsize;
char segname[16];
uint64_t vmaddr, vmsize, fileoff, filesize;
uint32_t maxprot, initprot, nsects, flags;
} mach_segment_command_64;
typedef struct {
char sectname[16], segname[16];
uint32_t addr, size;
uint32_t offset, align, reloff, nreloc, flags;
uint32_t reserved1, reserved2;
} mach_section;
typedef struct {
char sectname[16], segname[16];
uint64_t addr, size;
uint32_t offset, align, reloff, nreloc, flags;
uint32_t reserved1, reserved2, reserved3;
} mach_section_64;
typedef struct {
uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize;
} mach_symtab_command;
typedef struct {
int32_t strx;
uint8_t type, sect;
int16_t desc;
uint32_t value;
} mach_nlist;
typedef struct {
uint32_t strx;
uint8_t type, sect;
uint16_t desc;
uint64_t value;
} mach_nlist_64;
typedef struct
{
uint32_t magic, nfat_arch;
} mach_fat_header;
typedef struct
{
uint32_t cputype, cpusubtype, offset, size, align;
} mach_fat_arch;
typedef struct {
struct {
mach_header hdr;
mach_segment_command seg;
mach_section sec;
mach_symtab_command sym;
} arch[1];
mach_nlist sym_entry;
uint8_t space[4096];
} mach_obj;
typedef struct {
struct {
mach_header_64 hdr;
mach_segment_command_64 seg;
mach_section_64 sec;
mach_symtab_command sym;
} arch[1];
mach_nlist_64 sym_entry;
uint8_t space[4096];
} mach_obj_64;
typedef struct {
mach_fat_header fat;
mach_fat_arch fat_arch[4];
struct {
mach_header hdr;
mach_segment_command seg;
mach_section sec;
mach_symtab_command sym;
} arch[4];
mach_nlist sym_entry;
uint8_t space[4096];
} mach_fat_obj;
]]
local symname = '_'..LJBC_PREFIX..ctx.modname
local isfat, is64, align, mobj = false, false, 4, "mach_obj"
if ctx.arch == "x64" then
is64, align, mobj = true, 8, "mach_obj_64"
elseif ctx.arch == "arm" then
isfat, mobj = true, "mach_fat_obj"
else
check(ctx.arch == "x86", "unsupported architecture for OSX")
end
local function aligned(v, a) return bit.band(v+a-1, -a) end
local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE.
-- Create Mach-O object and fill in header.
local o = ffi.new(mobj)
local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align)
local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12,12,12} })[ctx.arch]
local cpusubtype = ({ x86={3}, x64={3}, arm={3,6,9,11} })[ctx.arch]
if isfat then
o.fat.magic = be32(0xcafebabe)
o.fat.nfat_arch = be32(#cpusubtype)
end
-- Fill in sections and symbols.
for i=0,#cpusubtype-1 do
local ofs = 0
if isfat then
local a = o.fat_arch[i]
a.cputype = be32(cputype[i+1])
a.cpusubtype = be32(cpusubtype[i+1])
-- Subsequent slices overlap each other to share data.
ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0])
a.offset = be32(ofs)
a.size = be32(mach_size-ofs+#s)
end
local a = o.arch[i]
a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface
a.hdr.cputype = cputype[i+1]
a.hdr.cpusubtype = cpusubtype[i+1]
a.hdr.filetype = 1
a.hdr.ncmds = 2
a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym)
a.seg.cmd = is64 and 0x19 or 0x1
a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)
a.seg.vmsize = #s
a.seg.fileoff = mach_size-ofs
a.seg.filesize = #s
a.seg.maxprot = 1
a.seg.initprot = 1
a.seg.nsects = 1
ffi.copy(a.sec.sectname, "__data")
ffi.copy(a.sec.segname, "__DATA")
a.sec.size = #s
a.sec.offset = mach_size-ofs
a.sym.cmd = 2
a.sym.cmdsize = ffi.sizeof(a.sym)
a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs
a.sym.nsyms = 1
a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs
a.sym.strsize = aligned(#symname+2, align)
end
o.sym_entry.type = 0xf
o.sym_entry.sect = 1
o.sym_entry.strx = 1
ffi.copy(o.space+1, symname)
-- Write Macho-O object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, mach_size))
bcsave_tail(fp, output, s)
end
local function bcsave_obj(ctx, output, s)
local ok, ffi = pcall(require, "ffi")
check(ok, "FFI library required to write this file type")
if ctx.os == "windows" then
return bcsave_peobj(ctx, output, s, ffi)
elseif ctx.os == "osx" then
return bcsave_machobj(ctx, output, s, ffi)
else
return bcsave_elfobj(ctx, output, s, ffi)
end
end
------------------------------------------------------------------------------
local function bclist(input, output)
local f = readfile(input)
require("jit.bc").dump(f, savefile(output, "w"), true)
end
local function bcsave(ctx, input, output)
local f = readfile(input)
local s = string.dump(f, ctx.strip)
local t = ctx.type
if not t then
t = detecttype(output)
ctx.type = t
end
if t == "raw" then
bcsave_raw(output, s)
else
if not ctx.modname then ctx.modname = detectmodname(input) end
if t == "obj" then
bcsave_obj(ctx, output, s)
else
bcsave_c(ctx, output, s)
end
end
end
local function docmd(...)
local arg = {...}
local n = 1
local list = false
local ctx = {
strip = true, arch = jit.arch, os = string.lower(jit.os),
type = false, modname = false,
}
while n <= #arg do
local a = arg[n]
if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then
table.remove(arg, n)
if a == "--" then break end
for m=2,#a do
local opt = string.sub(a, m, m)
if opt == "l" then
list = true
elseif opt == "s" then
ctx.strip = true
elseif opt == "g" then
ctx.strip = false
else
if arg[n] == nil or m ~= #a then usage() end
if opt == "e" then
if n ~= 1 then usage() end
arg[1] = check(loadstring(arg[1]))
elseif opt == "n" then
ctx.modname = checkmodname(table.remove(arg, n))
elseif opt == "t" then
ctx.type = checkarg(table.remove(arg, n), map_type, "file type")
elseif opt == "a" then
ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture")
elseif opt == "o" then
ctx.os = checkarg(table.remove(arg, n), map_os, "OS name")
else
usage()
end
end
end
else
n = n + 1
end
end
if list then
if #arg == 0 or #arg > 2 then usage() end
bclist(arg[1], arg[2] or "-")
else
if #arg ~= 2 then usage() end
bcsave(ctx, arg[1], arg[2])
end
end
------------------------------------------------------------------------------
-- Public module functions.
module(...)
start = docmd -- Process -b command line option.
| mit |
LegendsOfDota/LegendsOfDota | src/scripts/vscripts/statcollection/schema_examples/enfos.lua | 5 | 5097 | customSchema = class({})
function customSchema:init()
-- Check the schema_examples folder for different implementations
-- Flags
statCollection:setFlags({ version = CEnfosGameMode:GetVersion() })
-- Listen for changes in the current state
ListenToGameEvent('game_rules_state_change', function(keys)
local state = GameRules:State_Get()
-- Send custom stats when the game ends
if state == DOTA_GAMERULES_STATE_POST_GAME then
-- Build game array
local game = BuildGameArray()
-- Build players array
local players = BuildPlayersArray()
-- Print the schema data to the console
if statCollection.TESTING then
PrintSchema(game, players)
end
-- Send custom stats
if statCollection.HAS_SCHEMA then
statCollection:sendCustom({ game = game, players = players })
end
end
end, nil)
end
-------------------------------------
-- In the statcollection/lib/utilities.lua, you'll find many useful functions to build your schema.
-- You are also encouraged to call your custom mod-specific functions
-- Returns a table with our custom game tracking.
function BuildGameArray()
local game = {}
-- Add game values here as game.someValue = GetSomeGameValue()
game.r = Enfos.curRound
return game
end
-- Returns a table containing data for every player in the game
function BuildPlayersArray()
local players = {}
for playerID = 0, DOTA_MAX_PLAYERS do
if PlayerResource:IsValidPlayerID(playerID) then
if not PlayerResource:IsBroadcaster(playerID) then
local hero = PlayerResource:GetSelectedHeroEntity(playerID)
table.insert(players, {
-- steamID32 required in here
steamID32 = PlayerResource:GetSteamAccountID(playerID),
-- Example functions for generic stats are defined in statcollection/lib/utilities.lua
-- Add player values here as someValue = GetSomePlayerValue(),
hn = GetHeroName(playerID), -- name
hl = hero:GetLevel(), -- level
hnw = GetNetworth(PlayerResource:GetSelectedHeroEntity(playerID)), -- Networth
pt = GetPlayerTeam(PlayerResource:GetSelectedHeroEntity(playerID)), -- Hero's team
pk = hero:GetKills(), -- Kills
pa = hero:GetAssists(), -- Assists
pd = hero:GetDeaths(), -- Deaths
plh = PlayerResource:GetLastHits(hero:GetPlayerOwnerID()), -- Last hits
ph = PlayerResource:GetHealing(hero:GetPlayerOwnerID()), -- Healing
pgpm = math.floor(PlayerResource:GetGoldPerMin(hero:GetPlayerOwnerID())), -- GPM
il = GetItemList(hero) -- Item list
})
end
end
end
return players
end
-- Prints the custom schema, required to get an schemaID
function PrintSchema(gameArray, playerArray)
print("-------- GAME DATA --------")
DeepPrintTable(gameArray)
print("\n-------- PLAYER DATA --------")
DeepPrintTable(playerArray)
print("-------------------------------------")
end
-- Write 'test_schema' on the console to test your current functions instead of having to end the game
if Convars:GetBool('developer') then
Convars:RegisterCommand("test_schema", function() PrintSchema(BuildGameArray(), BuildPlayersArray()) end, "Test the custom schema arrays", 0)
end
-------------------------------------
-- If your gamemode is round-based, you can use statCollection:submitRound(bLastRound) at any point of your main game logic code to send a round
-- If you intend to send rounds, make sure your settings.kv has the 'HAS_ROUNDS' set to true. Each round will send the game and player arrays defined earlier
-- The round number is incremented internally, lastRound can be marked to notify that the game ended properly
function customSchema:submitRound(isLastRound)
local winners = BuildRoundWinnerArray()
local game = BuildGameArray()
local players = BuildPlayersArray()
statCollection:sendCustom({ game = game, players = players })
isLastRound = isLastRound or false --If the function is passed with no parameter, default to false.
return { winners = winners, lastRound = isLastRound }
end
-- A list of players marking who won this round
function BuildRoundWinnerArray()
local winners = {}
local current_winner_team = GameRules.Winner or 0 --You'll need to provide your own way of determining which team won the round
for playerID = 0, DOTA_MAX_PLAYERS do
if PlayerResource:IsValidPlayerID(playerID) then
if not PlayerResource:IsBroadcaster(playerID) then
winners[PlayerResource:GetSteamAccountID(playerID)] = (PlayerResource:GetTeam(playerID) == current_winner_team) and 1 or 0
end
end
end
return winners
end
------------------------------------- | gpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/endor/panshee_tribesman.lua | 2 | 1116 | panshee_tribesman = Creature:new {
objectName = "@mob/creature_names:panshee_tribesman",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "panshee_tribe",
faction = "panshee_tribe",
level = 24,
chanceHit = 0.35,
damageMin = 210,
damageMax = 220,
baseXp = 2443,
baseHAM = 5900,
baseHAMmax = 7200,
armor = 1,
resists = {30,30,-1,10,10,-1,-1,10,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_ewok_f_01.iff",
"object/mobile/dressed_ewok_f_07.iff",
"object/mobile/dressed_ewok_f_08.iff",
"object/mobile/dressed_ewok_f_09.iff",
"object/mobile/dressed_ewok_m_01.iff"},
lootGroups = {
{
groups = {
{group = "ewok", chance = 10000000}
},
lootChance = 1480000
}
},
weapons = {"ewok_weapons"},
conversationTemplate = "",
attacks = merge(marksmanmaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(panshee_tribesman, "panshee_tribesman")
| agpl-3.0 |
yimogod/boom | trunk/t-engine4/game/engines/engine/Mouse.lua | 1 | 8494 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2015 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
--- Basic mousepress handler
-- The engine calls receiveMouse when a mouse is clicked
module(..., package.seeall, class.make)
function _M:init()
self.areas = {}
self.areas_name = {}
self.status = {}
self.last_pos = { x = 0, y = 0 }
end
function _M:allowDownEvent(v)
self.allow_down = v
end
--- Called when a mouse is pressed
-- @param button
-- @param x coordinate of the click
-- @param y coordinate of the click
-- @param isup true if the key was released, false if pressed
-- @param force_name if not nil only the zone with this name may trigger
function _M:receiveMouse(button, x, y, isup, force_name, extra)
self.last_pos = { x = x, y = y }
self.status[button] = not isup
if not self.allow_down and not isup then return end
if _M.drag then
if _M.drag.prestart then _M.drag = nil
else return self:endDrag(x, y) end
end
for i = 1, #self.areas do
local m = self.areas[i]
if (not m.mode or m.mode.button) and (x >= m.x1 and x < m.x2 and y >= m.y1 and y < m.y2) and (not force_name or force_name == m.name) then
m.fct(button, x, y, nil, nil, (x-m.x1) / m.scale, (y-m.y1) / m.scale, isup and "button" or "button-down", extra)
break
end
end
end
function _M:getPos()
return self.last_pos.x, self.last_pos.y
end
function _M:receiveMouseMotion(button, x, y, xrel, yrel, force_name, extra)
self.last_pos = { x = x, y = y }
if _M.drag then
if _M.drag.on_move then return _M.drag.on_move(_M.drag, button, x, y, xrel, yrel) end
end
local cur_m = nil
for i = 1, #self.areas do
local m = self.areas[i]
if (not m.mode or m.mode.move) and (x >= m.x1 and x < m.x2 and y >= m.y1 and y < m.y2) and (not force_name or force_name == m.name) then
m.fct(button, x, y, xrel, yrel, (x-m.x1) / m.scale, (y-m.y1) / m.scale, "motion", extra)
cur_m = m
break
end
end
if self.last_m and self.last_m.allow_out_events and self.last_m ~= cur_m then
self.last_m.fct("none", x, y, xrel, yrel, (x-self.last_m.x1) / self.last_m.scale, (y-self.last_m.y1) / self.last_m.scale, "out", extra)
end
self.last_m = cur_m
end
--- Delegate an event from an other mouse handler
-- if self.delegate_offset_x and self.delegate_offset_y are set hey will be used to change the actual coordinates
function _M:delegate(button, mx, my, xrel, yrel, bx, by, event, name, extra)
local ox, oy = (self.delegate_offset_x or 0), (self.delegate_offset_y or 0)
mx = mx - ox
my = my - oy
if event == "button" then self:receiveMouse(button, mx, my, true, name, extra)
elseif event == "button-down" then self:receiveMouse(button, mx, my, false, name, extra)
elseif event == "motion" then self:receiveMouseMotion(button, mx, my, xrel, yrel, name, extra)
end
end
--- Setups as the current game keyhandler
function _M:setCurrent()
core.mouse.set_current_handler(self)
-- if game then game.mouse = self end
_M.current = self
end
--- Returns a zone definition by its name
function _M:getZone(name)
return self.areas_name[name]
end
--- Update a named zone with new coords
-- @return true if the zone was found and updated
function _M:updateZone(name, x, y, w, h, fct, scale)
local m = self.areas_name[name]
if not m then return false end
m.scale = scale or m.scale
m.x1 = x
m.y1 = y
m.x2 = x + w * m.scale
m.y2 = y + h * m.scale
m.fct = fct or m.fct
return true
end
--- Registers a click zone that when clicked will call the object's "onClick" method
function _M:registerZone(x, y, w, h, fct, mode, name, allow_out_events, scale)
scale = scale or 1
local d = {x1=x,y1=y,x2=x+w * scale,y2=y+h * scale, fct=fct, mode=mode, name=name, allow_out_events=allow_out_events, scale=scale}
table.insert(self.areas, 1, d)
if name then self.areas_name[name] = d end
end
function _M:registerZones(t)
for i, z in ipairs(t) do
self:registerZone(z.x, z.y, z.w, z.h, z.fct, z.mode, z.name, z.out_events)
end
end
function _M:unregisterZone(fct)
if type(fct) == "function" then
for i = #self.areas, 1, -1 do
local m = self.areas[i]
if m.fct == fct then local m = table.remove(self.areas, i) if m.name then self.areas_name[m.name] = nil end break end
end
else
for i = #self.areas, 1, -1 do
local m = self.areas[i]
if m.name == fct then local m = table.remove(self.areas, i) if m.name then self.areas_name[m.name] = nil end end
end
end
end
function _M:reset()
self.areas = {}
self.areas_name = {}
end
function _M:startDrag(x, y, cursor, payload, on_done, on_move, no_prestart)
local start = function()
_M.drag.prestart = nil
if _M.drag.cursor then
local w, h = _M.drag.cursor:getSize()
_M.drag.cursor = _M.drag.cursor:glTexture()
core.display.setMouseDrag(_M.drag.cursor, w, h)
end
print("[MOUSE] enabling drag from predrag")
end
if _M.drag then
if _M.drag.prestart and math.max(math.abs(_M.drag.start_x - x), math.abs(_M.drag.start_y - y)) > 6 then
start()
end
return
end
_M.drag = {start_x=x, start_y=y, payload=payload, on_done=on_done, on_move=on_move, prestart=true, cursor=cursor}
print("[MOUSE] pre starting drag'n'drop")
if no_prestart then start() end
end
function _M:endDrag(x, y)
local drag = _M.drag
print("[MOUSE] ending drag'n'drop")
core.display.setMouseDrag(nil, 0, 0)
_M.drag = nil
_M.dragged = drag
_M.current:receiveMouse("drag-end", x, y, true, nil, {drag=drag})
if drag.on_done then drag.on_done(drag, drag.used) end
_M.dragged = nil
end
function _M:usedDrag()
(_M.drag or _M.dragged).used = true
end
--- Called when a touch event is received
-- @param fingerId id of the finger info
-- @param x coordinate of the click (normalized to 0->1)
-- @param y coordinate of the click (normalized to 0->1)
-- @param dx delta coordinate of the click (normalized to 0->1)
-- @param dy delta coordinate of the click (normalized to 0->1)
-- @param isup true if the key was released, false if pressed
function _M:receiveTouch(fingerId, x, y, dx, dy, pressure, isup)
-- print("=touch", fingerId, x, y, dx, dy, pressure, isup)
end
--- Called when a touch event is received
-- @param fingerId id of the finger info
-- @param x coordinate of the click (normalized to 0->1)
-- @param y coordinate of the click (normalized to 0->1)
-- @param dx delta coordinate of the click (normalized to 0->1)
-- @param dy delta coordinate of the click (normalized to 0->1)
-- @param isup true if the key was released, false if pressed
function _M:receiveTouchMotion(fingerId, x, y, dx, dy, pressure)
-- print("=touch motion", fingerId, x, y, dx, dy, pressure)
end
--- Called when a touch event is received
-- @param fingerId id of the finger info
-- @param x coordinate of the click (normalized to 0->1)
-- @param y coordinate of the click (normalized to 0->1)
-- @param dx delta coordinate of the click (normalized to 0->1)
-- @param dy delta coordinate of the click (normalized to 0->1)
-- @param isup true if the key was released, false if pressed
function _M:receiveTouchGesture(nb_fingers, x, y, d_rot, d_pinch)
-- print("=touch gesture", nb_fingers, x, y, d_rot, d_pinch)
end
--- Called when a gamepad axis event is received
-- @param axis id of axis changed
-- @param value current value of the axis, from -1 to 1
function _M:receiveJoyAxis(axis, value)
-- print("=joy axis", axis, value)
end
--- Called when a gamepad ball event is received
-- @param ball id of ball changed
-- @param xrel the relative movement of the ball
-- @param yrel the relative movement of the ball
function _M:receiveJoyBall(ball, xrel, yrel)
-- print("=joy ball", axis, value)
end
--- Called when a gamepad hat event is received
-- @param hat id of the hat changed
-- @param dir current direction of the hat, one of 1,2,3,4,6,7,8,9 (representing direction)
function _M:receiveJoyHat(hat, dir)
-- print("=joy hat", hat, dir)
end
| apache-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/loot/items/wearables/ithorian/ith_jacket_s08.lua | 4 | 1278 | ith_jacket_s08 = {
-- Ithorian Tech Jacket
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/wearables/ithorian/ith_jacket_s08.iff",
craftingValues = {},
skillMods = {},
customizationStringNames = {"/private/index_color_1","/private/index_color_2"},
customizationValues = {
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119}
},
junkDealerTypeNeeded = JUNKCLOTHESANDJEWELLERY,
junkMinValue = 35,
junkMaxValue = 70
}
addLootItemTemplate("ith_jacket_s08", ith_jacket_s08) | agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/melee2hLunge1.lua | 2 | 2577 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
Melee2hLunge1Command = {
name = "melee2hlunge1",
damageMultiplier = 1.0,
speedMultiplier = 1.5,
accuracyBonus = 10,
healthCostMultiplier = 1.0,
actionCostMultiplier = 0.5,
mindCostMultiplier = 0.5,
animationCRC = hashCode("lower_posture_2hmelee_1"),
combatSpam = "lungeslam",
range = 20,
weaponType = TWOHANDMELEEWEAPON,
stateEffects = {
StateEffect(
POSTUREDOWN_EFFECT,
{ "postureDownRecovery" },
{ "posture_change_down_defense" },
{},
100,
0,
0
)
}
}
AddCommand(Melee2hLunge1Command)
| agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/setLoginTitle.lua | 4 | 2132 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
SetLoginTitleCommand = {
name = "setlogintitle",
}
AddCommand(SetLoginTitleCommand)
| agpl-3.0 |
DarkMuffinJoe/DeadlyZombies | lua/entities/curegranate_entity/init.lua | 1 | 1611 | include("shared.lua")
AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")
local humans = {
"npc_alyx",
"npc_barney",
"npc_citizen",
"npc_magnusson",
"npc_kleiner",
"npc_mossman",
"npc_gman",
"npc_odessa",
"npc_breen",
"npc_monk"
}
local zombies = {
"npc_zombie",
"npc_fastzombie",
"npc_fastzombie_torso",
"npc_zombie_torso",
"npc_poisonzombie"
}
function ENT:Initialize()
self:SetModel( "models/weapons/w_grenade.mdl" )
self:SetMoveType(MOVETYPE_NONE)
self:SetSolid(SOLID_NONE)
self:DrawShadow(false)
self.DeleteTime = CurTime() + 60
self.CheckTime = CurTime()
self:EmitSound("weapons/explode"..math.random(3,5)..".wav", 130, 100)
end
function ENT:Think()
if CurTime() >= self.CheckTime then
local entities = ents.FindInSphere(self:GetPos(), 125)
for k,v in pairs(entities) do
if table.HasValue(humans, v:GetClass()) or v:IsPlayer() then
if v.infected then
if v.stage != 2 then
v.infected = false
else
v:TakeDamage(20, self,self)
/*if v:IsPlayer() then
if math.random(1,4) == 4 then
v:SendLua("surface.PlaySound(\"npc/zombie_poison/pz_pain\"..math.random(1,3)..\".wav\")")
end
end*/
end
end
elseif table.HasValue(zombies, v:GetClass()) then
v:TakeDamage(20, self,self)
end
end
local part = EffectData()
part:SetStart( self:GetPos() + Vector(0,0,70) )
part:SetOrigin( self:GetPos() + Vector(0,0,70) )
part:SetEntity( self )
part:SetScale( 1 )
util.Effect( "curegas", part)
self.CheckTime = CurTime() + 1
end
if CurTime() >= self.DeleteTime then
self:Remove()
end
end | apache-2.0 |
ClearTables/ClearTables | pier.lua | 2 | 1598 | --[[
This file is part of ClearTables
@author Paul Norman <penorman@mac.com>
@copyright 2017 Paul Norman, MIT license
]]--
require "common"
function accept_pier_area (tags)
-- generic_polygon_way checks for being an area (e.g. area=yes)
return tags["man_made"] == "pier"
end
--- Acceptance for raw piers as lines
-- THis only accepts those which don't have tags *other* than man_made=pier
-- indicating its an area.
function accept_pier_line_raw (tags)
if tags["man_made"] and tags["man_made"] == "pier" then
-- drop the man_made tag to see if it's still an area
tags["man_made"] = nil
-- Only accept features which aren't polygons
return not isarea(tags)
end
return false
end
function transform_pier_area (tags)
local cols = {}
cols.name = tags["name"]
cols.names = names(tags)
return cols
end
function transform_pier_line_raw (tags)
local cols = {}
cols.name = tags["name"]
cols.names = names(tags)
if tags["area"] == "no" then
-- This object is a line, regardless of if it is closed or not
cols.forced_line = "true"
end
return cols
end
function pier_line_raw_ways (tags, num_keys)
return generic_line_way(tags, accept_pier_line_raw, transform_pier_line_raw)
end
function pier_area_ways (tags, num_keys)
return generic_polygon_way(tags, accept_pier_area, transform_pier_area)
end
function pier_rel_members (tags, member_tags, member_roles, membercount)
return generic_multipolygon_members(tags, member_tags, membercount, accept_pier_area, transform_pier_area)
end
| mit |
ShadowNinja/areas | internal.lua | 2 | 7979 | local S = minetest.get_translator("areas")
function areas:player_exists(name)
return minetest.get_auth_handler().get_auth(name) ~= nil
end
local safe_file_write = minetest.safe_file_write
if safe_file_write == nil then
function safe_file_write(path, content)
local file, err = io.open(path, "w")
if err then
return err
end
file:write(content)
file:close()
end
end
-- Save the areas table to a file
function areas:save()
local datastr = minetest.write_json(self.areas)
if not datastr then
minetest.log("error", "[areas] Failed to serialize area data!")
return
end
return safe_file_write(self.config.filename, datastr)
end
-- Load the areas table from the save file
function areas:load()
local file, err = io.open(self.config.filename, "r")
if err then
self.areas = self.areas or {}
return err
end
local data = file:read("*a")
if data:sub(1, 1) == "[" then
self.areas, err = minetest.parse_json(data)
else
self.areas, err = minetest.deserialize(data)
end
if type(self.areas) ~= "table" then
self.areas = {}
end
if err and #data > 10 then
minetest.log("error", "[areas] Failed to load area data: " ..
tostring(err))
end
file:close()
self:populateStore()
end
--- Checks an AreaStore ID.
-- Deletes the AreaStore (falling back to the iterative method)
-- and prints an error message if the ID is invalid.
-- @return Whether the ID was valid.
function areas:checkAreaStoreId(sid)
if not sid then
minetest.log("error", "AreaStore failed to find an ID for an "
.."area! Falling back to iterative area checking.")
self.store = nil
self.store_ids = nil
end
return sid and true or false
end
-- Populates the AreaStore after loading, if needed.
function areas:populateStore()
if not rawget(_G, "AreaStore") then
return
end
local store = AreaStore()
local store_ids = {}
for id, area in pairs(areas.areas) do
local sid = store:insert_area(area.pos1,
area.pos2, tostring(id))
if not self:checkAreaStoreId(sid) then
return
end
store_ids[id] = sid
end
self.store = store
self.store_ids = store_ids
end
-- Finds the first usable index in a table
-- Eg: {[1]=false,[4]=true} -> 2
local function findFirstUnusedIndex(t)
local i = 0
repeat i = i + 1
until t[i] == nil
return i
end
--- Add a area.
-- @return The new area's ID.
function areas:add(owner, name, pos1, pos2, parent)
local id = findFirstUnusedIndex(self.areas)
self.areas[id] = {
name = name,
pos1 = pos1,
pos2 = pos2,
owner = owner,
parent = parent
}
for i=1, #areas.registered_on_adds do
areas.registered_on_adds[i](id, self.areas[id])
end
-- Add to AreaStore
if self.store then
local sid = self.store:insert_area(pos1, pos2, tostring(id))
if self:checkAreaStoreId(sid) then
self.store_ids[id] = sid
end
end
return id
end
--- Remove a area, and optionally it's children recursively.
-- If a area is deleted non-recursively the children will
-- have the removed area's parent as their new parent.
function areas:remove(id, recurse)
if recurse then
-- Recursively find child entries and remove them
local cids = self:getChildren(id)
for _, cid in pairs(cids) do
self:remove(cid, true)
end
else
-- Update parents
local parent = self.areas[id].parent
local children = self:getChildren(id)
for _, cid in pairs(children) do
-- The subarea parent will be niled out if the
-- removed area does not have a parent
self.areas[cid].parent = parent
end
end
for i=1, #areas.registered_on_removes do
areas.registered_on_removes[i](id)
end
-- Remove main entry
self.areas[id] = nil
-- Remove from AreaStore
if self.store then
self.store:remove_area(self.store_ids[id])
self.store_ids[id] = nil
end
end
--- Move an area.
function areas:move(id, area, pos1, pos2)
area.pos1 = pos1
area.pos2 = pos2
for i=1, #areas.registered_on_moves do
areas.registered_on_moves[i](id, area, pos1, pos2)
end
if self.store then
self.store:remove_area(areas.store_ids[id])
local sid = self.store:insert_area(pos1, pos2, tostring(id))
if self:checkAreaStoreId(sid) then
self.store_ids[id] = sid
end
end
end
-- Checks if a area between two points is entirely contained by another area.
-- Positions must be sorted.
function areas:isSubarea(pos1, pos2, id)
local area = self.areas[id]
if not area then
return false
end
local ap1, ap2 = area.pos1, area.pos2
local ap1x, ap1y, ap1z = ap1.x, ap1.y, ap1.z
local ap2x, ap2y, ap2z = ap2.x, ap2.y, ap2.z
local p1x, p1y, p1z = pos1.x, pos1.y, pos1.z
local p2x, p2y, p2z = pos2.x, pos2.y, pos2.z
if
(p1x >= ap1x and p1x <= ap2x) and
(p2x >= ap1x and p2x <= ap2x) and
(p1y >= ap1y and p1y <= ap2y) and
(p2y >= ap1y and p2y <= ap2y) and
(p1z >= ap1z and p1z <= ap2z) and
(p2z >= ap1z and p2z <= ap2z) then
return true
end
end
-- Returns a table (list) of children of an area given it's identifier
function areas:getChildren(id)
local children = {}
for cid, area in pairs(self.areas) do
if area.parent and area.parent == id then
table.insert(children, cid)
end
end
return children
end
-- Checks if the user has sufficient privileges.
-- If the player is not a administrator it also checks
-- if the area intersects other areas that they do not own.
-- Also checks the size of the area and if the user already
-- has more than max_areas.
function areas:canPlayerAddArea(pos1, pos2, name)
local privs = minetest.get_player_privs(name)
if privs.areas then
return true
end
-- Check self protection privilege, if it is enabled,
-- and if the area is too big.
if not self.config.self_protection or
not privs[areas.config.self_protection_privilege] then
return false, S("Self protection is disabled or you do not have"
.." the necessary privilege.")
end
local max_size = privs.areas_high_limit and
self.config.self_protection_max_size_high or
self.config.self_protection_max_size
if
(pos2.x - pos1.x) > max_size.x or
(pos2.y - pos1.y) > max_size.y or
(pos2.z - pos1.z) > max_size.z then
return false, S("Area is too big.")
end
-- Check number of areas the user has and make sure it not above the max
local count = 0
for _, area in pairs(self.areas) do
if area.owner == name then
count = count + 1
end
end
local max_areas = privs.areas_high_limit and
self.config.self_protection_max_areas_high or
self.config.self_protection_max_areas
if count >= max_areas then
return false, S("You have reached the maximum amount of"
.." areas that you are allowed to protect.")
end
-- Check intersecting areas
local can, id = self:canInteractInArea(pos1, pos2, name)
if not can then
local area = self.areas[id]
return false, S("The area intersects with @1 [@2] (@3).",
area.name, id, area.owner)
end
return true
end
-- Given a id returns a string in the format:
-- "name [id]: owner (x1, y1, z1) (x2, y2, z2) -> children"
function areas:toString(id)
local area = self.areas[id]
local message = ("%s [%d]: %s %s %s"):format(
area.name, id, area.owner,
minetest.pos_to_string(area.pos1),
minetest.pos_to_string(area.pos2))
local children = areas:getChildren(id)
if #children > 0 then
message = message.." -> "..table.concat(children, ", ")
end
return message
end
-- Re-order areas in table by their identifiers
function areas:sort()
local sa = {}
for k, area in pairs(self.areas) do
if not area.parent then
table.insert(sa, area)
local newid = #sa
for _, subarea in pairs(self.areas) do
if subarea.parent == k then
subarea.parent = newid
table.insert(sa, subarea)
end
end
end
end
self.areas = sa
end
-- Checks if a player owns an area or a parent of it
function areas:isAreaOwner(id, name)
local cur = self.areas[id]
if cur and minetest.check_player_privs(name, self.adminPrivs) then
return true
end
while cur do
if cur.owner == name then
return true
elseif cur.parent then
cur = self.areas[cur.parent]
else
return false
end
end
return false
end
| lgpl-2.1 |
alireza1998/gfx1 | 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 |
mortezamosavy999/monsterr | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
punisherbot/shayan | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
amin1717/Dark-Wolfs-bot | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
elite-lang/oolua | build_scripts/oolua_amalgamation.lua | 2 | 6262 | --/**
--[[
\file oolua_amalgamation.lua
\brief Lua module for amalgamating the library's headers and source files into
one header and source file.
--]]
--*/
local copyright = [[
/*
The MIT License
Copyright (c) 2009 - 2015 Liam Devine
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
]]
--[[This allows doxygen to document the functions as you may expect--]]
--function amalgamate(include_dir, src_dir, output_dir);
--Lua module that generates a single header and source file for the library.
--/**
--[[
\addtogroup OOLuaConfig
@{
\addtogroup OOLuaAmalagate File amalgamation
@{
\brief Header and source file amalgamation
\details The module "oolua_amalgamation" returns a table containing a single function, amalgamate.
\snippet oolua_amalgamation.lua AmalModuleReturn
This function concatenates all of the library's header files to produce the file oolua.h, and
similarly the source files to produce the file oolua.cpp. The two files will contain all the functionality
of the library and could quickly be integrated into your project
You can produce the files using either the module with Lua or premake4.
<p>
<b>Lua module</b>:
\code
lua -e "require('build_scripts.oolua_amalgamation').amalgamate('./include/', './src/', './')"
\endcode
<p>
<b>Premake4</b>:
<p>
Generating the amalgamated files with premake4, will create the files oolua.h and oolua.cpp
that will be located in the directory "amal".
\code
premake4 oolua-amalgam
\endcode
\fn function amalgamate (include_dir, src_dir, output_dir)
\param include_dir Directory containing the header files
\param src_dir Directory containing the source files
\param output_dir Output directory for the amalgamated files
\brief Generates an amalgamated header and source file for the library.
\details Concatenates all the header files from include_dir and separately the source files from
src_dir, producing the outputs oolua.h and oolua.cpp respectively. These two files, located in
output_dir, contain all the functionality of the library.
@}
@}
--]]
--*/
--function amalgamate(include_dir, src_dir, output_dir);
local headers =
{
'lua_includes.h'
,'platform_check.h'
,'oolua_config.h'
,'typelist_structs.h'
,'type_list.h'
,'dsl_va_args.h'
,'lvd_type_traits.h'
,'lvd_types.h'
,'proxy_test.h'
,'oolua_string.h'
,'oolua_traits_fwd.h'
,'oolua_traits.h'
,'char_arrays.h'
,'proxy_userdata.h'
,'proxy_class.h'
,'proxy_base_checker.h'
,'class_from_stack.h'
,'oolua_error.h'
,'oolua_exception.h'
,'oolua_boilerplate.h'
,'type_converters.h'
,'oolua_stack_fwd.h'
,'proxy_tag_info.h'
,'proxy_storage.h'
,'push_pointer_internal.h'
,'proxy_stack_helper.h'
,'proxy_caller.h'
,'default_trait_caller.h'
,'oolua.h'
,'oolua_check_result.h'
,'oolua_chunk.h'
,'oolua_dsl.h'
,'oolua_dsl_export.h'
,'oolua_ref.h'
,'oolua_function.h'
,'oolua_helpers.h'
,'oolua_open.h'
,'oolua_pull.h'
,'oolua_push.h'
,'oolua_registration_fwd.h'
,'proxy_function_dispatch.h'
,'proxy_tags.h'
,'oolua_table.h'
,'proxy_operators.h'
,'oolua_registration.h'
,'oolua_script.h'
,'oolua_stack.h'
,'oolua_stack_dump.h'
,'oolua_version.h'
,'proxy_constructor_param_tester.h'
,'proxy_constructor.h'
,'proxy_member_function.h'
,'proxy_none_member_function.h'
,'proxy_public_member.h'
,'stack_get.h'
,'proxy_function_exports.h'
}
local source =
{
'class_from_stack.cpp'
,'oolua.cpp'
,'oolua_check_result.cpp'
,'oolua_chunk.cpp'
,'oolua_error.cpp'
,'oolua_exception.cpp'
,'oolua_function.cpp'
,'oolua_helpers.cpp'
,'oolua_open.cpp'
,'oolua_push.cpp'
,'oolua_pull.cpp'
,'oolua_ref.cpp'
,'oolua_registration.cpp'
,'oolua_script.cpp'
,'oolua_stack_dump.cpp'
,'oolua_string.cpp'
,'oolua_table.cpp'
,'proxy_storage.cpp'
,'push_pointer_internal.cpp'
,'stack_get.cpp'
}
local hcopy = {}
for _,v in ipairs(headers)do
hcopy[v] = 1
end
local remove_all_oolua_header_includes = function(header_file_data)
local result = header_file_data:gsub('(\n#%s-include%s-)"(.-)"',
function(c1,c2)
if hcopy[c2] then return ''
else return c1..'"'..c2..'"'
end
end)
return result
end
local do_headers = function(include_dir, output_dir)
local f = io.open(output_dir .. 'oolua.h', 'w+')
for _, file in ipairs(headers) do
local _f, err = io.open(include_dir .. file)
if err then print(err) end
f:write(remove_all_oolua_header_includes(_f:read('*a')))
_f:close()
end
f:close()
end
local do_source = function(src_dir, output_dir)
local f = io.open(output_dir .. 'oolua.cpp', 'w+')
f:write('#include "oolua.h"\n')
for _, file in ipairs(source) do
local _f, err = io.open(src_dir .. file)
if err then print(err) end
f:write(remove_all_oolua_header_includes(_f:read('*a')))
_f:close()
end
f:close()
end
local gen_false_header = function(leaf_and_path)
local f, err = io.open(leaf_and_path, 'w+')
if err then print(err) end
f:write('#include "oolua.h"\n')
f:close()
end
local amalgamate = function(include_dir, src_dir, output_dir)
do_headers(include_dir, output_dir)
do_source(src_dir, output_dir)
-- gen_false_header(output_dir .. 'oolua_dsl.h')
-- gen_false_header(output_dir .. 'oolua_dsl_export.h')
end
--/*[AmalModuleReturn]*/
return {
amalgamate = amalgamate
}
--/*[AmalModuleReturn]*/
| mit |
MonkeyZZZZ/platform_external_skia | resources/slides_content.lua | 78 | 1789 | Skia Overview 2014
< transition =slide>
One API -- many backends
- Raster [8888, 565, A8]
- GPU [opengl]
- PDF
- XPS
- Picture
- Pipe
<transition= fade>
One Team -- many clients
- Chrome
- ChromeOS
- Clank
- Android Framework
- 3rd parties (e.g. FireFox)
<transition= rotate>
<blockstyle = code>
Optimize for CPU variety
- x86 - 32bit (SSE, SSE2, ...), 64bit
- Arm - thumb, arm, NEON, ... 64bit?
- MIPS (just starting)
<transition= zoom>
Optimize for GPU variety
- Nvidia
- Qualcom
- Imagination
- ...
- ES2 -vs- ES3 -vs- Desktop profiles
Lots of testing and measuring
- build-bots
-- unittests, micro-benchmarks, image-regressions
-- http://108.170.217.252:10117/console
- webpage archives (in progress)
-- "map-reduce" server for saerching/historgrams
-- macro-benchmarks, image-reressions
-- gpu : cpu fuzzy compares
Skia Roadmap [Fall '13]
Roadmap in a nutshell
- GPU performance
- Pictures
- Images
- Fonts
- PDF
Roadmap : GPU Performance
- Clipping changes are expensive
- Texture cache optimizations
- Better batching / reordering
- Rely more on multi-sampling
- ES3/desktop features (e.g. path-rendering)
- ... continuo ad absurdum
Roadmap : Pictures
- Playback performance
-- improve culling
-- multi-core support
- Record performance
-- improve hash/cache
-- improve measuring/bbox computation
- Feedback to clients
-- annotations
-- heat-map for time spent drawing
-- peep-hole optimizations
Roadmap : Images
- HQ filtering and mipmaps
- Unpremul support
- sRGB support (future)
- Improve cache / lazy-decoding
Roadmap : Fonts
- Color emoji
- DirectWrite on windows
-- subpixel positioning!
- new FontMgr -- extended styles
Roadmap : PDF
- Android
-- perspective, color-filters
- New Viewer project
-- print-preview and more
-- can output picture / gpu directly
| bsd-3-clause |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/conversations/events/life_day/life_day_oraalarri_conv.lua | 3 | 4986 | lifeDayOraalarriConvoTemplate = ConvoTemplate:new {
initialScreen = "",
templateType = "Lua",
luaClassHandler = "lifeDayOraalarriConvoHandler",
screens = {}
}
im_sorry = ConvoScreen:new {
id = "im_sorry",
leftDialog = "@conversation/lifeday04b:s_5bd07d67", -- (Translated from Shyriiwook) I'm sorry, This is a private gathering for family and friends.
stopConversation = "true",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(im_sorry);
greetings = ConvoScreen:new {
id = "greetings",
leftDialog = "@conversation/lifeday04b:s_f0c65663", -- (Translated from Shyriiwook) Happy Life Day, friend! We are glad to have you celebrate with us.
stopConversation = "false",
options = {
{"@conversation/lifeday04b:s_8a712dbc", "speak_to_others"}, -- Thank you. What do I do?
{"@conversation/lifeday04b:s_6cd2786a", "i_understand"} -- I think I will do this later.
}
}
lifeDayOraalarriConvoTemplate:addScreen(greetings);
speak_to_others = ConvoScreen:new {
id = "speak_to_others",
leftDialog = "@conversation/lifeday04b:s_d8cde9a", -- Speak with all those assembled to learn about our holiday. Once you have heard what we have to say, I will see if we can find a Life Day gift for you.
stopConversation = "true",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(speak_to_others);
i_understand = ConvoScreen:new {
id = "i_understand",
leftDialog = "@conversation/lifeday04b:s_feeecf48", -- I understand, but if you wait too long, the time will pass and you will have to wait until next year to join us. Be safe, friend.
stopConversation = "true",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(i_understand);
no_gift = ConvoScreen:new {
id = "no_gift",
leftDialog = "@conversation/lifeday04b:s_b85028af", -- (Translated from Shyriiwook) I hope you have learned something of our ways. Since you have not been with our community for thirty cycles, I do not have a gift for you, but I hope you will keep the spirit of Life Day alive in your heart and return to us next year.
stopConversation = "true",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(no_gift);
have_spoken = ConvoScreen:new {
id = "have_spoken",
leftDialog = "@conversation/lifeday04b:s_b874dc09", -- (Translated from Shyriiwook) You have spoken to those assembled and learned of our ways. Hopefully this day brings you closer to freedom and to harmony and to peace. May you hold Life Day as dear as we do.
stopConversation = "false",
options = {
{"@conversation/lifeday04b:s_ebbd31aa", "have_gifts"} -- I have learned a lot.
}
}
lifeDayOraalarriConvoTemplate:addScreen(have_spoken);
have_gifts = ConvoScreen:new {
id = "have_gifts",
leftDialog = "@conversation/lifeday04b:s_af9f8883", -- (Translated from Shyriiwook) For those beings that have been a part of our community for at least thirty cycles, we have collected gifts to help you remember this day.
stopConversation = "false",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(have_gifts);
gift_non_wookiee = ConvoScreen:new {
id = "gift_non_wookiee",
leftDialog = "@conversation/lifeday04b:s_66b5743f", -- (Translated from Shyriiwook) This is a gift that reflects our Wookiee heritage. We hope you will display your gift with pride and remember your time with us.
stopConversation = "true",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(gift_non_wookiee);
gift_wookiee = ConvoScreen:new {
id = "gift_wookiee",
leftDialog = "@conversation/lifeday04b:s_f0f674e2", -- (Translated from Shyriiwook) Since you are one of our own, you have a choice. You may choose a traditional Life Day robe that may only be worn by Wookiees or you may receive another gift.
stopConversation = "false",
options = {
{"@conversation/lifeday04b:s_352585ec", "enjoy_robe"}, -- I would like the Wookiee Life Day Robe.
{"@conversation/lifeday04b:s_52645cdc", "enjoy_other_gift"} -- I would like another Life Day gift.
}
}
lifeDayOraalarriConvoTemplate:addScreen(gift_wookiee);
enjoy_robe = ConvoScreen:new {
id = "enjoy_robe",
leftDialog = "@conversation/lifeday04b:s_de3b1306", -- (Translated from Shyriiwook) Enjoy your gift. Happy Life Day to you.
stopConversation = "true",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(enjoy_robe);
enjoy_other_gift = ConvoScreen:new {
id = "enjoy_other_gift",
leftDialog = "@conversation/lifeday04b:s_de3b1306", -- (Translated from Shyriiwook) Enjoy your gift. Happy Life Day to you.
stopConversation = "true",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(enjoy_other_gift);
return_complete = ConvoScreen:new {
id = "return_complete",
leftDialog = "@conversation/lifeday04b:s_fe83540d", -- (Translated from Shyriiwook) It is good to see you again. Thank you for taking part in our celebration. We hope to see you next year.
stopConversation = "true",
options = {}
}
lifeDayOraalarriConvoTemplate:addScreen(return_complete);
addConversationTemplate("lifeDayOraalarriConvoTemplate", lifeDayOraalarriConvoTemplate);
| agpl-3.0 |
Inquiryel/HPW_Rewrite-SBS | lua/hpwrewrite/spells/harrypotter/avadakedavra.lua | 2 | 2254 | local Spell = { }
Spell.LearnTime = 1200
Spell.Description = [[
The Killing curse.
Inflicts instant painless death.
]]
Spell.Category = HpwRewrite.CategoryNames.Unforgivable
Spell.FlyEffect = "hpw_avadaked_main"
Spell.ImpactEffect = "hpw_avadaked_impact"
Spell.ApplyDelay = 0.5
Spell.AccuracyDecreaseVal = 0.3
Spell.Unforgivable = true
Spell.ForceAnim = { ACT_VM_PRIMARYATTACK_1, ACT_VM_PRIMARYATTACK_2 }
Spell.SpriteColor = Color(60, 255, 160)
Spell.Fightable = true
Spell.DoSparks = true
Spell.NodeOffset = Vector(938, -511, 0)
local mat = Material("cable/hydra")
local mat2 = Material("cable/xbeam")
Spell.FightingEffect = function(nPoints, points)
render.SetMaterial(mat)
for i = 1, 3 do
render.StartBeam(nPoints)
for k, v in pairs(points) do
render.AddBeam(v, (k / nPoints) * 60, math.Rand(0, 2), color_white)
end
render.EndBeam()
end
render.SetMaterial(mat2)
for i = 1, 2 do
render.StartBeam(nPoints)
for k, v in pairs(points) do
render.AddBeam(v, (k / nPoints) * 10, math.Rand(0, 1), color_white)
end
render.EndBeam()
end
for k, v in pairs(points) do
if math.random(1, (1 / RealFrameTime()) * 2) == 1 then HpwRewrite.MakeEffect("hpw_avadaked_impact", v, AngleRand()) end
end
end
function Spell:Draw(spell)
self:DrawGlow(spell)
end
function Spell:OnSpellSpawned(wand, spell)
sound.Play("ambient/wind/wind_snippet2.wav", spell:GetPos(), 75, 255)
spell:EmitSound("ambient/wind/wind_snippet2.wav", 80, 255)
wand:PlayCastSound()
end
function Spell:OnRemove(spell)
if CLIENT then
local dlight = DynamicLight(spell:EntIndex())
if dlight then
dlight.pos = spell:GetPos()
dlight.r = 80
dlight.g = 235
dlight.b = 180
dlight.brightness = 6
dlight.Decay = 1000
dlight.Size = 256
dlight.DieTime = CurTime() + 1
end
end
end
function Spell:OnFire(wand)
return true
end
function Spell:OnCollide(spell, data)
local ent = data.HitEntity
if IsValid(ent) then
local force = spell:GetFlyDirection() * 10000
if ent:IsNPC() or ent:IsPlayer() then
HpwRewrite.TakeDamage(ent, self.Owner, ent:Health(), force)
elseif ent.HPWRagdolledEnt then
HpwRewrite.TakeDamage(ent, self.Owner, ent.MaxPenetration, force)
end
end
end
HpwRewrite:AddSpell("Avada kedavra", Spell) | mit |
StephenZhuang/qdkpv2 | QDKP_V2/QDKP2_Config/Libs/AceTimer-3.0.lua | 2 | 9730 | --- **AceTimer-3.0** provides a central facility for registering timers.
-- AceTimer supports one-shot timers and repeating timers. All timers are stored in an efficient
-- data structure that allows easy dispatching and fast rescheduling. Timers can be registered
-- or canceled at any time, even from within a running timer, without conflict or large overhead.\\
-- AceTimer is currently limited to firing timers at a frequency of 0.01s. This constant may change
-- in the future, but for now it's required as animations with lower frequencies are buggy.
--
-- All `:Schedule` functions will return a handle to the current timer, which you will need to store if you
-- need to cancel the timer you just registered.
--
-- **AceTimer-3.0** can be embeded into your addon, either explicitly by calling AceTimer:Embed(MyAddon) or by
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
-- and can be accessed directly, without having to explicitly call AceTimer itself.\\
-- It is recommended to embed AceTimer, otherwise you'll have to specify a custom `self` on all calls you
-- make into AceTimer.
-- @class file
-- @name AceTimer-3.0
-- @release $Id: AceTimer-3.0.lua 1079 2013-02-17 19:56:06Z funkydude $
local MAJOR, MINOR = "AceTimer-3.0", 16 -- Bump minor on changes
local AceTimer, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceTimer then return end -- No upgrade needed
AceTimer.frame = AceTimer.frame or CreateFrame("Frame", "AceTimer30Frame") -- Animation parent
AceTimer.inactiveTimers = AceTimer.inactiveTimers or {} -- Timer recycling storage
AceTimer.activeTimers = AceTimer.activeTimers or {} -- Active timer list
-- Lua APIs
local type, unpack, next, error, pairs, tostring, select = type, unpack, next, error, pairs, tostring, select
-- Upvalue our private data
local inactiveTimers = AceTimer.inactiveTimers
local activeTimers = AceTimer.activeTimers
local function OnFinished(self)
local id = self.id
if type(self.func) == "string" then
-- We manually set the unpack count to prevent issues with an arg set that contains nil and ends with nil
-- e.g. local t = {1, 2, nil, 3, nil} print(#t) will result in 2, instead of 5. This fixes said issue.
self.object[self.func](self.object, unpack(self.args, 1, self.argsCount))
else
self.func(unpack(self.args, 1, self.argsCount))
end
-- If the id is different it means that the timer was already cancelled
-- and has been used to create a new timer during the OnFinished callback.
if not self.looping and id == self.id then
activeTimers[self.id] = nil
self.args = nil
inactiveTimers[self] = true
end
end
local function new(self, loop, func, delay, ...)
local timer = next(inactiveTimers)
if timer then
inactiveTimers[timer] = nil
else
local anim = AceTimer.frame:CreateAnimationGroup()
timer = anim:CreateAnimation()
timer:SetScript("OnFinished", OnFinished)
end
-- Very low delays cause the animations to fail randomly.
-- A limited resolution of 0.01 seems reasonable.
if delay < 0.01 then
delay = 0.01
end
timer.object = self
timer.func = func
timer.looping = loop
timer.args = {...}
timer.argsCount = select("#", ...)
local anim = timer:GetParent()
if loop then
anim:SetLooping("REPEAT")
else
anim:SetLooping("NONE")
end
timer:SetDuration(delay)
local id = tostring(timer.args)
timer.id = id
activeTimers[id] = timer
anim:Play()
return id
end
--- Schedule a new one-shot timer.
-- The timer will fire once in `delay` seconds, unless canceled before.
-- @param callback Callback function for the timer pulse (funcref or method name).
-- @param delay Delay for the timer, in seconds.
-- @param ... An optional, unlimited amount of arguments to pass to the callback function.
-- @usage
-- MyAddOn = LibStub("AceAddon-3.0"):NewAddon("MyAddOn", "AceTimer-3.0")
--
-- function MyAddOn:OnEnable()
-- self:ScheduleTimer("TimerFeedback", 5)
-- end
--
-- function MyAddOn:TimerFeedback()
-- print("5 seconds passed")
-- end
function AceTimer:ScheduleTimer(func, delay, ...)
if not func or not delay then
error(MAJOR..": ScheduleTimer(callback, delay, args...): 'callback' and 'delay' must have set values.", 2)
end
if type(func) == "string" then
if type(self) ~= "table" then
error(MAJOR..": ScheduleTimer(callback, delay, args...): 'self' - must be a table.", 2)
elseif not self[func] then
error(MAJOR..": ScheduleTimer(callback, delay, args...): Tried to register '"..func.."' as the callback, but it doesn't exist in the module.", 2)
end
end
return new(self, nil, func, delay, ...)
end
--- Schedule a repeating timer.
-- The timer will fire every `delay` seconds, until canceled.
-- @param callback Callback function for the timer pulse (funcref or method name).
-- @param delay Delay for the timer, in seconds.
-- @param ... An optional, unlimited amount of arguments to pass to the callback function.
-- @usage
-- MyAddOn = LibStub("AceAddon-3.0"):NewAddon("MyAddOn", "AceTimer-3.0")
--
-- function MyAddOn:OnEnable()
-- self.timerCount = 0
-- self.testTimer = self:ScheduleRepeatingTimer("TimerFeedback", 5)
-- end
--
-- function MyAddOn:TimerFeedback()
-- self.timerCount = self.timerCount + 1
-- print(("%d seconds passed"):format(5 * self.timerCount))
-- -- run 30 seconds in total
-- if self.timerCount == 6 then
-- self:CancelTimer(self.testTimer)
-- end
-- end
function AceTimer:ScheduleRepeatingTimer(func, delay, ...)
if not func or not delay then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): 'callback' and 'delay' must have set values.", 2)
end
if type(func) == "string" then
if type(self) ~= "table" then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): 'self' - must be a table.", 2)
elseif not self[func] then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): Tried to register '"..func.."' as the callback, but it doesn't exist in the module.", 2)
end
end
return new(self, true, func, delay, ...)
end
--- Cancels a timer with the given id, registered by the same addon object as used for `:ScheduleTimer`
-- Both one-shot and repeating timers can be canceled with this function, as long as the `id` is valid
-- and the timer has not fired yet or was canceled before.
-- @param id The id of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer`
function AceTimer:CancelTimer(id)
local timer = activeTimers[id]
if not timer then return false end
local anim = timer:GetParent()
anim:Stop()
activeTimers[id] = nil
timer.args = nil
inactiveTimers[timer] = true
return true
end
--- Cancels all timers registered to the current addon object ('self')
function AceTimer:CancelAllTimers()
for k,v in pairs(activeTimers) do
if v.object == self then
AceTimer.CancelTimer(self, k)
end
end
end
--- Returns the time left for a timer with the given id, registered by the current addon object ('self').
-- This function will return 0 when the id is invalid.
-- @param id The id of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer`
-- @return The time left on the timer.
function AceTimer:TimeLeft(id)
local timer = activeTimers[id]
if not timer then return 0 end
return timer:GetDuration() - timer:GetElapsed()
end
-- ---------------------------------------------------------------------
-- Upgrading
-- Upgrade from old hash-bucket based timers to animation timers
if oldminor and oldminor < 10 then
-- disable old timer logic
AceTimer.frame:SetScript("OnUpdate", nil)
AceTimer.frame:SetScript("OnEvent", nil)
AceTimer.frame:UnregisterAllEvents()
-- convert timers
for object,timers in pairs(AceTimer.selfs) do
for handle,timer in pairs(timers) do
if type(timer) == "table" and timer.callback then
local id
if timer.delay then
id = AceTimer.ScheduleRepeatingTimer(timer.object, timer.callback, timer.delay, timer.arg)
else
id = AceTimer.ScheduleTimer(timer.object, timer.callback, timer.when - GetTime(), timer.arg)
end
-- change id to the old handle
local t = activeTimers[id]
activeTimers[id] = nil
activeTimers[handle] = t
t.id = handle
end
end
end
AceTimer.selfs = nil
AceTimer.hash = nil
AceTimer.debug = nil
elseif oldminor and oldminor < 13 then
for handle, id in pairs(AceTimer.hashCompatTable) do
local t = activeTimers[id]
if t then
activeTimers[id] = nil
activeTimers[handle] = t
t.id = handle
end
end
AceTimer.hashCompatTable = nil
end
-- upgrade existing timers to the latest OnFinished
for timer in pairs(inactiveTimers) do
timer:SetScript("OnFinished", OnFinished)
end
for _,timer in pairs(activeTimers) do
timer:SetScript("OnFinished", OnFinished)
end
-- ---------------------------------------------------------------------
-- Embed handling
AceTimer.embeds = AceTimer.embeds or {}
local mixins = {
"ScheduleTimer", "ScheduleRepeatingTimer",
"CancelTimer", "CancelAllTimers",
"TimeLeft"
}
function AceTimer:Embed(target)
AceTimer.embeds[target] = true
for _,v in pairs(mixins) do
target[v] = AceTimer[v]
end
return target
end
-- AceTimer:OnEmbedDisable(target)
-- target (object) - target object that AceTimer is embedded in.
--
-- cancel all timers registered for the object
function AceTimer:OnEmbedDisable(target)
target:CancelAllTimers()
end
for addon in pairs(AceTimer.embeds) do
AceTimer:Embed(addon)
end
| gpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/endor/weathered_panshee_shaman.lua | 2 | 1116 | weathered_panshee_shaman = Creature:new {
objectName = "@mob/creature_names:weathered_panshee_shaman",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "panshee_tribe",
faction = "panshee_tribe",
level = 27,
chanceHit = 0.37,
damageMin = 260,
damageMax = 270,
baseXp = 2730,
baseHAM = 8100,
baseHAMmax = 9900,
armor = 0,
resists = {30,30,30,30,30,30,30,30,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_ewok_m_03.iff",
"object/mobile/dressed_ewok_m_07.iff",
"object/mobile/dressed_ewok_m_11.iff"},
lootGroups = {
{
groups = {
{group = "ewok", chance = 9000000},
{group = "wearables_uncommon", chance = 1000000},
},
lootChance = 1540000
}
},
weapons = {"ewok_weapons"},
conversationTemplate = "",
attacks = merge(riflemanmaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(weathered_panshee_shaman, "weathered_panshee_shaman")
| agpl-3.0 |
excessive/obtuse-tanuki | libs/hump/class.lua | 21 | 2960 | --[[
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 not to[k] 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
local inc = class.__includes or {}
if getmetatable(inc) then inc = {inc} end
for _, other in ipairs(inc) do
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 |
LeMagnesium/minetest-minetestforfun-server | mods/plantlife_modpack/flowers_plus/init.lua | 8 | 14057 | local S = biome_lib.intllib
-- This file supplies a few additional plants and some related crafts
-- for the plantlife modpack. Last revision: 2013-04-24
flowers_plus = {}
local SPAWN_DELAY = 1000
local SPAWN_CHANCE = 200
local flowers_seed_diff = 329
local lilies_max_count = 320
local lilies_rarity = 33
local seaweed_max_count = 320
local seaweed_rarity = 33
local sunflowers_max_count = 10
local sunflowers_rarity = 25
-- register the various rotations of waterlilies
local lilies_list = {
{ nil , nil , 1 },
{ "225", "22.5" , 2 },
{ "45" , "45" , 3 },
{ "675", "67.5" , 4 },
{ "s1" , "small_1" , 5 },
{ "s2" , "small_2" , 6 },
{ "s3" , "small_3" , 7 },
{ "s4" , "small_4" , 8 },
}
for i in ipairs(lilies_list) do
local deg1 = ""
local deg2 = ""
local lily_groups = {snappy = 3,flammable=2,flower=1}
if lilies_list[i][1] ~= nil then
deg1 = "_"..lilies_list[i][1]
deg2 = "_"..lilies_list[i][2]
lily_groups = { snappy = 3,flammable=2,flower=1, not_in_creative_inventory=1 }
end
minetest.register_node(":flowers:waterlily"..deg1, {
description = S("Waterlily"),
drawtype = "nodebox",
tiles = {
"flowers_waterlily"..deg2..".png",
"flowers_waterlily"..deg2..".png^[transformFY"
},
inventory_image = "flowers_waterlily.png",
wield_image = "flowers_waterlily.png",
sunlight_propagates = true,
paramtype = "light",
paramtype2 = "facedir",
walkable = false,
groups = lily_groups,
sounds = default.node_sound_leaves_defaults(),
selection_box = {
type = "fixed",
fixed = { -0.4, -0.5, -0.4, 0.4, -0.45, 0.4 },
},
node_box = {
type = "fixed",
fixed = { -0.5, -0.49, -0.5, 0.5, -0.49, 0.5 },
},
buildable_to = true,
liquids_pointable = true,
drop = "flowers:waterlily",
on_place = function(itemstack, placer, pointed_thing)
local keys=placer:get_player_control()
local pt = pointed_thing
local place_pos = nil
local top_pos = {x=pt.under.x, y=pt.under.y+1, z=pt.under.z}
local under_node = minetest.get_node(pt.under)
local above_node = minetest.get_node(pt.above)
local top_node = minetest.get_node(top_pos)
if biome_lib:get_nodedef_field(under_node.name, "buildable_to") then
if under_node.name ~= "default:water_source" then
place_pos = pt.under
elseif top_node.name ~= "default:water_source"
and biome_lib:get_nodedef_field(top_node.name, "buildable_to") then
place_pos = top_pos
else
return
end
elseif biome_lib:get_nodedef_field(above_node.name, "buildable_to") then
place_pos = pt.above
end
if place_pos and not minetest.is_protected(place_pos, placer:get_player_name()) then
local nodename = "default:cobble" -- if this block appears, something went....wrong :-)
if not keys["sneak"] then
local node = minetest.get_node(pt.under)
local waterlily = math.random(1,8)
if waterlily == 1 then
nodename = "flowers:waterlily"
elseif waterlily == 2 then
nodename = "flowers:waterlily_225"
elseif waterlily == 3 then
nodename = "flowers:waterlily_45"
elseif waterlily == 4 then
nodename = "flowers:waterlily_675"
elseif waterlily == 5 then
nodename = "flowers:waterlily_s1"
elseif waterlily == 6 then
nodename = "flowers:waterlily_s2"
elseif waterlily == 7 then
nodename = "flowers:waterlily_s3"
elseif waterlily == 8 then
nodename = "flowers:waterlily_s4"
end
minetest.set_node(place_pos, {name = nodename, param2 = math.random(0,3) })
else
local fdir = minetest.dir_to_facedir(placer:get_look_dir())
minetest.set_node(place_pos, {name = "flowers:waterlily", param2 = fdir})
end
if not biome_lib.expect_infinite_stacks then
itemstack:take_item()
end
return itemstack
end
end,
})
end
local algae_list = { {nil}, {2}, {3}, {4} }
for i in ipairs(algae_list) do
local num = ""
local algae_groups = {snappy = 3,flammable=2,flower=1}
if algae_list[i][1] ~= nil then
num = "_"..algae_list[i][1]
algae_groups = { snappy = 3,flammable=2,flower=1, not_in_creative_inventory=1 }
end
minetest.register_node(":flowers:seaweed"..num, {
description = S("Seaweed"),
drawtype = "nodebox",
tiles = {
"flowers_seaweed"..num..".png",
"flowers_seaweed"..num..".png^[transformFY"
},
inventory_image = "flowers_seaweed_2.png",
wield_image = "flowers_seaweed_2.png",
sunlight_propagates = true,
paramtype = "light",
paramtype2 = "facedir",
walkable = false,
groups = algae_groups,
sounds = default.node_sound_leaves_defaults(),
selection_box = {
type = "fixed",
fixed = { -0.4, -0.5, -0.4, 0.4, -0.45, 0.4 },
},
node_box = {
type = "fixed",
fixed = { -0.5, -0.49, -0.5, 0.5, -0.49, 0.5 },
},
buildable_to = true,
liquids_pointable = true,
drop = "flowers:seaweed",
on_place = function(itemstack, placer, pointed_thing)
local keys=placer:get_player_control()
local pt = pointed_thing
local place_pos = nil
local top_pos = {x=pt.under.x, y=pt.under.y+1, z=pt.under.z}
local under_node = minetest.get_node(pt.under)
local above_node = minetest.get_node(pt.above)
local top_node = minetest.get_node(top_pos)
if biome_lib:get_nodedef_field(under_node.name, "buildable_to") then
if under_node.name ~= "default:water_source" then
place_pos = pt.under
elseif top_node.name ~= "default:water_source"
and biome_lib:get_nodedef_field(top_node.name, "buildable_to") then
place_pos = top_pos
else
return
end
elseif biome_lib:get_nodedef_field(above_node.name, "buildable_to") then
place_pos = pt.above
end
if not minetest.is_protected(place_pos, placer:get_player_name()) then
local nodename = "default:cobble" -- :D
if not keys["sneak"] then
--local node = minetest.get_node(pt.under)
local seaweed = math.random(1,4)
if seaweed == 1 then
nodename = "flowers:seaweed"
elseif seaweed == 2 then
nodename = "flowers:seaweed_2"
elseif seaweed == 3 then
nodename = "flowers:seaweed_3"
elseif seaweed == 4 then
nodename = "flowers:seaweed_4"
end
minetest.set_node(place_pos, {name = nodename, param2 = math.random(0,3) })
else
local fdir = minetest.dir_to_facedir(placer:get_look_dir())
minetest.set_node(place_pos, {name = "flowers:seaweed", param2 = fdir})
end
if not biome_lib.expect_infinite_stacks then
itemstack:take_item()
end
return itemstack
end
end,
})
end
local box = {
type="fixed",
fixed = { { -0.2, -0.5, -0.2, 0.2, 0.5, 0.2 } },
}
local sunflower_drop = "farming:seed_wheat"
if minetest.registered_items["farming:seed_spelt"] then
sunflower_drop = "farming:seed_spelt"
end
minetest.register_node(":flowers:sunflower", {
description = "Sunflower",
drawtype = "mesh",
paramtype = "light",
paramtype2 = "facedir",
inventory_image = "flowers_sunflower_inv.png",
mesh = "flowers_sunflower.obj",
tiles = { "flowers_sunflower.png" },
walkable = false,
buildable_to = true,
is_ground_content = true,
groups = { dig_immediate=3, flora=1, flammable=3 },
sounds = default.node_sound_leaves_defaults(),
selection_box = box,
collision_box = box,
drop = {
max_items = 1,
items = {
{items = {sunflower_drop}, rarity = 8},
{items = {"flowers:sunflower"}},
}
}
})
local extra_aliases = {
"waterlily",
"waterlily_225",
"waterlily_45",
"waterlily_675",
"seaweed"
}
for i in ipairs(extra_aliases) do
local flower = extra_aliases[i]
minetest.register_alias("flowers:flower_"..flower, "flowers:"..flower)
end
minetest.register_alias( "trunks:lilypad" , "flowers:waterlily_s1" )
minetest.register_alias( "along_shore:lilypads_1" , "flowers:waterlily_s1" )
minetest.register_alias( "along_shore:lilypads_2" , "flowers:waterlily_s2" )
minetest.register_alias( "along_shore:lilypads_3" , "flowers:waterlily_s3" )
minetest.register_alias( "along_shore:lilypads_4" , "flowers:waterlily_s4" )
minetest.register_alias( "along_shore:pondscum_1" , "flowers:seaweed" )
minetest.register_alias( "along_shore:seaweed_1" , "flowers:seaweed" )
minetest.register_alias( "along_shore:seaweed_2" , "flowers:seaweed_2" )
minetest.register_alias( "along_shore:seaweed_3" , "flowers:seaweed_3" )
minetest.register_alias( "along_shore:seaweed_4" , "flowers:seaweed_4" )
-- ongen registrations
flowers_plus.grow_waterlily = function(pos)
local right_here = {x=pos.x, y=pos.y+1, z=pos.z}
for i in ipairs(lilies_list) do
local chance = math.random(1,8)
local ext = ""
local num = lilies_list[i][3]
if lilies_list[i][1] ~= nil then
ext = "_"..lilies_list[i][1]
end
if chance == num then
minetest.set_node(right_here, {name="flowers:waterlily"..ext, param2=math.random(0,3)})
end
end
end
biome_lib:register_generate_plant({
surface = {"default:water_source"},
max_count = lilies_max_count,
rarity = lilies_rarity,
min_elevation = 1,
max_elevation = 40,
near_nodes = {"default:dirt_with_grass"},
near_nodes_size = 4,
near_nodes_vertical = 1,
near_nodes_count = 1,
plantlife_limit = -0.9,
temp_max = -0.22,
temp_min = 0.22,
},
flowers_plus.grow_waterlily
)
flowers_plus.grow_seaweed = function(pos)
local right_here = {x=pos.x, y=pos.y+1, z=pos.z}
minetest.set_node(right_here, {name="along_shore:seaweed_"..math.random(1,4), param2=math.random(1,3)})
end
biome_lib:register_generate_plant({
surface = {"default:water_source"},
max_count = seaweed_max_count,
rarity = seaweed_rarity,
min_elevation = 1,
max_elevation = 40,
near_nodes = {"default:dirt_with_grass"},
near_nodes_size = 4,
near_nodes_vertical = 1,
near_nodes_count = 1,
plantlife_limit = -0.9,
},
flowers_plus.grow_seaweed
)
-- seaweed at beaches
-- MM: not satisfied with it, but IMHO some beaches should have some algae
biome_lib:register_generate_plant({
surface = {"default:water_source"},
max_count = seaweed_max_count,
rarity = seaweed_rarity,
min_elevation = 1,
max_elevation = 40,
near_nodes = {"default:sand"},
near_nodes_size = 1,
near_nodes_vertical = 0,
near_nodes_count = 3,
plantlife_limit = -0.9,
temp_max = -0.64, -- MM: more or less random values, just to make sure it's not everywhere
temp_min = -0.22, -- MM: more or less random values, just to make sure it's not everywhere
},
flowers_plus.grow_seaweed
)
biome_lib:register_generate_plant({
surface = {"default:sand"},
max_count = seaweed_max_count*2,
rarity = seaweed_rarity/2,
min_elevation = 1,
max_elevation = 40,
near_nodes = {"default:water_source"},
near_nodes_size = 1,
near_nodes_vertical = 0,
near_nodes_count = 3,
plantlife_limit = -0.9,
temp_max = -0.64, -- MM: more or less random values, just to make sure it's not everywhere
temp_min = -0.22, -- MM: more or less random values, just to make sure it's not everywhere
},
flowers_plus.grow_seaweed
)
biome_lib:register_generate_plant({
surface = {"default:dirt_with_grass"},
avoid_nodes = { "flowers:sunflower" },
max_count = sunflowers_max_count,
rarity = sunflowers_rarity,
min_elevation = 0,
plantlife_limit = -0.9,
temp_max = 0.53,
random_facedir = {0,3},
},
"flowers:sunflower"
)
-- spawn ABM registrations
biome_lib:spawn_on_surfaces({
spawn_delay = SPAWN_DELAY/2,
spawn_plants = {
"flowers:waterlily",
"flowers:waterlily_225",
"flowers:waterlily_45",
"flowers:waterlily_675",
"flowers:waterlily_s1",
"flowers:waterlily_s2",
"flowers:waterlily_s3",
"flowers:waterlily_s4"
},
avoid_radius = 2.5,
spawn_chance = SPAWN_CHANCE*4,
spawn_surfaces = {"default:water_source"},
avoid_nodes = {"group:flower", "group:flora" },
seed_diff = flowers_seed_diff,
light_min = 9,
depth_max = 2,
random_facedir = {0,3}
})
biome_lib:spawn_on_surfaces({
spawn_delay = SPAWN_DELAY*2,
spawn_plants = {"flowers:seaweed"},
spawn_chance = SPAWN_CHANCE*2,
spawn_surfaces = {"default:water_source"},
avoid_nodes = {"group:flower", "group:flora"},
seed_diff = flowers_seed_diff,
light_min = 4,
light_max = 10,
neighbors = {"default:dirt_with_grass"},
facedir = 1
})
biome_lib:spawn_on_surfaces({
spawn_delay = SPAWN_DELAY*2,
spawn_plants = {"flowers:seaweed"},
spawn_chance = SPAWN_CHANCE*2,
spawn_surfaces = {"default:dirt_with_grass"},
avoid_nodes = {"group:flower", "group:flora" },
seed_diff = flowers_seed_diff,
light_min = 4,
light_max = 10,
neighbors = {"default:water_source"},
ncount = 1,
facedir = 1
})
biome_lib:spawn_on_surfaces({
spawn_delay = SPAWN_DELAY*2,
spawn_plants = {"flowers:seaweed"},
spawn_chance = SPAWN_CHANCE*2,
spawn_surfaces = {"default:stone"},
avoid_nodes = {"group:flower", "group:flora" },
seed_diff = flowers_seed_diff,
light_min = 4,
light_max = 10,
neighbors = {"default:water_source"},
ncount = 6,
facedir = 1
})
biome_lib:spawn_on_surfaces({
spawn_delay = SPAWN_DELAY*2,
spawn_plants = {"flowers:sunflower"},
spawn_chance = SPAWN_CHANCE*2,
spawn_surfaces = {"default:dirt_with_grass"},
avoid_nodes = {"group:flower", "flowers:sunflower"},
seed_diff = flowers_seed_diff,
light_min = 11,
light_max = 14,
min_elevation = 0,
plantlife_limit = -0.9,
temp_max = 0.53,
random_facedir = {0,3},
avoid_radius = 5
})
-- Cotton plants are now provided by the default "farming" mod.
-- old cotton plants -> farming cotton stage 8
-- cotton wads -> string (can be crafted into wool blocks)
-- potted cotton plants -> potted white dandelions
minetest.register_alias("flowers:cotton_plant", "farming:cotton_8")
minetest.register_alias("flowers:flower_cotton", "farming:cotton_8")
minetest.register_alias("flowers:flower_cotton_pot", "flowers:potted_dandelion_white")
minetest.register_alias("flowers:potted_cotton_plant", "flowers:potted_dandelion_white")
minetest.register_alias("flowers:cotton", "farming:string")
minetest.register_alias("flowers:cotton_wad", "farming:string")
minetest.register_alias("sunflower:sunflower", "flowers:sunflower")
minetest.log("action", S("[Flowers] Loaded."))
| unlicense |
amirhoseinkarimi2233/uzzbot | plugins/steam.lua | 645 | 2117 | -- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI
do
local BASE_URL = 'http://store.steampowered.com/api/appdetails/'
local DESC_LENTH = 200
local function unescape(str)
str = string.gsub( str, '<', '<' )
str = string.gsub( str, '>', '>' )
str = string.gsub( str, '"', '"' )
str = string.gsub( str, ''', "'" )
str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end )
str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end )
str = string.gsub( str, '&', '&' ) -- Be sure to do this after all others
return str
end
local function get_steam_data (appid)
local url = BASE_URL
url = url..'?appids='..appid
url = url..'&cc=us'
local res,code = http.request(url)
if code ~= 200 then return nil end
local data = json:decode(res)[appid].data
return data
end
local function price_info (data)
local price = '' -- If no data is empty
if data then
local initial = data.initial
local final = data.final or data.initial
local min = math.min(data.initial, data.final)
price = tostring(min/100)
if data.discount_percent and initial ~= final then
price = price..data.currency..' ('..data.discount_percent..'% OFF)'
end
price = price..' (US)'
end
return price
end
local function send_steam_data(data, receiver)
local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...'
local title = data.name
local price = price_info(data.price_overview)
local text = title..' '..price..'\n'..description
local image_url = data.header_image
local cb_extra = {
receiver = receiver,
url = image_url
}
send_msg(receiver, text, send_photo_from_url_callback, cb_extra)
end
local function run(msg, matches)
local appid = matches[1]
local data = get_steam_data(appid)
local receiver = get_receiver(msg)
send_steam_data(data, receiver)
end
return {
description = "Grabs Steam info for Steam links.",
usage = "",
patterns = {
"http://store.steampowered.com/app/([0-9]+)",
},
run = run
}
end
| gpl-2.0 |
fantajeon/TripletNet | generate_shoes_pair.lua | 1 | 4203 | require 'nn'
require 'csvigo'
require 'cudnn'
require 'properties_util'
require 'xlua'
local debugger = require 'fb.debugger'
torch.setdefaulttensortype('torch.FloatTensor')
--filepath = './properties/excel_1459334593242.shoes.train.csv'
--pair_output_filename = 'shoes_pair.train.csv'
filepath = './properties/excel_1459334593242.shoes.valid.csv'
pair_output_filename = 'shoes_pair.valid.csv'
category_name = 'shoes'
db = torch.Tensor():type( 'torch.CudaTensor' )
local loss = nn.PairwiseDistance(1)
loss:cuda()
loss:evaluate()
function distance(X, Y)
--local off = torch.cmin(X:eq(0):sum(2), Y:eq(0):sum(2))
--local hd = X:eq(Y):sum(2)
--local d = (hd- off ):add( -17 ):neg()
--return d
return X:ne(Y):sum(2)
end
function getKnn(Data, anchor_index, k, threshold_distance)
local X = Data.data.anchor_name_list[anchor_index].properties
local batchX = torch.repeatTensor(X, db:size(1), 1):type( 'torch.CudaTensor' )
collectgarbage()
batchX:cuda()
local bucket = {}
local d = distance(batchX, db)
for j=1,d:size(1) do
table.insert(bucket,{index=j,value=d[j][1]})
end
table.sort(bucket, function(a, b)
return a.value < b.value
end )
local result = {}
for i=1,#bucket do
index = bucket[i].index
if #result >= k then
break
end
if bucket[i].index ~= anchor_index then
if bucket[i].value < threshold_distance then
table.insert(result, {index, bucket[i].value} )
end
end
end
local neg_result = {}
for i=#bucket,k+1,-500 do
if #neg_result >= k or bucket[i].value < 3 then
break
end
index = bucket[i].index
table.insert(neg_result, {index, bucket[i].value} )
end
return result, neg_result
end
function LoadData(filepath)
local Data = {data={},imagepool={}}
local positive_pairs = {}
local negative_pairs = {}
local anchor_name_list = {}
local ImagePool = {}
local count_imagepool = 0
local ImagePoolByName = {}
label_pairs = csvigo.load( {path=filepath, mode='large'} )
--for i=1,#label_pairs,1000 do
for i=1,#label_pairs do
local isbreak = (function()
m = label_pairs[i]
local a_name, box, properties = ParsingShoes(m)
--print (a_name, box, properties)
if a_name == nil then
return ""
end
table.insert(anchor_name_list, {filename=a_name, box=box, properties=properties})
return ""
end)()
if isbreak == "break" then
break
end
print (i, #label_pairs, 100.0*(i/#label_pairs), "anchor", #anchor_name_list)
end
print("loaded: " .. #anchor_name_list)
Data.data.anchor_name_list = anchor_name_list
Data.Resolution = {3,299,299}
print ("Data Size:", #Data.data.anchor_name_list)
return Data
end
Data = LoadData(filepath)
function build_db()
db_size = #Data.data.anchor_name_list
local feature_dim = Data.data.anchor_name_list[1].properties:size(1)
local nsz = torch.LongStorage(2)
nsz[1] = db_size
nsz[2] = feature_dim
db:resize(nsz)
for i=1,db_size do
local z = Data.data.anchor_name_list[i].properties
db[i]:copy(z)
end
db:cuda()
end
print ('building db....')
build_db()
f_pair_out = torch.DiskFile( pair_output_filename, "w")
for i=1,#Data.data.anchor_name_list do
local a_name = Data.data.anchor_name_list[i].filename
result, negresult = getKnn(Data, i, 50, 1)
for j=1,#result do
local p_name = Data.data.anchor_name_list[ result[j][1] ].filename
str = string.format( '%s,%s,%s,1,%s\n', category_name, a_name, p_name, result[j][2])
f_pair_out:writeString( str )
end
for j=1,#negresult do
local p_name = Data.data.anchor_name_list[ negresult[j][1] ].filename
str = string.format( '%s,%s,%s,0,%s\n', category_name, a_name, p_name, negresult[j][2])
f_pair_out:writeString( str )
end
xlua.progress( i, #Data.data.anchor_name_list )
end
f_pair_out:close()
| mit |
sbouchex/domoticz | dzVents/runtime/Variable.lua | 6 | 2343 | local Time = require('Time')
local TimedCommand = require('TimedCommand')
local evenItemIdentifier = require('eventItemIdentifier')
local function Variable(domoticz, data)
local self = {
['value'] = data.data.value,
['name'] = data.name,
['type'] = data.variableType,
['changed'] = data.changed,
['id'] = data.id,
['idx'] = data.id,
['lastUpdate'] = Time(data.lastUpdate),
}
evenItemIdentifier.setType(self, 'isVariable', domoticz.BASETYPE_VARIABLE, data.name)
if (data.variableType == 'float' or data.variableType == 'integer') then
-- actually this isn't needed as value is already in the
-- proper type
-- just for backward compatibility
self['nValue'] = data.data.value
end
function self.dump( filename )
domoticz.logObject(self, filename, 'variable')
end
function self.dumpSelection( selection )
domoticz.utils.dumpSelection(self, ( selection or 'attributes' ))
end
if (data.variableType == 'date') then
local d, mon, y = string.match(data.data.value, "(%d+)[%p](%d+)[%p](%d+)")
local date = y .. '-' .. mon .. '-' .. d .. ' 00:00:00'
self['date'] = Time(date)
end
if (data.variableType == 'time') then
local now = os.date('*t')
local time = tostring(now.year) ..
'-' .. tostring(now.month) ..
'-' .. tostring(now.day) ..
' ' .. data.data.value ..
':00'
self['time'] = Time(time)
end
-- send an update to domoticz
function self.set(value)
if self.type == 'integer' then
value = math.floor(value)
elseif value == nil then
value = ''
end
-- return TimedCommand(domoticz, 'Variable:' .. data.name, tostring(value), 'variable')
return TimedCommand(domoticz, 'Variable', {
idx = data.id,
_trigger = true,
value = tostring(value)
}, 'variable')
end
function self.cancelQueuedCommands()
domoticz.sendCommand('Cancel', {
type = 'variable',
idx = data.id
})
end
function self.rename(newName)
local newValue = domoticz.utils.urlEncode(self.value)
if self.type == 'integer' then
newValue = math.floor(self.value)
end
local url = domoticz.settings['Domoticz url'] .. '/json.htm?type=command¶m=updateuservariable' ..
'&idx=' .. data.id ..
'&vname=' .. domoticz.utils.urlEncode(newName) ..
'&vtype=' .. self.type ..
'&vvalue=' .. newValue
domoticz.openURL(url)
end
return self
end
return Variable
| gpl-3.0 |
LeMagnesium/minetest-minetestforfun-server | mods/homedecor_modpack/homedecor/lighting.lua | 7 | 16989 | -- This file supplies glowlights
local dirs1 = { 20, 23, 22, 21 }
local dirs2 = { 9, 18, 7, 12 }
local S = homedecor.gettext
local colors = {"yellow","white"}
for i in ipairs(colors) do
local color = colors[i]
minetest.register_abm({
nodenames = { "homedecor:glowlight_thin_"..color },
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
minetest.set_node(pos, {name = "homedecor:glowlight_quarter_"..color, param2 = 20})
end,
})
minetest.register_abm({
nodenames = { "homedecor:glowlight_thick_"..color },
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
minetest.set_node(pos, {name = "homedecor:glowlight_half_"..color, param2 = 20})
end,
})
minetest.register_abm({
nodenames = { "homedecor:glowlight_thin_"..color.."_wall" },
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local fdir = node.param2 or 0
local nfdir = dirs2[fdir+1]
minetest.set_node(pos, {name = "homedecor:glowlight_quarter_"..color, param2 = nfdir})
end,
})
minetest.register_abm({
nodenames = { "homedecor:glowlight_thick_"..color.."_wall" },
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local fdir = node.param2 or 0
local nfdir = dirs2[fdir+1]
minetest.set_node(pos, {name = "homedecor:glowlight_half_"..color, param2 = nfdir})
end,
})
minetest.register_abm({
nodenames = { "homedecor:glowlight_small_cube_"..color.."_ceiling" },
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
minetest.set_node(pos, {name = "homedecor:glowlight_small_cube_"..color, param2 = 20})
end,
})
local glowlight_nodebox = {
half = homedecor.nodebox.slab_y(1/2),
quarter = homedecor.nodebox.slab_y(1/4),
small_cube = {
type = "fixed",
fixed = { -0.25, -0.5, -0.25, 0.25, 0, 0.25 }
},
}
homedecor.register("glowlight_half_"..color, {
description = S("Thick Glowlight ("..color..")"),
tiles = {
"homedecor_glowlight_"..color.."_top.png",
"homedecor_glowlight_"..color.."_bottom.png",
"homedecor_glowlight_thick_"..color.."_sides.png",
"homedecor_glowlight_thick_"..color.."_sides.png",
"homedecor_glowlight_thick_"..color.."_sides.png",
"homedecor_glowlight_thick_"..color.."_sides.png"
},
selection_box = glowlight_nodebox.half,
node_box = glowlight_nodebox.half,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX,
sounds = default.node_sound_glass_defaults(),
on_place = minetest.rotate_node
})
homedecor.register("glowlight_quarter_"..color, {
description = S("Thin Glowlight ("..color..")"),
tiles = {
"homedecor_glowlight_"..color.."_top.png",
"homedecor_glowlight_"..color.."_bottom.png",
"homedecor_glowlight_thin_"..color.."_sides.png",
"homedecor_glowlight_thin_"..color.."_sides.png",
"homedecor_glowlight_thin_"..color.."_sides.png",
"homedecor_glowlight_thin_"..color.."_sides.png"
},
selection_box = glowlight_nodebox.quarter,
node_box = glowlight_nodebox.quarter,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-1,
sounds = default.node_sound_glass_defaults(),
on_place = minetest.rotate_node
})
-- Glowlight "cubes"
homedecor.register("glowlight_small_cube_"..color, {
description = S("Small Glowlight Cube ("..color..")"),
tiles = {
"homedecor_glowlight_cube_"..color.."_tb.png",
"homedecor_glowlight_cube_"..color.."_tb.png",
"homedecor_glowlight_cube_"..color.."_sides.png",
"homedecor_glowlight_cube_"..color.."_sides.png",
"homedecor_glowlight_cube_"..color.."_sides.png",
"homedecor_glowlight_cube_"..color.."_sides.png"
},
selection_box = glowlight_nodebox.small_cube,
node_box = glowlight_nodebox.small_cube,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-1,
sounds = default.node_sound_glass_defaults(),
on_place = minetest.rotate_node
})
end
homedecor.register("plasma_lamp", {
description = "Plasma Lamp",
drawtype = "glasslike_framed",
tiles = {"default_gold_block.png","homedecor_glass_face_clean.png"},
special_tiles = {
{
name="homedecor_plasma_storm.png",
animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0},
}
},
use_texture_alpha = true,
light_source = default.LIGHT_MAX - 1,
sunlight_propagates = true,
groups = {cracky=3,oddly_breakable_by_hand=3},
sounds = default.node_sound_glass_defaults(),
after_place_node = function(pos, placer, itemstack, pointed_thing)
minetest.swap_node(pos, {name = "homedecor:plasma_lamp", param2 = 255})
end
})
homedecor.register("plasma_ball", {
description = "Plasma Ball",
mesh = "homedecor_plasma_ball.obj",
tiles = {
"homedecor_generic_plastic_black.png",
{
name = "homedecor_plasma_ball_streamers.png",
animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0},
},
"homedecor_plasma_ball_glass.png"
},
inventory_image = "homedecor_plasma_ball_inv.png",
selection_box = {
type = "fixed",
fixed = { -0.1875, -0.5, -0.1875, 0.1875, 0, 0.1875 }
},
walkable = false,
use_texture_alpha = true,
light_source = default.LIGHT_MAX - 5,
sunlight_propagates = true,
groups = {cracky=3,oddly_breakable_by_hand=3},
sounds = default.node_sound_glass_defaults(),
})
local tc_cbox = {
type = "fixed",
fixed = {
{ -0.1875, -0.5, -0.1875, 0.1875, 0.375, 0.1875 },
}
}
homedecor.register("candle", {
description = S("Thick Candle"),
mesh = "homedecor_candle_thick.obj",
tiles = {
'homedecor_candle_sides.png',
{name="homedecor_candle_flame.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}},
},
inventory_image = "homedecor_candle_inv.png",
selection_box = tc_cbox,
walkable = false,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-4,
})
local c_cbox = {
type = "fixed",
fixed = {
{ -0.125, -0.5, -0.125, 0.125, 0.05, 0.125 },
}
}
homedecor.register("candle_thin", {
description = S("Thin Candle"),
mesh = "homedecor_candle_thin.obj",
tiles = {
'homedecor_candle_sides.png',
{name="homedecor_candle_flame.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}},
},
inventory_image = "homedecor_candle_thin_inv.png",
selection_box = c_cbox,
walkable = false,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-4,
})
local cs_cbox = {
type = "fixed",
fixed = {
{ -0.15625, -0.5, -0.15625, 0.15625, 0.3125, 0.15625 },
}
}
homedecor.register("candlestick_wrought_iron", {
description = S("Candlestick (wrought iron)"),
mesh = "homedecor_candlestick.obj",
tiles = {
"homedecor_candle_sides.png",
{name="homedecor_candle_flame.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}},
"homedecor_generic_metal_wrought_iron.png",
},
inventory_image = "homedecor_candlestick_wrought_iron_inv.png",
selection_box = cs_cbox,
walkable = false,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-4,
})
homedecor.register("candlestick_brass", {
description = S("Candlestick (brass)"),
mesh = "homedecor_candlestick.obj",
tiles = {
"homedecor_candle_sides.png",
{name="homedecor_candle_flame.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}},
"homedecor_generic_metal_brass.png",
},
inventory_image = "homedecor_candlestick_brass_inv.png",
selection_box = cs_cbox,
walkable = false,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-4,
})
homedecor.register("wall_sconce", {
description = S("Wall sconce"),
mesh = "homedecor_wall_sconce.obj",
tiles = {
'homedecor_candle_sides.png',
{name="homedecor_candle_flame.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}},
'homedecor_wall_sconce_back.png',
'homedecor_generic_metal_wrought_iron.png',
},
inventory_image = "homedecor_wall_sconce_inv.png",
selection_box = {
type = "fixed",
fixed = { -0.1875, -0.25, 0.3125, 0.1875, 0.25, 0.5 }
},
walkable = false,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-4,
})
local ol_cbox = {
type = "fixed",
fixed = {
{ -5/16, -8/16, -3/16, 5/16, 4/16, 3/16 },
}
}
homedecor.register("oil_lamp", {
description = S("Oil lamp (hurricane)"),
mesh = "homedecor_oil_lamp.obj",
tiles = {
"homedecor_generic_metal_brass.png",
"homedecor_generic_metal_black.png",
"homedecor_generic_metal_black.png^[colorize:#ff0000:160",
"homedecor_oil_lamp_wick.png",
"homedecor_generic_metal_black.png^[colorize:#ff0000:150",
"homedecor_oil_lamp_glass.png",
},
use_texture_alpha = true,
inventory_image = "homedecor_oil_lamp_inv.png",
selection_box = ol_cbox,
walkable = false,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-3,
sounds = default.node_sound_glass_defaults(),
})
homedecor.register("oil_lamp_tabletop", {
description = S("Oil Lamp (tabletop)"),
mesh = "homedecor_oil_lamp_tabletop.obj",
tiles = {"homedecor_oil_lamp_tabletop.png"},
inventory_image = "homedecor_oil_lamp_tabletop_inv.png",
selection_box = ol_cbox,
collision_box = ol_cbox,
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-3,
sounds = default.node_sound_glass_defaults(),
})
local gl_cbox = {
type = "fixed",
fixed = { -0.25, -0.5, -0.25, 0.25, 0.45, 0.25 },
}
minetest.register_alias("homedecor:wall_lantern", "homedecor:ground_lantern")
homedecor.register("ground_lantern", {
description = S("Ground Lantern"),
mesh = "homedecor_ground_lantern.obj",
tiles = { "homedecor_light.png", "homedecor_generic_metal_wrought_iron.png" },
use_texture_alpha = true,
inventory_image = "homedecor_ground_lantern_inv.png",
wield_image = "homedecor_ground_lantern_inv.png",
groups = {snappy=3},
light_source = 11,
selection_box = gl_cbox,
walkable = false
})
local hl_cbox = {
type = "fixed",
fixed = { -0.25, -0.5, -0.2, 0.25, 0.5, 0.5 },
}
homedecor.register("hanging_lantern", {
description = S("Hanging Lantern"),
mesh = "homedecor_hanging_lantern.obj",
tiles = { "homedecor_generic_metal_wrought_iron.png", "homedecor_light.png" },
use_texture_alpha = true,
inventory_image = "homedecor_hanging_lantern_inv.png",
wield_image = "homedecor_hanging_lantern_inv.png",
groups = {snappy=3},
light_source = 11,
selection_box = hl_cbox,
walkable = false
})
local cl_cbox = {
type = "fixed",
fixed = { -0.35, -0.45, -0.35, 0.35, 0.5, 0.35 }
}
homedecor.register("ceiling_lantern", {
drawtype = "mesh",
mesh = "homedecor_ceiling_lantern.obj",
tiles = { "homedecor_light.png", "homedecor_generic_metal_wrought_iron.png" },
use_texture_alpha = true,
inventory_image = "homedecor_ceiling_lantern_inv.png",
description = "Ceiling Lantern",
groups = {snappy=3},
light_source = 11,
selection_box = cl_cbox,
walkable = false
})
homedecor.register("lattice_lantern_large", {
description = S("Lattice lantern (large)"),
tiles = { 'homedecor_lattice_lantern_large.png' },
groups = { snappy = 3 },
light_source = default.LIGHT_MAX,
sounds = default.node_sound_glass_defaults(),
})
homedecor.register("lattice_lantern_small", {
description = S("Lattice lantern (small)"),
tiles = {
'homedecor_lattice_lantern_small_tb.png',
'homedecor_lattice_lantern_small_tb.png',
'homedecor_lattice_lantern_small_sides.png'
},
selection_box = {
type = "fixed",
fixed = { -0.25, -0.5, -0.25, 0.25, 0, 0.25 }
},
node_box = {
type = "fixed",
fixed = { -0.25, -0.5, -0.25, 0.25, 0, 0.25 }
},
groups = { snappy = 3 },
light_source = default.LIGHT_MAX-1,
sounds = default.node_sound_glass_defaults(),
on_place = minetest.rotate_node
})
local repl = { off="low", low="med", med="hi", hi="max", max="off", }
local brights_tab = { 0, 50, 100, 150, 200 }
local lamp_colors = {
{"white", "#ffffffe0:175"},
{"blue", "#2626c6e0:200"},
{"green", "#27a927e0:200"},
{"pink", "#ff8fb7e0:200"},
{"red", "#ad2323e0:200"},
{"violet", "#7f29d7e0:200"}
}
local tlamp_cbox = {
type = "fixed",
fixed = { -0.25, -0.5, -0.25, 0.25, 0.5, 0.25 }
}
local slamp_cbox = {
type = "fixed",
fixed = { -0.25, -0.5, -0.25, 0.25, 1.5, 0.25 }
}
local function reg_lamp(suffix, nxt, tilesuffix, light, color)
local lampcolor = "_"..color[1]
local colordesc = " ("..color[1]..")"
local woolcolor = color[1]
local invcolor = color[2]
local wool_brighten = (light or 0) * 7
local bulb_brighten = (light or 0) * 14
if color == "" then
lampcolor = ""
colordesc = " (white)"
woolcolor = "white"
end
homedecor.register("table_lamp"..lampcolor.."_"..suffix, {
description = S("Table Lamp "..colordesc),
mesh = "homedecor_table_lamp.obj",
tiles = {
"wool_"..woolcolor..".png^[colorize:#ffffff:"..wool_brighten,
"homedecor_table_standing_lamp_lightbulb.png^[colorize:#ffffff:"..bulb_brighten,
"homedecor_generic_wood_red.png",
"homedecor_generic_metal_black.png^[brighten",
},
inventory_image = "homedecor_table_lamp_foot_inv.png^(homedecor_table_lamp_top_inv.png^[colorize:"..invcolor..")",
walkable = false,
light_source = light,
selection_box = tlamp_cbox,
sounds = default.node_sound_wood_defaults(),
groups = {cracky=2,oddly_breakable_by_hand=1,
not_in_creative_inventory=((light ~= nil) and 1) or nil,
},
drop = "homedecor:table_lamp"..lampcolor.."_off",
on_punch = function(pos, node, puncher)
node.name = "homedecor:table_lamp"..lampcolor.."_"..repl[suffix]
minetest.set_node(pos, node)
end,
})
-- standing lamps
homedecor.register("standing_lamp"..lampcolor.."_"..suffix, {
description = S("Standing Lamp"..colordesc),
mesh = "homedecor_standing_lamp.obj",
tiles = {
"wool_"..woolcolor..".png^[colorize:#ffffff:"..wool_brighten,
"homedecor_table_standing_lamp_lightbulb.png^[colorize:#ffffff:"..bulb_brighten,
"homedecor_generic_wood_red.png",
"homedecor_generic_metal_black.png^[brighten",
},
inventory_image = "homedecor_standing_lamp_foot_inv.png^(homedecor_standing_lamp_top_inv.png^[colorize:"..invcolor..")",
walkable = false,
light_source = light,
groups = {cracky=2,oddly_breakable_by_hand=1,
not_in_creative_inventory=((light ~= nil) and 1) or nil,
},
selection_box = slamp_cbox,
sounds = default.node_sound_wood_defaults(),
on_rotate = screwdriver.rotate_simple,
on_punch = function(pos, node, puncher)
node.name = "homedecor:standing_lamp"..lampcolor.."_"..repl[suffix]
minetest.set_node(pos, node)
end,
expand = { top="placeholder" },
})
minetest.register_alias("homedecor:standing_lamp_bottom"..lampcolor.."_"..suffix, "homedecor:standing_lamp"..lampcolor.."_"..suffix)
minetest.register_alias("homedecor:standing_lamp_top"..lampcolor.."_"..suffix, "air")
-- for old maps that had the original 3dforniture mod
if lampcolor == "" then
minetest.register_alias("3dforniture:table_lamp_"..suffix, "homedecor:table_lamp_"..suffix)
end
end
for _, color in ipairs(lamp_colors) do
reg_lamp("off", "low", "", nil, color )
reg_lamp("low", "med", "l", 3, color )
reg_lamp("med", "hi", "m", 7, color )
reg_lamp("hi", "max", "h", 11, color )
reg_lamp("max", "off", "x", 14, color )
end
local dlamp_cbox = {
type = "fixed",
fixed = { -0.2, -0.5, -0.15, 0.32, 0.12, 0.15 },
}
local dlamp_colors = { "red","blue","green","violet" }
for _, color in ipairs(dlamp_colors) do
homedecor.register("desk_lamp_"..color, {
description = S("Desk Lamp ("..color..")"),
mesh = "homedecor_desk_lamp.obj",
tiles = {
"homedecor_table_standing_lamp_lightbulb.png^[colorize:#ffffff:200",
"homedecor_generic_metal_black.png^[colorize:"..color..":150",
"homedecor_generic_metal_black.png",
"homedecor_generic_metal_black.png^[colorize:"..color..":150"
},
inventory_image = "homedecor_desk_lamp_stem_inv.png^(homedecor_desk_lamp_metal_inv.png^[colorize:"..color..":140)",
selection_box = dlamp_cbox,
walkable = false,
groups = {snappy=3},
})
end
homedecor.register("ceiling_lamp", {
description = S("Ceiling Lamp"),
mesh = "homedecor_ceiling_lamp.obj",
tiles = {
"homedecor_generic_metal_brass.png",
"homedecor_ceiling_lamp_glass.png",
"homedecor_table_standing_lamp_lightbulb.png^[colorize:#ffffff:200",
"homedecor_generic_plastic_black.png^[colorize:#442d04:200",
},
inventory_image = "homedecor_ceiling_lamp_inv.png",
light_source = default.LIGHT_MAX,
groups = {snappy=3},
walkable = false,
on_punch = function(pos, node, puncher)
minetest.set_node(pos, {name = "homedecor:ceiling_lamp_off"})
end,
})
homedecor.register("ceiling_lamp_off", {
description = S("Ceiling Lamp (off)"),
mesh = "homedecor_ceiling_lamp.obj",
tiles = {
"homedecor_generic_metal_brass.png",
"homedecor_ceiling_lamp_glass.png",
"homedecor_table_standing_lamp_lightbulb.png",
"homedecor_generic_plastic_black.png^[colorize:#442d04:200",
},
groups = {snappy=3, not_in_creative_inventory=1},
walkable = false,
on_punch = function(pos, node, puncher)
minetest.set_node(pos, {name = "homedecor:ceiling_lamp"})
end,
drop = "homedecor:ceiling_lamp"
})
| unlicense |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/loot/items/wearables/jacket/jacket_s21.lua | 4 | 1255 | jacket_s21 = {
-- Spec-Ops Duster
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/wearables/jacket/jacket_s21.iff",
craftingValues = {},
skillMods = {},
customizationStringNames = {"/private/index_color_1","/private/index_color_2"},
customizationValues = {
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119}
},
junkDealerTypeNeeded = JUNKCLOTHESANDJEWELLERY,
junkMinValue = 45,
junkMaxValue = 90
}
addLootItemTemplate("jacket_s21", jacket_s21) | agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/managers/jedi/village/tests/village_jedi_manager_Test_disabled.lua | 2 | 3873 | local DirectorManagerMocks = require("screenplays.mocks.director_manager_mocks")
local GlowingMocks = require("managers.jedi.village.mocks.glowing_mocks")
local VillageJediManager = require("managers.jedi.village.village_jedi_manager")
local VillageJediManagerHolocronMocks = require("managers.jedi.village.mocks.village_jedi_manager_holocron_mocks")
local SithShadowEncounterMocks = require("managers.jedi.village.mocks.sith_shadow_encounter_mocks")
local SithShadowIntroTheaterMocks = require("managers.jedi.village.mocks.sith_shadow_intro_theater_mocks")
describe("Village Jedi Manager", function()
local pCreatureObject = { "creatureObjectPointer" }
local pPlayerObject = { "playerObjectPointer" }
local pSceneObject = { "sceneObjectPointer" }
local creatureObject
local playerObject
setup(function()
DirectorManagerMocks.mocks.setup()
GlowingMocks.mocks.setup()
VillageJediManagerHolocronMocks.setup()
SithShadowEncounterMocks.mocks.setup()
SithShadowIntroTheaterMocks.mocks.setup()
end)
teardown(function()
DirectorManagerMocks.mocks.teardown()
GlowingMocks.mocks.teardown()
VillageJediManagerHolocronMocks.teardown()
SithShadowEncounterMocks.mocks.teardown()
SithShadowIntroTheaterMocks.mocks.teardown()
end)
before_each(function()
DirectorManagerMocks.mocks.before_each()
GlowingMocks.mocks.before_each()
VillageJediManagerHolocronMocks.before_each()
SithShadowEncounterMocks.mocks.before_each()
SithShadowIntroTheaterMocks.mocks.before_each()
creatureObject = {}
creatureObject.sendSystemMessage = spy.new(function() end)
DirectorManagerMocks.creatureObjects[pCreatureObject] = creatureObject
playerObject = {}
playerObject.hasBadge = spy.new(function() return false end)
DirectorManagerMocks.playerObjects[pPlayerObject] = playerObject
end)
describe("Interface functions", function()
describe("useItem", function()
describe("When called with holocron and creature object", function()
it("Should call the useHolocron function in the VillageJediManagerHolocron", function()
VillageJediManager:useItem(pSceneObject, ITEMHOLOCRON, pCreatureObject)
assert.spy(VillageJediManagerHolocron.useHolocron).was.called_with(pSceneObject, pCreatureObject)
end)
end)
describe("When called with a waypoint datapad and creature object", function()
it("Should call the useWaypointDatapad function in the SithShadowEncounter", function()
VillageJediManager:useItem(pSceneObject, ITEMWAYPOINTDATAPAD, pCreatureObject)
assert.spy(SithShadowEncounterMocks.useWaypointDatapad).was.called_with(SithShadowEncounterMocks, pSceneObject, pCreatureObject)
end)
end)
describe("When called with a theater datapad and creature object", function()
it("Should call the useTheaterDatapad function in the SithShadowIntroTheater", function()
VillageJediManager:useItem(pSceneObject, ITEMTHEATERDATAPAD, pCreatureObject)
assert.spy(SithShadowIntroTheaterMocks.useTheaterDatapad).was.called_with(SithShadowIntroTheaterMocks, pSceneObject, pCreatureObject)
end)
end)
end)
describe("checkForceStatusCommand", function()
it("Should call checkForceStatusCommand in the glowing module.", function()
VillageJediManager:checkForceStatusCommand(pCreatureObject)
assert.spy(GlowingMocks.checkForceStatusCommand).was.called_with(GlowingMocks.realObject, pCreatureObject)
end)
end)
describe("onPlayerLoggedIn", function()
describe("When called with a player as argument", function()
it("Should call the onPlayerLoggedIn function in the Glowing module with the player as argument.", function()
VillageJediManager:onPlayerLoggedIn(pCreatureObject)
assert.spy(GlowingMocks.onPlayerLoggedIn).was.called_with(GlowingMocks.realObject, pCreatureObject)
end)
end)
end)
end)
describe("Private functions", function()
end)
end)
| agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/conversations/recruiter/rebel_recruiter_conv.lua | 2 | 19616 | rebelRecruiterConvoTemplate = ConvoTemplate:new {
initialScreen = "",
templateType = "Lua",
luaClassHandler = "RecruiterConvoHandler",
screens = {}
}
greet_hated = ConvoScreen:new {
id = "greet_hated",
leftDialog = "@conversation/faction_recruiter_rebel:s_462", -- I'm sorry, but I do not know you and do not wish to.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(greet_hated);
greet_changing_status = ConvoScreen:new {
id = "greet_changing_status",
leftDialog = "@conversation/faction_recruiter_rebel:s_596", -- Greetings. I see that your status is currently being processed. I won't be able to help you until that is complete. It should not take much longer.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(greet_changing_status);
greet_enemy = ConvoScreen:new {
id = "greet_enemy",
leftDialog = "@conversation/faction_recruiter_rebel:s_464", -- What are you doing talking to me? People like you are destroying the galaxy.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(greet_enemy);
member_covert_start = ConvoScreen:new {
id = "greet_member_start_covert",
leftDialog = "@conversation/faction_recruiter_rebel:s_466", -- Hello friend. Is there something that I may do to help you?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_504", "confirm_go_overt"}, -- I need to address my role in the Civil War.
{"@conversation/faction_recruiter_rebel:s_526", "leave_time_covert"}, -- I need to go on leave for a time.
{"@conversation/faction_recruiter_rebel:s_538", "resign_covert"}, -- This is all too much for me. I would like to resign completely.
}
}
rebelRecruiterConvoTemplate:addScreen(member_covert_start);
member_overt_start = ConvoScreen:new {
id = "greet_member_start_overt",
leftDialog = "@conversation/faction_recruiter_rebel:s_466", -- Hello friend. Is there something that I may do to help you?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_504", "confirm_go_covert"}, -- I need to address my role in the Civil War.
{"@conversation/faction_recruiter_rebel:s_526", "leave_time_overt"}, -- I need to go on leave for a time.
{"@conversation/faction_recruiter_rebel:s_538", "resign_overt"}, -- This is all too much for me. I would like to resign completely.
}
}
rebelRecruiterConvoTemplate:addScreen(member_overt_start);
neutral_start = ConvoScreen:new {
id = "greet_neutral_start",
leftDialog = "@conversation/faction_recruiter_rebel:s_566", -- Hello friend. Is there something that I can do for you? Are you interested in helping free the peoples of the galaxy?
stopConversation = "false",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(neutral_start);
onleave_start = ConvoScreen:new {
id = "greet_onleave_start",
leftDialog = "@conversation/faction_recruiter_rebel:s_448", -- Hello friend. Ready to get back to some real work?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_450", "resume_duties"}, -- I am ready to get back to my duties.
}
}
rebelRecruiterConvoTemplate:addScreen(onleave_start);
join_military = ConvoScreen:new {
id = "join_military",
leftDialog = "@conversation/faction_recruiter_rebel:s_584", -- This is not a decision to be taken lightly. Rebels are hunted across the galaxy. If you join us, while you are an active combatant, Imperials will attack you on sight but Imperial Special Forces will leave you alone. Are you ready for that?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_586", "accept_join"},
{"@conversation/faction_recruiter_rebel:s_592", "think_more"},
}
}
rebelRecruiterConvoTemplate:addScreen(join_military);
neutral_need_more_points = ConvoScreen:new {
id = "neutral_need_more_points",
leftDialog = "@conversation/faction_recruiter_rebel:s_582", -- Your enthusiasm warms my heart. I'm afraid that right now, your loyalty is somewhat in question. Go out and prove to us that you want to help us overthrow the Empire and we can talk later.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(neutral_need_more_points);
accept_join = ConvoScreen:new {
id = "accept_join",
leftDialog = "@conversation/faction_recruiter_rebel:s_588", -- Superb! Welcome to the Rebellion!
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accept_join);
think_more = ConvoScreen:new {
id = "think_more",
leftDialog = "@conversation/faction_recruiter_rebel:s_594", -- We only want serious, committed candidates. If you change your mind, talk to me then.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(think_more);
confirm_go_overt = ConvoScreen:new {
id = "confirm_go_overt",
leftDialog = "@conversation/faction_recruiter_rebel:s_516", -- We can use good people in Special Forces. As a member of the Special Forces, you will be able to attack and be attacked by Imperial Special Forces members. Does this interest you?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_518", "accepted_go_overt"}, -- Yes. I want to hunt Imperial Special Forces. Sign me up!
{"@conversation/faction_recruiter_rebel:s_522", "greet_member_start_overt"} -- Actually, maybe it isn't for me after all. Never mind.
}
}
rebelRecruiterConvoTemplate:addScreen(confirm_go_overt);
confirm_go_covert = ConvoScreen:new {
id = "confirm_go_covert",
leftDialog = "@conversation/faction_recruiter_rebel:s_506", -- You are currently in Special Forces. Do you need to step back from it for now?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_508", "accepted_go_covert"}, -- Yes please. I would like to return to combatant status and not fight the Imperial Special Forces.
{"@conversation/faction_recruiter_rebel:s_512", "stay_special_forces"} -- Actually, I want to stay in Special Forces.
}
}
rebelRecruiterConvoTemplate:addScreen(confirm_go_covert);
stay_special_forces = ConvoScreen:new {
id = "stay_special_forces",
leftDialog = "@conversation/faction_recruiter_rebel:s_514", -- Good show! Show those Imperials what for. May I help you with something else instead?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_504", "confirm_go_covert"}, -- I need to address my role in the Civil War.
{"@conversation/faction_recruiter_rebel:s_526", "leave_time_overt"}, -- I need to go on leave for a time.
{"@conversation/faction_recruiter_rebel:s_538", "resign_overt"}, -- This is all too much for me. I would like to resign completely.
}
}
rebelRecruiterConvoTemplate:addScreen(stay_special_forces);
accepted_go_overt = ConvoScreen:new {
id = "accepted_go_overt",
leftDialog = "@conversation/faction_recruiter_rebel:s_520", -- Good for you! I'll update your status and you will be a member of the Special Forces in 30 seconds.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accepted_go_overt);
accepted_go_covert = ConvoScreen:new {
id = "accepted_go_covert",
leftDialog = "@conversation/faction_recruiter_rebel:s_510", -- That's a shame. It will take some time to push the paperwork through for approval. Your status will change in about 5 minutes.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accepted_go_covert);
leave_time_covert = ConvoScreen:new {
id = "leave_time_covert",
leftDialog = "@conversation/faction_recruiter_rebel:s_528", -- We really need your skills. Are you sure that you want to go on leave now? You will be overlooked by most Imperials, unless you get stopped by a tenacious agent that finds something linking you to us.
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_530", "accepted_go_on_leave"}, -- Yes. I really need to take some leave time.
{"@conversation/faction_recruiter_rebel:s_534", "stay_covert"} -- Maybe not. I will stay active.
}
}
rebelRecruiterConvoTemplate:addScreen(leave_time_covert);
stay_covert = ConvoScreen:new {
id = "stay_covert",
leftDialog = "@conversation/faction_recruiter_rebel:s_536", -- I wish all of our soldiers had your dedication. I salute you!
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_504", "confirm_go_overt"}, -- I need to address my role in the Civil War.
{"@conversation/faction_recruiter_rebel:s_526", "leave_time_covert"}, -- I need to go on leave for a time.
{"@conversation/faction_recruiter_rebel:s_538", "resign_covert"}, -- This is all too much for me. I would like to resign completely.
}
}
rebelRecruiterConvoTemplate:addScreen(stay_covert);
leave_time_overt = ConvoScreen:new {
id = "leave_time_overt",
leftDialog = "@conversation/faction_recruiter_rebel:s_528", -- We really need your skills. Are you sure that you want to go on leave now? You will be overlooked by most Imperials, unless you get stopped by a tenacious agent that finds something linking you to us.
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_530", "accepted_go_on_leave"}, -- Yes. I really need to take some leave time.
{"@conversation/faction_recruiter_rebel:s_534", "stay_overt"} -- Maybe not. I will stay active.
}
}
rebelRecruiterConvoTemplate:addScreen(leave_time_overt);
stay_overt = ConvoScreen:new {
id = "stay_overt",
leftDialog = "@conversation/faction_recruiter_rebel:s_536", -- I wish all of our soldiers had your dedication. I salute you!
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_504", "confirm_go_covert"}, -- I need to address my role in the Civil War.
{"@conversation/faction_recruiter_rebel:s_526", "leave_time_covert"}, -- I need to go on leave for a time.
{"@conversation/faction_recruiter_rebel:s_538", "resign_covert"}, -- This is all too much for me. I would like to resign completely.
}
}
rebelRecruiterConvoTemplate:addScreen(stay_overt);
accepted_go_on_leave = ConvoScreen:new {
id = "accepted_go_on_leave",
leftDialog = "@conversation/faction_recruiter_rebel:s_532", -- It will take me some time to process, but you will be on leave beginning in 5 minutes.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accepted_go_on_leave);
leave_resign_covert = ConvoScreen:new {
id = "resign_covert",
leftDialog = "@conversation/faction_recruiter_rebel:s_540", -- How could you turn your back on people trying to win freedom from tyranny? We need everyone we can get! Won't you reconsider?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_542", "accepted_resign"}, -- I'm sure. I have had enough war. I want out.
{"@conversation/faction_recruiter_rebel:s_546", "dont_resign_covert"} -- You are right. It was a momentary lapse. I will stay with the Rebellion.
}
}
rebelRecruiterConvoTemplate:addScreen(leave_resign_covert);
dont_resign_covert = ConvoScreen:new {
id = "dont_resign_covert",
leftDialog = "@conversation/faction_recruiter_rebel:s_548", -- Doubt is understandable, but have faith. We are on the right side. No one wants to cater to a tyrant. Down with the Empire!
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_504", "confirm_go_overt"}, -- I need to address my role in the Civil War.
{"@conversation/faction_recruiter_rebel:s_526", "leave_time_covert"}, -- I need to go on leave for a time.
{"@conversation/faction_recruiter_rebel:s_538", "resign_covert"}, -- This is all too much for me. I would like to resign completely.
}
}
rebelRecruiterConvoTemplate:addScreen(dont_resign_covert);
leave_resign_overt = ConvoScreen:new {
id = "resign_overt",
leftDialog = "@conversation/faction_recruiter_rebel:s_540", -- How could you turn your back on people trying to win freedom from tyranny? We need everyone we can get! Won't you reconsider?
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_542", "accepted_resign"}, -- I'm sure. I have had enough war. I want out.
{"@conversation/faction_recruiter_rebel:s_546", "dont_resign_overt"} -- You are right. It was a momentary lapse. I will stay with the Rebellion.
}
}
rebelRecruiterConvoTemplate:addScreen(leave_resign_overt);
dont_resign_overt = ConvoScreen:new {
id = "dont_resign_overt",
leftDialog = "@conversation/faction_recruiter_rebel:s_548", -- Doubt is understandable, but have faith. We are on the right side. No one wants to cater to a tyrant. Down with the Empire!
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_504", "confirm_go_covert"}, -- I need to address my role in the Civil War.
{"@conversation/faction_recruiter_rebel:s_526", "leave_time_covert"}, -- I need to go on leave for a time.
{"@conversation/faction_recruiter_rebel:s_538", "resign_covert"}, -- This is all too much for me. I would like to resign completely.
}
}
rebelRecruiterConvoTemplate:addScreen(dont_resign_overt);
accepted_resign = ConvoScreen:new {
id = "accepted_resign",
leftDialog = "@conversation/faction_recruiter_rebel:s_544", -- So be it. If you decide that you want to come back, let me know. But for now, you are no longer a member of the Rebellion.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accepted_resign);
resume_duties = ConvoScreen:new {
id = "resume_duties",
leftDialog = "@conversation/faction_recruiter_rebel:s_452", -- Good to hear! I just want to make sure that you are serious about returning. You really want to come off leave? Remember that most of the Imperials will attack you on sight.
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_454", "accepted_resume_duties"}, -- Absolutely.
{"@conversation/faction_recruiter_rebel:s_458", "stay_on_leave"} -- Actually, I think I like being on leave.
}
}
rebelRecruiterConvoTemplate:addScreen(resume_duties);
stay_on_leave = ConvoScreen:new {
id = "stay_on_leave",
leftDialog = "@conversation/faction_recruiter_rebel:s_460", -- All right. We need you, but I think I can give you a few more days of leave.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(stay_on_leave);
accepted_resume_duties = ConvoScreen:new {
id = "accepted_resume_duties",
leftDialog = "@conversation/faction_recruiter_rebel:s_456", -- Let me send your paperwork through. It should only take me about 30 seconds to get it done.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accepted_resume_duties);
confirm_promotion = ConvoScreen:new {
id = "confirm_promotion",
leftDialog = "@conversation/faction_recruiter_rebel:s_470", -- I see that you qualify for a promotion to %TO.
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_472", "accepted_promotion"}, -- Excellent. I would like that promotion.
{"@conversation/faction_recruiter_rebel:s_476", "declined_promotion"}
}
}
rebelRecruiterConvoTemplate:addScreen(confirm_promotion);
accepted_promotion = ConvoScreen:new {
id = "accepted_promotion",
leftDialog = "@conversation/faction_recruiter_rebel:s_474", -- Outstanding! You certainly deserve this promotion. Congratulations.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accepted_promotion);
declined_promotion = ConvoScreen:new {
id = "declined_promotion",
leftDialog = "@conversation/faction_recruiter_rebel:s_478", -- While I applaud you for not seeking glory, we need good leaders. I hope you change your mind.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(declined_promotion);
not_enough_points = ConvoScreen:new {
id = "not_enough_points",
leftDialog = "@faction_recruiter:not_enough_for_promotion", -- You do not have enough faction standing to spend. You must maintain at least %DI to remain part of the %TO faction.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(not_enough_points);
confirm_bribe = ConvoScreen:new {
id = "confirm_bribe",
leftDialog = "@conversation/faction_recruiter_rebel:s_570", -- I would be happy to accept a donation.
stopConversation = "false",
options = {
{"@conversation/faction_recruiter_rebel:s_572", "accepted_bribe_20k"} -- I just happen to have a spare 20000 credits for you.
}
}
rebelRecruiterConvoTemplate:addScreen(confirm_bribe);
accepted_bribe_20k = ConvoScreen:new {
id = "accepted_bribe_20k",
leftDialog = "@conversation/faction_recruiter_rebel:s_574", -- Your donation is certainly appreciated. Let me just quickly verify the bank funds.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accepted_bribe_20k);
accepted_bribe_100k = ConvoScreen:new {
id = "accepted_bribe_100k",
leftDialog = "@conversation/faction_recruiter_rebel:s_578", -- Wow! That's quite a donation. Thank you very much. Your donation will be processed after I verify the funds.
stopConversation = "true",
options = {
}
}
rebelRecruiterConvoTemplate:addScreen(accepted_bribe_100k);
faction_purchase = ConvoScreen:new {
id = "faction_purchase",
leftDialog = "@conversation/faction_recruiter_rebel:s_482", -- we have some things. what do you need?
stopConversation = "false",
options = {
{ "@conversation/faction_recruiter_rebel:s_484", "fp_installations" }, -- We have some things. What do you need?
{ "@conversation/faction_recruiter_rebel:s_488", "fp_weapons_armor" }, -- I need better weaponry and armor.
--{ "@conversation/faction_recruiter_rebel:s_492", "fp_schematics" }, -- I like to build. What schematics are available?
{ "@conversation/faction_recruiter_rebel:s_496", "fp_furniture"}, -- I would like to do some decorating. I need furniture.
{ "@conversation/faction_recruiter_rebel:s_500", "fp_hirelings" }, -- I need some back-up troops.
},
}
rebelRecruiterConvoTemplate:addScreen(faction_purchase);
fp_furniture = ConvoScreen:new {
id = "fp_furniture",
leftDialog = "@conversation/faction_recruiter_rebel:s_498", -- What suits your style? This is what I have available.
stopConversation = "true",
options = { },
}
rebelRecruiterConvoTemplate:addScreen(fp_furniture);
fp_weapons_armor = ConvoScreen:new {
id = "fp_weapons_armor",
leftDialog = "@conversation/faction_recruiter_rebel:s_490", -- Don't we all? With all the Imperial thugs crawling around, I don't blame you. Let me show you my selection.
stopConversation = "true",
options = {},
}
rebelRecruiterConvoTemplate:addScreen(fp_weapons_armor);
fp_installations = ConvoScreen:new {
id = "fp_installations",
leftDialog = "@conversation/faction_recruiter_rebel:s_486", -- All right. Let me show you the plans that are available.
stopConversation = "true",
options = {},
}
rebelRecruiterConvoTemplate:addScreen(fp_installations);
fp_schematics = ConvoScreen:new {
id = "fp_schematics",
leftDialog = "@conversation/faction_recruiter_rebel:s_494", -- Good. We always need people making useful goods. I'll show you what I have.
stopConversation = "true",
options = {},
}
rebelRecruiterConvoTemplate:addScreen(fp_schematics);
fp_hirelings = ConvoScreen:new {
id = "fp_hirelings",
leftDialog = "@conversation/faction_recruiter_rebel:s_502", -- I'll see what I can do, but as you know, every soldier is valuable.
stopConversation = "true",
options = {},
}
rebelRecruiterConvoTemplate:addScreen(fp_hirelings);
addConversationTemplate("rebelRecruiterConvoTemplate", rebelRecruiterConvoTemplate);
| agpl-3.0 |
alinofel/zooz11 | libs/XMLElement.lua | 569 | 4025 | -- Copyright 2009 Leo Ponomarev. Distributed under the BSD Licence.
-- updated for module-free world of lua 5.3 on April 2 2015
-- Not documented at all, but not interesting enough to warrant documentation anyway.
local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error
local table, string = table, string
local XMLElement={}
local mt
XMLElement.new = function(lom)
return setmetatable({lom=lom or {}}, mt)
end
local function filter(filtery_thing, lom)
filtery_thing=filtery_thing or '*'
for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do
if thing == "text()" then
if type(lom)=='string' then return true end
elseif thing == '*' then
if type(lom)=='table' then return true end
else
if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end
end
end
return nil
end
mt ={ __index = {
getAttr = function(self, attribute)
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
return self.lom.attr[attribute]
end,
setAttr = function(self, attribute, value)
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
if value == nil then return self:removeAttr(attribute) end
self.lom.attr[attribute]=tostring(value)
return self
end,
removeAttr = function(self, attribute)
local lom = self.lom
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
if not lom.attr[attribute] then return self end
for i,v in ipairs(lom.attr) do
if v == attribute then
table.remove(lom.attr, i)
break
end
end
lom.attr[attribute]=nil
end,
removeAllAttributes = function(self)
local attr = self.lom.attr
for i, v in pairs(self.lom.attr) do
attr[i]=nil
end
return self
end,
getAttributes = function(self)
local attr = {}
for i, v in ipairs(self.lom.attr) do
table.insert(attr,v)
end
return attr
end,
getXML = function(self)
local function getXML(lom)
local attr, inner = {}, {}
for i, attribute in ipairs(lom.attr) do
table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute]))
end
for i, v in ipairs(lom) do
local t = type(v)
if t == "string" then table.insert(inner, v)
elseif t == "table" then
table.insert(inner, getXML(v))
else
error("oh shit")
end
end
local tagcontents = table.concat(inner)
local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or ""
if #tagcontents>0 then
return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag)
else
return string.format("<%s%s />", lom.tag, attrstring)
end
end
return getXML(self.lom)
end,
getText = function(self)
local function getText(lom)
local inner = {}
for i, v in ipairs(lom) do
local t = type(v)
if t == "string" then table.insert(inner, v)
elseif t == "table" then
table.insert(inner, getText(v))
end
end
return table.concat(inner)
end
return getText(self.lom)
end,
getChildren = function(self, filter_thing)
local res = {}
for i, node in ipairs(self.lom) do
if filter(filter_thing, node) then
table.insert(res, type(node)=='table' and XMLElement.new(node) or node)
end
end
return res
end,
getDescendants = function(self, filter_thing)
local res = {}
local function descendants(lom)
for i, child in ipairs(lom) do
if filter(filter_thing, child) then
table.insert(res, type(child)=='table' and XMLElement.new(child) or child)
if type(child)=='table' then descendants(child) end
end
end
end
descendants(self.lom)
return res
end,
getChild = function(self, filter_thing)
for i, node in ipairs(self.lom) do
if filter(filter_thing, node) then
return type(node)=='table' and XMLElement.new(node) or node
end
end
end,
getTag = function(self)
return self.lom.tag
end
}}
return XMLElement | gpl-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/requestResourceWeightsBatch.lua | 4 | 2174 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
RequestResourceWeightsBatchCommand = {
name = "requestresourceweightsbatch",
}
AddCommand(RequestResourceWeightsBatchCommand)
| agpl-3.0 |
insionng/gopher-lua | _glua-tests/vm.lua | 5 | 5567 | for i, v in ipairs({"hoge", {}, function() end, true, nil}) do
local ok, msg = pcall(function()
print(-v)
end)
assert(not ok and string.find(msg, "__unm undefined"))
end
assert(#"abc" == 3)
local tbl = {1,2,3}
setmetatable(tbl, {__len = function(self)
return 10
end})
assert(#tbl == 10)
setmetatable(tbl, nil)
assert(#tbl == 3)
local ok, msg = pcall(function()
return 1 < "hoge"
end)
assert(not ok and string.find(msg, "attempt to compare number with string"))
local ok, msg = pcall(function()
return {} < (function() end)
end)
assert(not ok and string.find(msg, "attempt to compare table with function"))
local ok, msg = pcall(function()
for n = nil,1 do
print(1)
end
end)
assert(not ok and string.find(msg, "for statement init must be a number"))
local ok, msg = pcall(function()
for n = 1,nil do
print(1)
end
end)
assert(not ok and string.find(msg, "for statement limit must be a number"))
local ok, msg = pcall(function()
for n = 1,10,nil do
print(1)
end
end)
assert(not ok and string.find(msg, "for statement step must be a number"))
local ok, msg = pcall(function()
return {} + (function() end)
end)
assert(not ok and string.find(msg, "cannot perform add operation between table and function"))
local ok, msg = pcall(function()
return {} .. (function() end)
end)
assert(not ok and string.find(msg, "cannot perform concat operation between table and function"))
-- test table with initial elements over 511
local bigtable = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,10}
assert(bigtable[601] == 10)
local ok, msg = loadstring([[
function main(
a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16,
a17, a18, a19, a20, a21, a22, a23, a24,
a25, a26, a27, a28, a29, a30, a31, a32,
a33, a34, a35, a36, a37, a38, a39, a40,
a41, a42, a43, a44, a45, a46, a47, a48,
a49, a50, a51, a52, a53, a54, a55, a56,
a57, a58, a59, a60, a61, a62, a63, a64,
a65, a66, a67, a68, a69, a70, a71, a72,
a73, a74, a75, a76, a77, a78, a79, a80,
a81, a82, a83, a84, a85, a86, a87, a88,
a89, a90, a91, a92, a93, a94, a95, a96,
a97, a98, a99, a100, a101, a102, a103,
a104, a105, a106, a107, a108, a109, a110,
a111, a112, a113, a114, a115, a116, a117,
a118, a119, a120, a121, a122, a123, a124,
a125, a126, a127, a128, a129, a130, a131,
a132, a133, a134, a135, a136, a137, a138,
a139, a140, a141, a142, a143, a144, a145,
a146, a147, a148, a149, a150, a151, a152,
a153, a154, a155, a156, a157, a158, a159,
a160, a161, a162, a163, a164, a165, a166,
a167, a168, a169, a170, a171, a172, a173,
a174, a175, a176, a177, a178, a179, a180,
a181, a182, a183, a184, a185, a186, a187,
a188, a189, a190, a191, a192, a193, a194,
a195, a196, a197, a198, a199, a200, a201,
a202, a203, a204, a205, a206, a207, a208,
a209, a210, a211, a212, a213, a214, a215,
a216, a217, a218, a219, a220, a221, a222,
a223, a224, a225, a226, a227, a228, a229,
a230, a231, a232, a233, a234, a235, a236,
a237, a238, a239, a240, a241, a242, a243,
a244, a245, a246, a247, a248, a249, a250,
a251, a252, a253, a254, a255, a256, a257,
a258, a259, a260, a261, a262, a263, a264,
a265, a266, a267, a268, a269, a270, a271,
a272, a273, a274, a275, a276, a277, a278,
a279, a280, a281, a282, a283, a284, a285,
a286, a287, a288, a289, a290, a291, a292,
a293, a294, a295, a296, a297, a298, a299,
a300, a301, a302) end
]])
assert(not ok and string.find(msg, "register overflow"))
local ok, msg = loadstring([[
function main()
local a = {...}
end
]])
assert(not ok and string.find(msg, "cannot use '...' outside a vararg function"))
| mit |
garoose/eecs494.p2 | dev/premake/premake/tests/test_platforms.lua | 59 | 1601 | --
-- tests/test_platforms.lua
-- Automated test suite for platform handling functions.
-- Copyright (c) 2009 Jason Perkins and the Premake project
--
T.platforms = { }
local testmap = { Native="Win32", x32="Win32", x64="x64" }
local sln, r
function T.platforms.setup()
sln = solution "MySolution"
configurations { "Debug", "Release" }
end
function T.platforms.filter_OnNoSolutionPlatforms()
premake.bake.buildconfigs()
r = premake.filterplatforms(sln, testmap)
test.isequal("", table.concat(r, ":"))
end
function T.platforms.filter_OnNoSolutionPlatformsAndDefault()
premake.bake.buildconfigs()
r = premake.filterplatforms(sln, testmap, "x32")
test.isequal("x32", table.concat(r, ":"))
end
function T.platforms.filter_OnIntersection()
platforms { "x32", "x64", "Xbox360" }
premake.bake.buildconfigs()
r = premake.filterplatforms(sln, testmap, "x32")
test.isequal("x32:x64", table.concat(r, ":"))
end
function T.platforms.filter_OnNoIntersection()
platforms { "Universal", "Xbox360" }
premake.bake.buildconfigs()
r = premake.filterplatforms(sln, testmap)
test.isequal("", table.concat(r, ":"))
end
function T.platforms.filter_OnNoIntersectionAndDefault()
platforms { "Universal", "Xbox360" }
premake.bake.buildconfigs()
r = premake.filterplatforms(sln, testmap, "x32")
test.isequal("x32", table.concat(r, ":"))
end
function T.platforms.filter_OnDuplicateKeys()
platforms { "Native", "x32" }
premake.bake.buildconfigs()
r = premake.filterplatforms(sln, testmap, "x32")
test.isequal("Native", table.concat(r, ":"))
end
| mit |
NYRDS/pixel-dungeon-remix | RemixedDungeon/src/main/assets/scripts/lib/item.lua | 1 | 2129 | --
-- User: mike
-- Date: 28.05.2018
-- Time: 22:35
-- This file is part of Remixed Pixel Dungeon.
--
local serpent = require "scripts/lib/serpent"
local RPD = require "scripts/lib/commonClasses"
local util = require "scripts/lib/util"
local item = {}
item.__index = item
function item.actions(self, item, hero)
return {}
end
function item.execute(self, item, hero, action)
end
function item.burn(self, item, cell)
return item
end
function item.freeze(self, item, cell)
return item
end
function item.poison(self, item, cell)
return item
end
function item.act(self, item)
item:deactivateActor()
end
function item.onThrow(self, item, cell, thrower)
item:dropTo(cell)
end
function item.cellSelected(self, item, action, cell)
end
function item.activate(self, item, hero)
end
function item.deactivate(self, item, hero)
end
function item.saveData(self)
return serpent.dump(self.data or {})
end
function item.loadData(self, _, str)
local _,data = serpent.load(str)
self.data = data or {}
end
function item.storeData(self, data)
self.data = data or {}
end
function item.restoreData(self)
return self.data or {}
end
function item.defaultDesc()
return {
image = 14,
imageFile = "items/food.png",
name = "smth",
info = "smth",
stackable = false,
upgradable = false,
identified = true,
defaultAction = "Item_ACThrow",
price = 0,
equipable = ""
}
end
function item.itemDesc(self,thisItem)
local ret = item.defaultDesc(thisItem)
local own = self:desc(thisItem)
if own.isArtifact then
own.equipable = "artifact"
end
self.data = own.data or {}
for k,v in pairs(own) do
ret[k] = v
end
return ret
end
function item.desc(self, item)
return item.defaultDesc()
end
item.init = function(desc)
setmetatable(desc, item)
return desc
end
function item.makeGlowing(color, period)
return luajava.newInstance('com.watabou.pixeldungeon.sprites.Glowing', color, period)
end
return item | gpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/dantooine/force_trained_archaist.lua | 2 | 1401 | force_trained_archaist = Creature:new {
objectName = "@mob/creature_names:force_trained_archaist",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "force",
faction = "",
level = 90,
chanceHit = 0.9,
damageMin = 640,
damageMax = 990,
baseXp = 8593,
baseHAM = 13000,
baseHAMmax = 16000,
armor = 2,
resists = {45,45,0,0,0,0,0,0,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/dressed_force_trained_archaist.iff"},
lootGroups = {
{
groups = {
{group = "junk", chance = 3500000},
{group = "crystals_poor", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "holocron_dark", chance = 500000},
{group = "holocron_light", chance = 500000},
{group = "melee_weapons", chance = 1000000},
{group = "armor_attachments", chance = 1000000},
{group = "clothing_attachments", chance = 1000000},
{group = "wearables_common", chance = 750000},
{group = "wearables_uncommon", chance = 750000}
}
}
},
weapons = {"mixed_force_weapons"},
conversationTemplate = "",
attacks = merge(pikemanmaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(force_trained_archaist, "force_trained_archaist")
| agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/corellia/meatlump_loon.lua | 2 | 1395 | meatlump_loon = Creature:new {
objectName = "@mob/creature_names:meatlump_loon",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "meatlump",
faction = "meatlump",
level = 10,
chanceHit = 0.28,
damageMin = 90,
damageMax = 110,
baseXp = 356,
baseHAM = 810,
baseHAMmax = 990,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_gran_thug_male_01.iff",
"object/mobile/dressed_gran_thug_male_02.iff",
"object/mobile/dressed_criminal_thug_aqualish_female_01.iff",
"object/mobile/dressed_criminal_thug_aqualish_female_02.iff",
"object/mobile/dressed_criminal_thug_aqualish_male_01.iff",
"object/mobile/dressed_criminal_thug_aqualish_male_02.iff"},
lootGroups = {
{
groups = {
{group = "junk", chance = 2900000},
{group = "loot_kit_parts", chance = 1500000},
{group = "color_crystals", chance = 100000},
{group = "tailor_components", chance = 500000},
{group = "meatlump_common", chance = 5000000}
}
}
},
weapons = {"pirate_weapons_light"},
reactionStf = "@npc_reaction/slang",
attacks = merge(brawlernovice,marksmannovice)
}
CreatureTemplates:addCreatureTemplate(meatlump_loon, "meatlump_loon")
| agpl-3.0 |
lolleko/guesswho | gamemodes/guesswho/gamemode/round.lua | 1 | 15924 | local GWRound = {}
GM.GWRound = GWRound
hook.Add("InitPostEntity", "gw_InitPostEntity", function()
GAMEMODE.GWRound:UpdateSettings()
GAMEMODE.GWRound:RoundPreGame()
GAMEMODE.GWRound.GeneratedSpawnPointCount = 0
end)
function GWRound:RoundPreGame()
self:SetRoundState(GW_ROUND_PRE_GAME)
hook.Run("GWPreGame")
self:SetEndTime(CurTime() + self.PreGameDuration)
timer.Create("gwPreGameTimer", self.PreGameDuration, 1,
function() self:RoundWaitForPlayers() end)
timer.Simple(1, function() self:MeshController() end)
end
function GWRound:RoundWaitForPlayers()
-- do not start round without players or at least one player in each team
if team.NumPlayers(GW_TEAM_HIDING) < self.MinHiding or
team.NumPlayers(GW_TEAM_SEEKING) < self.MinSeeking then
-- check again after half a second second
timer.Simple(0.5, function() self:RoundWaitForPlayers() end)
-- clear remaning npcs to save recources
for k, v in pairs(ents.FindByClass(GW_WALKER_CLASS)) do v:Remove() end
self:SetEndTime(CurTime() + 1)
self:SetRoundState(GW_ROUND_WAITING_PLAYERS)
return
end
self:RoundCreateWalkers()
end
function GWRound:RoundCreateWalkers()
self:SetRoundState(GW_ROUND_CREATING_NPCS)
hook.Run("GWCreating")
self:UpdateSpawnPoints()
local wave = 1
local playerCount = player.GetCount()
self.WalkerCount = 0
self.MaxWalkers = self.BaseWalkers + (playerCount * self.WalkerPerPly)
if #self.SpawnPoints > self.MaxWalkers then
self:SpawnNPCWave()
MsgN("GW Spawned ", self.WalkerCount, " NPCs in 1 wave.")
else
local wpw
for w = 0, math.ceil(self.MaxWalkers / #self.SpawnPoints) - 1, 1 do
wave = wave + 1
timer.Simple(w * 5, function()
wpw = self.WalkerCount
self:SpawnNPCWave()
MsgN("GW Spawned ", self.WalkerCount - wpw, " NPCs in wave ",
w + 1, ".")
end)
end
wave = wave - 1
end
timer.Simple(5 * wave, function()
self:SetRoundState(GW_ROUND_HIDE)
hook.Run("GWHide")
for _, v in pairs(team.GetPlayers(GW_TEAM_HIDING)) do v:Spawn() end
end)
timer.Simple(5 + (5 * wave), function()
for _, v in pairs(team.GetPlayers(GW_TEAM_SEEKING)) do
v:Spawn()
v:SetPos(v:GetPos() + Vector(2, 2, 2)) -- move them a little bit to make avoid players work
v:Freeze(true)
v:GodEnable()
v:SetAvoidPlayers(true)
end
end)
timer.Simple(self.HideDuration + (5 * wave),
function() self:RoundStart() end)
self:SetEndTime(CurTime() + self.HideDuration + (5 * wave))
PrintMessage(HUD_PRINTTALK,
"Map will change in " .. self.MaxRounds -
GetGlobalInt("RoundNumber", 0) .. " rounds.")
end
function GWRound:RoundStart()
for _, v in pairs(team.GetPlayers(GW_TEAM_SEEKING)) do
v:Freeze(false)
v:SetAvoidPlayers(false)
v:GodDisable()
end
timer.Create("RoundThink", 1, self.RoundDuration,
function() self:RoundThink() end)
self.RoundTime = 1
self:SetEndTime(CurTime() + self.RoundDuration)
SetGlobalInt("RoundNumber", GetGlobalInt("RoundNumber", 0) + 1)
self:SetRoundState(GW_ROUND_SEEK)
hook.Run("GWSeek")
end
-- will be called every second
function GWRound:RoundThink()
-- end conditions
self.RoundTime = self.RoundTime + 1
if self.RoundTime == self.RoundDuration then self:RoundEnd(false) end
if team.NumPlayers(GW_TEAM_HIDING) < self.MinHiding or
team.NumPlayers(GW_TEAM_SEEKING) < self.MinSeeking then self:RoundEnd() end
local seekersWin = true
for k, v in pairs(team.GetPlayers(GW_TEAM_HIDING)) do
if v:Alive() then seekersWin = false end
end
local hidingWin = true
for k, v in pairs(team.GetPlayers(GW_TEAM_SEEKING)) do
if v:Alive() then hidingWin = false end
end
if seekersWin then self:RoundEnd(true) end
if hidingWin then self:RoundEnd(false) end
end
function GWRound:RoundEnd(caught)
hook.Run("GWOnRoundEnd", caught)
if timer.Exists("RoundThink") then timer.Remove("RoundThink") end
-- choose winner and stuff
local postRoundDelay = 8
if caught then
GWNotifications:Add("gwVictory" .. team.GetName(GW_TEAM_SEEKING), "<font=gw_font_normal>" .. team.GetName(GW_TEAM_SEEKING) .. " Victory" .. "</font>", "", postRoundDelay)
for _, v in pairs(team.GetPlayers(GW_TEAM_SEEKING)) do
v:GWPlayTauntOnClients(ACT_GMOD_TAUNT_CHEER)
end
team.AddScore(GW_TEAM_SEEKING, 1)
else
GWNotifications:Add("gwVictory" .. team.GetName(GW_TEAM_HIDING), "<font=gw_font_normal>" .. team.GetName(GW_TEAM_HIDING) .. " Victory" .. "</font>", "", postRoundDelay)
for _, v in pairs(team.GetPlayers(GW_TEAM_HIDING)) do
v:GWPlayTauntOnClients(ACT_GMOD_TAUNT_CHEER)
if v:Alive() then v:AddFrags(1) end -- if still alive as hiding after round give them one point (frag)
end
team.AddScore(GW_TEAM_HIDING, 1)
end
-- reset reroll protections and funcs
for _, v in pairs(team.GetPlayers(GW_TEAM_HIDING)) do
v:SetGWDiedInPrep(false)
v:SetGWReRolledAbility(false)
end
timer.Create("gwPostRoundDelayTimer", postRoundDelay, 1, function() self:PostRound() end)
end
function GWRound:PostRound()
if GetGlobalInt("RoundNumber", 0) >= self.MaxRounds then
MsgN("GW Round cap reached changing map..")
if MapVote then
MsgN("GW Mapvote detected starting vote!")
MapVote.Start()
return
end
game.LoadNextMap()
end
-- cleanup everythiung except generated spawn points
game.CleanUpMap(false, {"info_player_start"})
for _, walker in pairs(ents.FindByClass(GW_WALKER_CLASS)) do walker:Remove() end
-- Remove some HL2 entities
local hl2EntClasses = {
"weapon_357",
"weapon_pistol",
"weapon_bugbait",
"weapon_crossbow",
"weapon_crowbar",
"weapon_frag",
"weapon_physcannon",
"weapon_ar2",
"weapon_rpg",
"weapon_slam",
"weapon_shotgun",
"weapon_smg1",
"weapon_stunstick"
}
for _, hl2EntClass in pairs(hl2EntClasses) do
for _, hl2Ent in pairs(ents.FindByClass(hl2EntClass)) do hl2Ent:Remove() end
end
timer.Simple(self.PostRoundDuration,
function() self:RoundWaitForPlayers() end)
self:SetEndTime(CurTime() + self.PostRoundDuration)
self:SetRoundState(GW_ROUND_POST)
hook.Run("GWPostRound")
self:UpdateSettings()
-- teamswap
for _, v in pairs(player.GetAll()) do
if v:Team() == GW_TEAM_SEEKING then
v:SetTeam(GW_TEAM_HIDING)
elseif v:Team() == GW_TEAM_HIDING then
v:SetTeam(GW_TEAM_SEEKING)
end
v:KillSilent()
end
end
function GWRound:SpawnNPCWave()
for _, v in pairs(self.SpawnPoints) do
if self.WalkerCount >= self.MaxWalkers then break end
local occupied = false
for _, ent in pairs(ents.FindInBox(v:GetPos() + Vector(-16, -16, 0),
v:GetPos() + Vector(16, 16, 72))) do
if ent:GetClass() == GW_WALKER_CLASS then occupied = true end
end
if not occupied then
local walker = ents.Create(GW_WALKER_CLASS)
if not IsValid(walker) then break end
walker:SetPos(v:GetPos())
walker:Spawn()
walker:Activate()
self.WalkerCount = self.WalkerCount + 1
end
end
end
function GWRound:UpdateSettings()
self.BaseWalkers = GetConVar("gw_basewalkeramount"):GetInt()
self.WalkerPerPly = GetConVar("gw_walkerperplayer"):GetFloat()
self.PreGameDuration = GetConVar("gw_pregameduration"):GetInt()
self.RoundDuration = GetConVar("gw_roundduration"):GetInt()
self.HideDuration = GetConVar("gw_hideduration"):GetInt()
self.PostRoundDuration = GetConVar("gw_postroundduration"):GetInt()
self.MaxRounds = GetConVar("gw_maxrounds"):GetInt()
self.MinHiding = GetConVar("gw_minhiding"):GetInt()
self.MinSeeking = GetConVar("gw_minseeking"):GetInt()
end
function GWRound:MeshController()
if navmesh.IsLoaded() then
MsgN("GW Navmesh loaded waiting for game to start.")
else
timer.Remove("gwPreGameTimer")
self:SetRoundState(GW_ROUND_NAV_GEN)
navmesh.BeginGeneration()
-- force generate
if not navmesh.IsGenerating() then
self:UpdateSpawnPoints()
local tr = util.TraceLine({
start = self.SpawnPoints[1]:GetPos(),
endpos = self.SpawnPoints[1]:GetPos() - Vector(0, 0, 100),
filter = self.SpawnPoints[1]
})
local ent = ents.Create("info_player_start")
ent:SetPos(tr.HitPos)
ent:Spawn()
navmesh.BeginGeneration()
end
if not navmesh.IsGenerating() then
PrintMessage(HUD_PRINTCENTER,
"Guess Who Navmesh generation failed, try to reload the map a few times.\nIf it still fails try a diffrent map!")
else
timer.Create("gwNavmeshGen", 1, 0, function()
PrintMessage(HUD_PRINTCENTER,
"Generating navmesh, this will take some time!\nUp to 10min (worst case) depending on map size and your system.\nYou will only need to do this once.")
end)
end
end
end
function GWRound:UpdateSpawnPoints()
self.SpawnPoints = ents.FindByClass("info_player_start")
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_deathmatch"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_combine"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_rebel"))
-- CS Maps
self.SpawnPoints = table.Add(self.SpawnPoints, ents.FindByClass(
"info_player_counterterrorist"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_terrorist"))
-- DOD Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_axis"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_allies"))
-- (Old) GMod Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("gmod_player_start"))
-- TF Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_teamspawn"))
-- INS Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("ins_spawnpoint"))
-- AOC Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("aoc_spawnpoint"))
-- Dystopia Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("dys_spawn_point"))
-- PVKII Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_pirate"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_viking"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_knight"))
-- DIPRIP Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("diprip_start_team_blue"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("diprip_start_team_red"))
-- OB Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_red"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_blue"))
-- SYN Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_coop"))
-- ZPS Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_human"))
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_zombie"))
-- ZM Maps
self.SpawnPoints = table.Add(self.SpawnPoints,
ents.FindByClass("info_player_deathmatch"))
self.SpawnPoints = table.Add(self.SpawnPoints, ents.FindByClass(
"info_player_zombiemaster"))
-- FOF Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass("info_player_fof"))
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass("info_player_desperado"))
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass("info_player_vigilante"))
-- L4D Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass("info_survivor_rescue"))
-- try to create more spawnpoints if we dont have enough
if #self.SpawnPoints < 5 then
local locations = {
Vector(48, 0, 2),
Vector(-48, 0, 2),
Vector(0, 48, 2),
Vector(0, -48, 2),
Vector(48, 48, 2),
Vector(48, -48, 2),
Vector(-48, 48, 2),
Vector(-48, -48, 2),
Vector(96, 0, 2),
Vector(-96, 0, 2),
Vector(0, 96, 2),
Vector(0, -96, 2),
Vector(96, 96, 2),
Vector(96, -96, 2),
Vector(-96, 96, 2),
Vector(-96, -96, 2),
}
for _, spawnPoint in pairs(self.SpawnPoints) do
for _, locationOffset in pairs(locations) do
local location = spawnPoint:GetPos() + locationOffset
local tr = util.TraceHull({
start = location,
endpos = location,
maxs = Vector(16, 16, 72),
mins = Vector(-16, -16, 0),
})
if self.GeneratedSpawnPointCount < 16 and not tr.Hit then
local newSpawnPoint = ents.Create("info_player_start")
if not IsValid(newSpawnPoint) then break end
newSpawnPoint:SetPos(location)
newSpawnPoint:Spawn()
newSpawnPoint:Activate()
table.insert(self.SpawnPoints, newSpawnPoint)
self.GeneratedSpawnPointCount = self.GeneratedSpawnPointCount + 1
end
end
end
end
local rand = math.random
local n = #self.SpawnPoints
while n > 2 do
local k = rand(n) -- 1 <= k <= n
self.SpawnPoints[n], self.SpawnPoints[k] = self.SpawnPoints[k],
self.SpawnPoints[n]
n = n - 1
end
end
function GWRound:SetRoundState(state)
self.RoundState = state
self:SendRoundState(state)
end
function GWRound:GetRoundState() return self.RoundState end
function GWRound:IsCurrentState(state) return self.RoundState == state end
function GWRound:SendRoundState(state, ply)
net.Start("gwRoundState")
net.WriteUInt(state, 8)
return ply and net.Send(ply) or net.Broadcast()
end
function GWRound:SetEndTime(time) SetGlobalFloat("gwEndTime", time) end
| mit |
excessive/obtuse-tanuki | libs/winapi/propsys.lua | 2 | 2554 |
--proc/propsys: Property System API.
--Written by Cosmin Apreutesei. Public Domain.
setfenv(1, require'winapi')
require'winapi.sstorage'
ffi.cdef[[
typedef struct _tagpropertykey
{
GUID fmtid;
DWORD pid;
} PROPERTYKEY;
typedef const PROPERTYKEY * REFPROPERTYKEY;
typedef struct IPropertyStore IPropertyStore;
typedef struct IPropertyStoreVtbl
{
HRESULT ( __stdcall *QueryInterface )(
IPropertyStore * This,
REFIID riid,
void **ppvObject);
ULONG ( __stdcall *AddRef )(
IPropertyStore * This);
ULONG ( __stdcall *Release )(
IPropertyStore * This);
HRESULT ( __stdcall *GetCount )(
IPropertyStore * This,
DWORD *cProps);
HRESULT ( __stdcall *GetAt )(
IPropertyStore * This,
DWORD iProp,
PROPERTYKEY *pkey);
HRESULT ( __stdcall *GetValue )(
IPropertyStore * This,
REFPROPERTYKEY key,
PROPVARIANT *pv);
HRESULT ( __stdcall *SetValue )(
IPropertyStore * This,
/* [in] */ REFPROPERTYKEY key,
/* [in] */ REFPROPVARIANT propvar);
HRESULT ( __stdcall *Commit )(
IPropertyStore * This);
} IPropertyStoreVtbl;
struct IPropertyStore
{
const struct IPropertyStoreVtbl *lpVtbl;
};
]]
IPropertyStore = ffi.typeof("IPropertyStore");
IPropertyStore_mt = {
__index = {
GetAt = function(self, idx, pkey)
return self.lpVtbl.GetAt(self, idx, pkey);
end,
GetValue = function(self, pkey, pv)
return self.lpVtbl.GetValue(self, pkey, pv);
end,
},
}
ffi.metatype(IPropertyStore, IPropertyStore_mt);
--[[
#define IPropertyStore_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define IPropertyStore_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define IPropertyStore_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define IPropertyStore_GetCount(This,cProps) \
( (This)->lpVtbl -> GetCount(This,cProps) )
#define IPropertyStore_GetAt(This,iProp,pkey) \
( (This)->lpVtbl -> GetAt(This,iProp,pkey) )
#define IPropertyStore_GetValue(This,key,pv) \
( (This)->lpVtbl -> GetValue(This,key,pv) )
#define IPropertyStore_SetValue(This,key,propvar) \
( (This)->lpVtbl -> SetValue(This,key,propvar) )
#define IPropertyStore_Commit(This) \
( (This)->lpVtbl -> Commit(This) )
--]]
| mit |
mafiesto4/Game1 | MyGame/MyGame/cocos2d/external/lua/luasocket/script/mime.lua | 149 | 2487 | -----------------------------------------------------------------------------
-- MIME support for the Lua language.
-- Author: Diego Nehab
-- Conforming to RFCs 2045-2049
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local ltn12 = require("ltn12")
local mime = require("mime.core")
local io = require("io")
local string = require("string")
local _M = mime
-- encode, decode and wrap algorithm tables
local encodet, decodet, wrapt = {},{},{}
_M.encodet = encodet
_M.decodet = decodet
_M.wrapt = wrapt
-- creates a function that chooses a filter by name from a given table
local function choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then
base.error("unknown key (" .. base.tostring(name) .. ")", 3)
else return f(opt1, opt2) end
end
end
-- define the encoding filters
encodet['base64'] = function()
return ltn12.filter.cycle(_M.b64, "")
end
encodet['quoted-printable'] = function(mode)
return ltn12.filter.cycle(_M.qp, "",
(mode == "binary") and "=0D=0A" or "\r\n")
end
-- define the decoding filters
decodet['base64'] = function()
return ltn12.filter.cycle(_M.unb64, "")
end
decodet['quoted-printable'] = function()
return ltn12.filter.cycle(_M.unqp, "")
end
local function format(chunk)
if chunk then
if chunk == "" then return "''"
else return string.len(chunk) end
else return "nil" end
end
-- define the line-wrap filters
wrapt['text'] = function(length)
length = length or 76
return ltn12.filter.cycle(_M.wrp, length, length)
end
wrapt['base64'] = wrapt['text']
wrapt['default'] = wrapt['text']
wrapt['quoted-printable'] = function()
return ltn12.filter.cycle(_M.qpwrp, 76, 76)
end
-- function that choose the encoding, decoding or wrap algorithm
_M.encode = choose(encodet)
_M.decode = choose(decodet)
_M.wrap = choose(wrapt)
-- define the end-of-line normalization filter
function _M.normalize(marker)
return ltn12.filter.cycle(_M.eol, 0, marker)
end
-- high level stuffing filter
function _M.stuff()
return ltn12.filter.cycle(_M.dot, 2)
end
return _M | gpl-2.0 |
Inquiryel/HPW_Rewrite-SBS | lua/hpwrewrite/datamanager.lua | 2 | 4869 | if not HpwRewrite then return end
HpwRewrite.DM = HpwRewrite.DM or { }
if not file.Exists("hpwrewrite", "DATA") then
file.CreateDir("hpwrewrite")
print("hpwrewrite folder has been created")
end
if CLIENT then
-- Binds
if not file.Exists("hpwrewrite/client", "DATA") then
file.CreateDir("hpwrewrite/client")
print("hpwrewrite/client folder has been created")
end
if not file.Exists("hpwrewrite/client/binds.txt", "DATA") then
local data = { ["Alpha"] = { } }
file.Write("hpwrewrite/client/binds.txt", util.TableToJSON(data))
print("hpwrewrite/client/binds.txt has been created")
end
function HpwRewrite.DM:ReadBinds()
local newfile = file.Read("hpwrewrite/client/binds.txt")
if not newfile then return end
local data = util.JSONToTable(newfile)
if not data then return end
-- Hotfix for numbers
for k, v in pairs(data) do
data[k] = nil
data[tostring(k)] = v
end
return data, "hpwrewrite/client/binds.txt"
end
-- Favourite spells
local name = "hpwrewrite/client/favourites.txt"
function HpwRewrite.DM:ReadFavourites()
local fav = file.Read(name)
if fav then
local spells = string.Explode("¤", fav)
return spells, name
end
end
function HpwRewrite.DM:AddToFavourites(spellName)
local fav = file.Read(name)
if fav then
file.Write(name, fav .. "¤" .. spellName)
HpwRewrite.FavouriteSpells[spellName] = true
end
end
function HpwRewrite.DM:RemoveFromFavourites(spellName)
local fav = file.Read(name)
if fav then
local target = "¤" .. spellName
file.Write(name, string.Replace(fav, target, ""))
HpwRewrite.FavouriteSpells[spellName] = false
end
end
if not file.Exists(name, "DATA") then
local data = ""
file.Write(name, data)
print("hpwrewrite/client/favourites.txt has been created")
else
local fav = HpwRewrite.DM:ReadFavourites()
if fav then
for k, v in pairs(fav) do
HpwRewrite.FavouriteSpells[v] = true
end
end
end
return
end
-- Config
if not file.Exists("hpwrewrite/cfg", "DATA") then
file.CreateDir("hpwrewrite/cfg")
print("hpwrewrite/cfg folder has been created")
end
if not file.Exists("hpwrewrite/cfg/config.txt", "DATA") then
local data = {
AdminOnly = { },
Blacklist = { },
DefaultSkin = "Wand"
}
file.Write("hpwrewrite/cfg/config.txt", util.TableToJSON(data))
print("hpwrewrite/cfg/config.txt has been created")
end
function HpwRewrite.DM:ReadConfig()
local newfile = file.Read("hpwrewrite/cfg/config.txt")
if not newfile then return end
local data = util.JSONToTable(newfile)
if not data then return end
return data, "hpwrewrite/cfg/config.txt"
end
-- Spells data
-- Learned and learnable
function HpwRewrite.DM:GetFilenameID(ply)
if ply.HpwRewrite.FILE_ID then
HpwRewrite:LogDebug("[Data] returning " .. ply.HpwRewrite.FILE_ID .. " for " .. ply:Name())
return ply.HpwRewrite.FILE_ID
end
local files, dirs = file.Find("hpwrewrite/*", "DATA")
for k, v in pairs(files) do
local path = "hpwrewrite/" .. v
local newfile = file.Read(path)
if newfile then
local data = util.JSONToTable(newfile)
if not data then
file.Delete(path)
continue
end
if data.SteamID == ply:SteamID() then
ply.HpwRewrite.FILE_ID = path
return path
end
end
end
local data = {
SteamID = ply:SteamID(),
Spells = { },
LearnableSpells = { }
}
local nicesteamid = string.gsub(ply:SteamID(), "[^%d]", "") .. "_" .. table.Count(files)
local filename = "hpwrewrite/" .. nicesteamid .. ".txt"
file.Write(filename, util.TableToJSON(data))
ply.HpwRewrite.FILE_ID = filename
HpwRewrite:LogDebug("[Data] " .. ply:Name() .. " has got filename id - " .. filename)
return filename
end
function HpwRewrite.DM:LoadDataFile(ply)
local filename = self:GetFilenameID(ply)
local getfile = file.Read(filename, "DATA")
if not getfile then
if not ply.HpwRewrite.Attempts then ply.HpwRewrite.Attempts = 0 end
ply.HpwRewrite.Attempts = ply.HpwRewrite.Attempts + 1
-- No recursion?
if ply.HpwRewrite.Attempts > 5 then
ErrorNoHalt("[ERROR] HPW: DATA FILE FOR " .. ply:Name() .. " CANNOT BE CREATED!\n")
return
end
ErrorNoHalt("[ERROR] HPW: DATA FILE FOR " .. ply:Name() .. " NOT FOUND! CREATING ANOTHER ONE... [Attempt: " .. ply.HpwRewrite.Attempts .. "]\n")
ply.HpwRewrite.FILE_ID = nil
return self:LoadDataFile(ply)
end
local data = util.JSONToTable(getfile)
if not data then
ErrorNoHalt("[ERROR] HPW: CAN'T READ DATA FILE (" .. filename .. ") FOR " .. ply:Name() .. "!\n")
ply.HpwRewrite.FILE_ID = nil
return nil, filename
end
if data.SteamID != ply:SteamID() then
ErrorNoHalt("[ERROR] HPW: UNEXPECTED STEAM ID: EXPECTED " .. data.SteamID .. ", GOT " .. ply:SteamID() .. " PLAYER " .. ply:Name() .. "\n")
ply.HpwRewrite.FILE_ID = nil
return nil, filename
end
ply.HpwRewrite.Attempts = 0
return data, filename
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.