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 |
|---|---|---|---|---|---|
larber/domoticz | scripts/dzVents/runtime/device-adapters/kwh_device.lua | 5 | 1123 | return {
baseType = 'device',
name = 'kWh device adapter',
matches = function (device, adapterManager)
local res = (device.deviceSubType == 'kWh')
if (not res) then
adapterManager.addDummyMethod(device, 'updateElectricity')
end
return res
end,
process = function (device, data, domoticz, utils, adapterManager)
-- from data: whAtual, whTotal
local formatted = device.counterToday or ''
local info = adapterManager.parseFormatted(formatted, domoticz['radixSeparator'])
-- as this is a kWh device we assume the value is in kWh
-- so we have to multiply it with 1000 to get it in W
device['WhToday'] = info['value'] * 1000
-- fix casing
device['whTotal'] = nil
device['WhTotal'] = data.data.whTotal
device['whActual'] = nil
device['WhActual'] = data.data.whActual
device['counterToday'] = info['value']
formatted = device.usage or ''
info = adapterManager.parseFormatted(formatted, domoticz['radixSeparator'])
device.usage = info['value']
function device.updateElectricity(power, energy)
device.update(0, tostring(power) .. ';' .. tostring(energy))
end
end
} | gpl-3.0 |
facebokiii/Uproject | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
teleblue/telele | plugins/gps.lua | 14 | 4662 | local function run(msg, matches)
local lat = matches[2]
local lon = matches[3]
local receiver = get_receiver(msg)
if matches[1] == "loc" then
send_location(receiver, lat, lon, ok_cb, false)
elseif matches[1] == "map" then
local zooms = {10, 16}
local urls = {}
for i = 1, #zooms do
local zoom = zooms[i]
local url = "http://maps.googleapis.com/maps/api/staticmap?zoom=" .. zoom .. "&size=600x300&maptype=roadmap¢er=" .. lat .. "," .. lon .. "&markers=color:blue%7Clabel:X%7C" .. lat .. "," .. lon
table.insert(urls, url)
end
send_photos_from_url(receiver, urls)
elseif matches[1] == "view" then
local zooms = {12, 18}
local urls = {}
for i = 1, #zooms do
local zoom = zooms[i]
local url = "http://maps.googleapis.com/maps/api/staticmap?zoom=" .. zoom .. "&size=600x300&maptype=hybrid¢er=" .. lat .. "," .. lon .. "&markers=color:blue%7Clabel:X%7C" .. lat .. "," .. lon
table.insert(urls, url)
end
send_photos_from_url(receiver, urls)
elseif matches[1] == "link" then
return "أ™â€¦أ™ث†أ™â€ڑأکآ¹أ™إ أکآھ أ™â€¦أڑآ©أکآ§أ™â€ أ™إ أکآ¯أکآ± أڑآ¯أ™ث†أڑآ¯أ™â€ أ™â€¦أ™آ¾:\nhttps://www.google.com/maps/place/" .. lat .. "," .. lon
end
end
return {
description = "Generate Map for GPS Coordinates",
usagehtm = '<tr><td align="center">gps loc أکآ¹أکآ±أکآ¶ أکآ¬أکآ؛أکآ±أکآ§أ™آپأ›إ’أکآ§أ›إ’أ›إ’,أکآ·أ™ث†أ™â€ أکآ¬أکآ؛أکآ±أکآ§أ™آپأ›إ’أکآ§أ›إ’أ›إ’</td><td align="right">أ™â€ أ™â€¦أکآ§أ›إ’أکآ´ أ™â€¦أ™ث†أ™â€ڑأکآ¹أ›إ’أکآھ أ™â€¦أڑآ©أکآ§أ™â€ أ›إ’ أ™â€¦أکآ®أکآھأکآµأکآ§أکآھ أ™ث†أکآ§أکآ±أکآ¯ أکآ´أکآ¯أ™â€، أکآ¯أکآ± أ™â€ڑأکآ§أ™â€أکآ¨ أ™â€أ™ث†أڑآ©أ›إ’أکآ´أ™â€ </td></tr>'
..'<tr><td align="center">gps link أکآ¹أکآ±أکآ¶ أکآ¬أکآ؛أکآ±أکآ§أ™آپأ›إ’أکآ§أ›إ’أ›إ’,أکآ·أ™ث†أ™â€ أکآ¬أکآ؛أکآ±أکآ§أ™آپأ›إ’أکآ§أ›إ’أ›إ’</td><td align="right">أکآ§أکآ±أکآ§أکآ¦أ™â€، أ›إ’ أ™â€أ›إ’أ™â€ أڑآ© أ™â€أ™ث†أڑآ¯أ™â€ أ™â€¦أ™آ¾ أکآ§أکآ² أ™â€¦أکآ®أکآھأکآµأکآ§أکآھ أ™ث†أکآ§أکآ±أکآ¯ أکآ´أکآ¯أ™â€،</td></tr>'
..'<tr><td align="center">gps map أکآ¹أکآ±أکآ¶ أکآ¬أکآ؛أکآ±أکآ§أ™آپأ›إ’أکآ§أ›إ’أ›إ’,أکآ·أ™ث†أ™â€ أکآ¬أکآ؛أکآ±أکآ§أ™آپأ›إ’أکآ§أ›إ’أ›إ’</td><td align="right">أ™â€ أ™â€¦أکآ§أ›إ’أکآ´ أ™â€ أ™â€ڑأکآ´أ™â€، أ›إ’ أ™â€¦أکآ®أکآھأکآµأکآ§أکآھ أ™ث†أکآ§أکآ±أکآ¯ أکآ´أکآ¯أ™â€، أکآ¯أکآ± أ™â€ڑأکآ§أ™â€أکآ¨ أکآ¹أڑآ©أکآ³</td></tr>'
..'<tr><td align="center">gps view أکآ¹أکآ±أکآ¶ أکآ¬أکآ؛أکآ±أکآ§أ™آپأ›إ’أکآ§أ›إ’أ›إ’,أکآ·أ™ث†أ™â€ أکآ¬أکآ؛أکآ±أکآ§أ™آپأ›إ’أکآ§أ›إ’أ›إ’</td><td align="right">أ™â€ أ™â€¦أکآ§أ›إ’أکآ´ أکآھأکآµأ™ث†أ›إ’أکآ± أکآ²أ™â€ أکآ¯أ™â€، أ™â€¦أڑآ©أکآ§أ™â€ أ›إ’ أ™â€¦أکآ®أکآھأکآµأکآ§أکآھ أ™ث†أکآ§أکآ±أکآ¯ أکآ´أکآ¯أ™â€، أکآ¯أکآ± أ™â€ڑأکآ§أ™â€أکآ¨ أکآ¹أڑآ©أکآ³</td></tr>',
usage = {
"gps loc (lat,lon) : أ™â€أ™ث†أڑآ©أ™إ أکآ´أ™â€ أ™â€¦أ™ث†أ™â€ڑأکآ¹أ™إ أکآھ",
"gps link (lat,lon) : أ™â€أ™إ أ™â€ أڑآ© أڑآ¯أ™ث†أڑآ¯أ™â€ أ™â€¦أ™آ¾",
"gps map (lat,lon) : أ™â€ أ™â€ڑأکآ´أ™â€، أ™â€¦أ™ث†أ™â€ڑأکآ¹أ™إ أکآھ",
"gps view (lat,lon) : أکآھأکآµأ™ث†أ™إ أکآ± أ™ث†أکآ§أ™â€ڑأکآ¹أ™إ ",
},
patterns = {
"^[#!/][Gg]ps (loc) ([^,]*)[,%s]([^,]*)$",
"^[#!/][Gg]ps (map) ([^,]*)[,%s]([^,]*)$",
"^[#!/][Gg]ps (view) ([^,]*)[,%s]([^,]*)$",
"^[#!/][Gg]ps (link) ([^,]*)[,%s]([^,]*)$",
},
run = run
}
| gpl-2.0 |
amirb8/TELEHONES- | plugins/ingroup.lua | 371 | 44212 | 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']
local user_info = redis:hgetall('user:'..group_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")
if user_info.username then
return "Group onwer is @"..user_info.username.." ["..group_owner.."]"
else
return "Group owner is ["..group_owner..']'
end
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 |
DevMoataz/Maestro | plugins/newgroup.lua | 2 | 36187 | --[[
_ _ _ _____ _____ ____ ____
/ \ / \ / \ | ____|___|_ _| /_\ \ / __ \ Đєⱴ 💀: @MaEsTrO_0
/ / \/ / \ / _ \ | _| / __| | | | |_\_/| | | | Đєⱴ 💀: @devmaestr0
/ / \ \/ \ \ / ___ \| |___\__ \ | | | | \ \| |__| | Đєⱴ ฿๏ͳ💀: @iqMaestroBot
/_/ \/ \_/_/ \_|_____|___/ |_| |_| \_\\____/ Đєⱴ ฿๏ͳ💀: @maestr0bot
Đєⱴ Ϲḫ₳ͷͷєℓ💀: @DevMaestro
—]]
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'المجموعة 👥 [ '..string.gsub(group_name, '_', ' ')..' ] \n تمت صناعة المجموعة👥 '
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.peer_id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.peer_id, result.peer_id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.peer_id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.peer_id, result.peer_id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
if msg.to.type == 'chat' and not is_realm(msg) then
data[tostring(msg.to.id)]['group_type'] = 'Group'
save_data(_config.moderation.data, data)
elseif msg.to.type == 'channel' then
data[tostring(msg.to.id)]['group_type'] = 'SuperGroup'
save_data(_config.moderation.data, data)
end
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
local channel = 'channel#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
send_large_msg(channel, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin1(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_arabic(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic/Persian is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic/Persian has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTL char. in names is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL char. in names is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been unlocked'
end
end
local function lock_group_links(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'Link posting is already locked'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link posting has been locked'
end
end
local function unlock_group_links(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_spam(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'SuperGroup spam is already locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been locked'
end
end
local function unlock_group_spam(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'SuperGroup spam is not locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTL char. in names is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL char. in names is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_public_lock = data[tostring(target)]['settings']['public']
if group_public_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'SuperGroup is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_public_lock = data[tostring(target)]['settings']['public']
if group_public_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup is now: not public'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin1(msg) then
return "For admins only!"
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings for "..target..":\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nPublic: "..settings.public
end
-- show SuperGroup settings
local function show_super_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin1(msg) then
return "For admins only!"
end
if data[tostring(msg.to.id)]['settings'] then
if not data[tostring(msg.to.id)]['settings']['public'] then
data[tostring(msg.to.id)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict
return text
end
local function returnids(cb_extra, success, result)
local i = 1
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.peer_id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' (ID: '..result.peer_id..'):\n\n'
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text ..i..' - '.. string.gsub(v.print_name,"_"," ") .. " [" .. v.peer_id .. "] \n\n"
i = i + 1
end
end
local file = io.open("./groups/lists/"..result.peer_id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function cb_user_info(cb_extra, success, result)
local receiver = cb_extra.receiver
if result.first_name then
first_name = result.first_name:gsub("_", " ")
else
first_name = "None"
end
if result.last_name then
last_name = result.last_name:gsub("_", " ")
else
last_name = "None"
end
if result.username then
username = "@"..result.username
else
username = "@[none]"
end
text = "User Info:\n\nID: "..result.peer_id.."\nFirst: "..first_name.."\nLast: "..last_name.."\nUsername: "..username
send_large_msg(receiver, text)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List of global admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
if data[tostring(v)] then
if data[tostring(v)]['settings'] then
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
end
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, '@'..member_username..' is already an admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
send_large_msg(receiver, "@"..member_username..' is not an admin.')
return
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Admin @'..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.peer_id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function res_user_support(cb_extra, success, result)
local receiver = cb_extra.receiver
local get_cmd = cb_extra.get_cmd
local support_id = result.peer_id
if get_cmd == 'addsupport' then
support_add(support_id)
send_large_msg(receiver, "User ["..support_id.."] has been added to the support team")
elseif get_cmd == 'removesupport' then
support_remove(support_id)
send_large_msg(receiver, "User ["..support_id.."] has been removed from the support team")
end
end
local function set_log_group(target, data)
if not is_admin1(msg) then
return
end
local log_group = data[tostring(target)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(target)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin1(msg) then
return
end
local log_group = data[tostring(target)]['log_group']
if log_group == 'no' then
return 'Log group is not set'
else
data[tostring(target)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
local receiver = get_receiver(msg)
savelog(msg.to.id, "log file created by owner/support/admin")
send_document(receiver,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and msg.to.type == 'chat' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
local file = io.open("./groups/lists/"..msg.to.id.."memberlist.txt", "r")
text = file:read("*a")
send_large_msg(receiver,text)
file:close()
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
send_document("chat#id"..msg.to.id,"./groups/lists/"..msg.to.id.."memberlist.txt", ok_cb, false)
end
if matches[1] == 'whois' and is_momod(msg) then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
user_info(user_id, cb_user_info, {receiver = receiver})
end
if not is_sudo(msg) then
if is_realm(msg) and is_admin1(msg) then
print("Admin detected")
else
return
end
end
if matches[1] == 'صنع مجموعه' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
--[[ Experimental
if matches[1] == 'createsuper' and matches[2] then
if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then
return "You cant create groups!"
end
group_name = matches[2]
group_type = 'super_group'
return create_group(msg)
end]]
if matches[1] == 'createrealm' and matches[2] then
if not is_sudo(msg) then
return "Sudo users only !"
end
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[1] == 'setabout' and matches[2] == 'group' and is_realm(msg) then
local target = matches[3]
local about = matches[4]
return set_description(msg, data, target, about)
end
if matches[1] == 'setabout' and matches[2] == 'sgroup'and is_realm(msg) then
local channel = 'channel#id'..matches[3]
local about_text = matches[4]
local data_cat = 'description'
local target = matches[3]
channel_set_about(channel, about_text, ok_cb, false)
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
return "Description has been set for ["..matches[2]..']'
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
if matches[2] == 'arabic' then
return lock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
return lock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
return lock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
return lock_group_sticker(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
if matches[3] == 'arabic' then
return unlock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
return unlock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
return unlock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
return unlock_group_sticker(msg, data, target)
end
end
if matches[1] == 'settings' and matches[2] == 'group' and data[tostring(matches[3])]['settings'] then
local target = matches[3]
text = show_group_settingsmod(msg, target)
return text.."\nID: "..target.."\n"
end
if matches[1] == 'settings' and matches[2] == 'sgroup' and data[tostring(matches[3])]['settings'] then
local target = matches[3]
text = show_supergroup_settingsmod(msg, target)
return text.."\nID: "..target.."\n"
end
if matches[1] == 'setname' and is_realm(msg) then
local settings = data[tostring(matches[2])]['settings']
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin1(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local chat_to_rename = 'chat#id'..matches[2]
local channel_to_rename = 'channel#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
rename_channel(channel_to_rename, group_name_set, ok_cb, false)
savelog(matches[3], "Group { "..group_name_set.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
--[[if matches[1] == 'set' then
if matches[2] == 'loggroup' and is_sudo(msg) then
local target = msg.to.peer_id
savelog(msg.to.peer_id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(target, data)
end
end
if matches[1] == 'rem' then
if matches[2] == 'loggroup' and is_sudo(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return unset_log_group(target, data)
end
end]]
if matches[1] == 'kill' and matches[2] == 'chat' and matches[3] then
if not is_admin1(msg) then
return
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' and matches[3] then
if not is_admin1(msg) then
return
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'rem' and matches[2] then
-- Group configuration removal
data[tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Chat '..matches[2]..' removed')
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin1(msg) and is_realm(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if not is_sudo(msg) then-- Sudo only
return
end
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if not is_sudo(msg) then-- Sudo only
return
end
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'support' and matches[2] then
if string.match(matches[2], '^%d+$') then
local support_id = matches[2]
print("User "..support_id.." has been added to the support team")
support_add(support_id)
return "User ["..support_id.."] has been added to the support team"
else
local member = string.gsub(matches[2], "@", "")
local receiver = get_receiver(msg)
local get_cmd = "addsupport"
resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver})
end
end
if matches[1] == '-support' then
if string.match(matches[2], '^%d+$') then
local support_id = matches[2]
print("User "..support_id.." has been removed from the support team")
support_remove(support_id)
return "User ["..support_id.."] has been removed from the support team"
else
local member = string.gsub(matches[2], "@", "")
local receiver = get_receiver(msg)
local get_cmd = "removesupport"
resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' then
if matches[2] == 'admins' then
return admin_list(msg)
end
-- if matches[2] == 'support' and not matches[2] then
-- return support_list()
-- end
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' or msg.to.type == 'channel' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
send_document("channel#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' or msg.to.type == 'channel' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
send_document("channel#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^(صنع مجموعه) (.*)$",
"^[#!/](صنع مجموعه) (.*)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Scentus/PonyPlayerModels | pony_player_models/lua/ppm/preset.lua | 2 | 2568 |
PPM.bannedVars = {"m_bodyt0"}
-- NOTABLE LIMITATION: WILL REMOVE SPACES FROM STRINGS TYPE ITEMS BEFORE SAVING AND WILL REFUSE TO LOAD THEM PROPERLY
-- (THIS IS A LIMITATION OF THE ORIGINAL FORMAT FROM A PRIOR AUTHOR AND MAY BE FIXED LATER WITH A WORKAROUND IF IT EVER BECOMES NEEDED)
function PPM.PonyDataToString( ponydata )
local saveframe = {}
for k,v in SortedPairs( ponydata ) do
if not table.HasValue( PPM.bannedVars, k ) then
if type(v) == "number" then
table.insert( saveframe, "\n " .. k .. " " .. tostring(v) )
elseif type(v) == "Vector" then
table.insert( saveframe, "\n " .. k .. " " .. tostring(v) )
elseif type(v) == "boolean" then
table.insert( saveframe, "\n " .. k .. " b " .. tostring(v) )
elseif type(v) == "string" then
table.insert( saveframe, "\n " .. k .. " s " .. string.Replace( v, " ", "" ) )
end
end
end
return table.concat( saveframe )
end
function PPM.StringToPonyData( str )
local lines = string.Split( str, "\n" )
local ponydata = {}
for k,v in pairs( lines ) do
local args = string.Split( string.Trim(v), " " )
local name = string.Replace( args[1], "pny_", "" )
if not table.HasValue( PPM.bannedVars, name ) then
if( table.Count(args) == 2 ) then
ponydata[name] =tonumber( args[2] )
elseif( table.Count(args) == 4 ) then
ponydata[name] =Vector( tonumber( args[2] ), tonumber( args[3] ), tonumber( args[4] ) )
elseif( table.Count(args) == 3 ) then
if args[2] == "b" then
ponydata[name] = tobool( args[3] )
elseif args[2] == "s" then
ponydata[name] = args[3]
end
end
end
end
-- Perform simple data validation (May add more here later if players start finding ways to mess up their pony files)
if ponydata.custom_mark ~= nil and type( ponydata.custom_mark ) ~= "string" then
ponydata.custom_mark = nil
end
return ponydata
end
if CLIENT then
function PPM.Save(filename, ponydata)
local saveframe = PPM.PonyDataToString( ponydata )
if !string.EndsWith( filename,".txt" ) then
filename = filename .. ".txt"
end
if !file.Exists( "ppm", "DATA" ) then
file.CreateDir( "ppm" )
end
MsgN( "saving .... " .. "ppm/" .. filename )
file.Write( "ppm/" .. filename, saveframe )
return PPM.SaveToCache( PPM.CacheGroups.OC_DATA, LocalPlayer(), filename, saveframe )
end
function PPM.Load(filename)
local data = file.Read("data/ppm/"..filename,"GAME")
return PPM.StringToPonyData( data )
end
end | gpl-3.0 |
stephank/luci | libs/web/luasrc/http/protocol/mime.lua | 88 | 2933 | --[[
HTTP protocol implementation for LuCI - mime handling
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
--- LuCI http protocol implementation - mime helper class.
-- This class provides functions to guess mime types from file extensions and
-- vice versa.
module("luci.http.protocol.mime", package.seeall)
require("luci.util")
--- MIME mapping table containg extension - mimetype relations.
-- @class table
MIME_TYPES = {
["txt"] = "text/plain";
["js"] = "text/javascript";
["css"] = "text/css";
["htm"] = "text/html";
["html"] = "text/html";
["patch"] = "text/x-patch";
["c"] = "text/x-csrc";
["h"] = "text/x-chdr";
["o"] = "text/x-object";
["ko"] = "text/x-object";
["bmp"] = "image/bmp";
["gif"] = "image/gif";
["png"] = "image/png";
["jpg"] = "image/jpeg";
["jpeg"] = "image/jpeg";
["svg"] = "image/svg+xml";
["zip"] = "application/zip";
["pdf"] = "application/pdf";
["xml"] = "application/xml";
["xsl"] = "application/xml";
["doc"] = "application/msword";
["ppt"] = "application/vnd.ms-powerpoint";
["xls"] = "application/vnd.ms-excel";
["odt"] = "application/vnd.oasis.opendocument.text";
["odp"] = "application/vnd.oasis.opendocument.presentation";
["pl"] = "application/x-perl";
["sh"] = "application/x-shellscript";
["php"] = "application/x-php";
["deb"] = "application/x-deb";
["iso"] = "application/x-cd-image";
["tgz"] = "application/x-compressed-tar";
["mp3"] = "audio/mpeg";
["ogg"] = "audio/x-vorbis+ogg";
["wav"] = "audio/x-wav";
["mpg"] = "video/mpeg";
["mpeg"] = "video/mpeg";
["avi"] = "video/x-msvideo";
}
--- Extract extension from a filename and return corresponding mime-type or
-- "application/octet-stream" if the extension is unknown.
-- @param filename The filename for which the mime type is guessed
-- @return String containign the determined mime type
function to_mime(filename)
if type(filename) == "string" then
local ext = filename:match("[^%.]+$")
if ext and MIME_TYPES[ext:lower()] then
return MIME_TYPES[ext:lower()]
end
end
return "application/octet-stream"
end
--- Return corresponding extension for a given mime type or nil if the
-- given mime-type is unknown.
-- @param mimetype The mimetype to retrieve the extension from
-- @return String with the extension or nil for unknown type
function to_ext(mimetype)
if type(mimetype) == "string" then
for ext, type in luci.util.kspairs( MIME_TYPES ) do
if type == mimetype then
return ext
end
end
end
return nil
end
| apache-2.0 |
jsphweid/finale-macros | lua/time-sigs-score-big.lua | 2 | 1049 | function plugindef()
finaleplugin.Author = "Joseph Weidinger"
finaleplugin.Version = "1.0"
finaleplugin.Date = "July 02, 2015"
finaleplugin.RequireSelection = false
finaleplugin.CategoryTags = "make big time signatures in score"
return "Time Signatures - Score - Make Big", "Time Signatures - Score - Make Big", "Score - Big Time Sigs"
end
function setFont(fontID, fontName, fontSize, topSymbol, bottomSymbol)
-- load font preferences for fontID
local fontPrefs = finale.FCFontPrefs()
fontPrefs:Load(fontID)
local fontInfo = fontPrefs:CreateFontInfo()
-- set name / size
fontInfo:SetName(fontName)
fontInfo:SetSize(fontSize)
-- save it back
fontPrefs:SetFontInfo(fontInfo)
fontPrefs:Save()
local distanceprefs = finale.FCDistancePrefs()
distanceprefs:Load(1)
distanceprefs.TimeSigTopVertical = topSymbol
distanceprefs.TimeSigBottomVertical = bottomSymbol
distanceprefs:Save()
end
setFont(finale.FONTPREF_TIMESIG, "EngraverTime", 40, 0, -290)
-- show only top (can use other script to display)
| mit |
artynet/luci | modules/luci-base/luasrc/tools/status.lua | 1 | 6237 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.tools.status", package.seeall)
local uci = require "luci.model.uci".cursor()
local ipc = require "luci.ip"
local function dhcp_leases_common(family)
local rv = { }
local nfs = require "nixio.fs"
local sys = require "luci.sys"
local leasefile = "/tmp/dhcp.leases"
uci:foreach("dhcp", "dnsmasq",
function(s)
if s.leasefile and nfs.access(s.leasefile) then
leasefile = s.leasefile
return false
end
end)
local fd = io.open(leasefile, "r")
if fd then
while true do
local ln = fd:read("*l")
if not ln then
break
else
local ts, mac, ip, name, duid = ln:match("^(%d+) (%S+) (%S+) (%S+) (%S+)")
local expire = tonumber(ts) or 0
if ts and mac and ip and name and duid then
if family == 4 and not ip:match(":") then
rv[#rv+1] = {
expires = (expire ~= 0) and os.difftime(expire, os.time()),
macaddr = ipc.checkmac(mac) or "00:00:00:00:00:00",
ipaddr = ip,
hostname = (name ~= "*") and name
}
elseif family == 6 and ip:match(":") then
rv[#rv+1] = {
expires = (expire ~= 0) and os.difftime(expire, os.time()),
ip6addr = ip,
duid = (duid ~= "*") and duid,
hostname = (name ~= "*") and name
}
end
end
end
end
fd:close()
end
local lease6file = "/tmp/hosts/odhcpd"
uci:foreach("dhcp", "odhcpd",
function(t)
if t.leasefile and nfs.access(t.leasefile) then
lease6file = t.leasefile
return false
end
end)
local fd = io.open(lease6file, "r")
if fd then
while true do
local ln = fd:read("*l")
if not ln then
break
else
local iface, duid, iaid, name, ts, id, length, ip = ln:match("^# (%S+) (%S+) (%S+) (%S+) (-?%d+) (%S+) (%S+) (.*)")
local expire = tonumber(ts) or 0
if ip and iaid ~= "ipv4" and family == 6 then
rv[#rv+1] = {
expires = (expire >= 0) and os.difftime(expire, os.time()),
duid = duid,
ip6addr = ip,
hostname = (name ~= "-") and name
}
elseif ip and iaid == "ipv4" and family == 4 then
rv[#rv+1] = {
expires = (expire >= 0) and os.difftime(expire, os.time()),
macaddr = sys.net.duid_to_mac(duid) or "00:00:00:00:00:00",
ipaddr = ip,
hostname = (name ~= "-") and name
}
end
end
end
fd:close()
end
if family == 6 then
local _, lease
local hosts = sys.net.host_hints()
for _, lease in ipairs(rv) do
local mac = sys.net.duid_to_mac(lease.duid)
local host = mac and hosts[mac]
if host then
if not lease.name then
lease.host_hint = host.name or host.ipv4 or host.ipv6
elseif host.name and lease.hostname ~= host.name then
lease.host_hint = host.name
end
end
end
end
return rv
end
function dhcp_leases()
return dhcp_leases_common(4)
end
function dhcp6_leases()
return dhcp_leases_common(6)
end
function wifi_networks()
local rv = { }
local ntm = require "luci.model.network".init()
local dev
for _, dev in ipairs(ntm:get_wifidevs()) do
local rd = {
up = dev:is_up(),
device = dev:name(),
name = dev:get_i18n(),
networks = { }
}
local net
for _, net in ipairs(dev:get_wifinets()) do
local a, an = nil, 0
for _, a in pairs(net:assoclist() or {}) do
an = an + 1
end
rd.networks[#rd.networks+1] = {
name = net:shortname(),
link = net:adminlink(),
up = net:is_up(),
mode = net:active_mode(),
ssid = net:active_ssid(),
bssid = net:active_bssid(),
encryption = net:active_encryption(),
frequency = net:frequency(),
channel = net:channel(),
signal = net:signal(),
quality = net:signal_percent(),
noise = net:noise(),
bitrate = net:bitrate(),
ifname = net:ifname(),
country = net:country(),
txpower = net:txpower(),
txpoweroff = net:txpower_offset(),
num_assoc = an,
disabled = (dev:get("disabled") == "1" or
net:get("disabled") == "1")
}
end
rv[#rv+1] = rd
end
return rv
end
function wifi_network(id)
local ntm = require "luci.model.network".init()
local net = ntm:get_wifinet(id)
if net then
local dev = net:get_device()
if dev then
return {
id = id,
name = net:shortname(),
link = net:adminlink(),
up = net:is_up(),
mode = net:active_mode(),
ssid = net:active_ssid(),
bssid = net:active_bssid(),
encryption = net:active_encryption(),
frequency = net:frequency(),
channel = net:channel(),
signal = net:signal(),
quality = net:signal_percent(),
noise = net:noise(),
bitrate = net:bitrate(),
ifname = net:ifname(),
country = net:country(),
txpower = net:txpower(),
txpoweroff = net:txpower_offset(),
disabled = (dev:get("disabled") == "1" or
net:get("disabled") == "1"),
device = {
up = dev:is_up(),
device = dev:name(),
name = dev:get_i18n()
}
}
end
end
return { }
end
function wifi_assoclist()
local sys = require "luci.sys"
local ntm = require "luci.model.network".init()
local hosts = sys.net.host_hints()
local assoc = {}
local _, dev, net, bss
for _, dev in ipairs(ntm:get_wifidevs()) do
local radioname = dev:get_i18n()
for _, net in ipairs(dev:get_wifinets()) do
local netname = net:shortname()
local netlink = net:adminlink()
local ifname = net:ifname()
for _, bss in pairs(net:assoclist() or {}) do
local host = hosts[_]
bss.bssid = _
bss.ifname = ifname
bss.radio = radioname
bss.name = netname
bss.link = netlink
bss.host_name = (host) and (host.name or host.ipv4 or host.ipv6)
bss.host_hint = (host and host.name and (host.ipv4 or host.ipv6)) and (host.ipv4 or host.ipv6)
assoc[#assoc+1] = bss
end
end
end
table.sort(assoc, function(a, b)
if a.radio ~= b.radio then
return a.radio < b.radio
elseif a.ifname ~= b.ifname then
return a.ifname < b.ifname
else
return a.bssid < b.bssid
end
end)
return assoc
end
| apache-2.0 |
UnluckyNinja/PathOfBuilding | Data/2_6/Skills/other.lua | 1 | 22167 | -- This file is automatically generated, do not edit!
-- Path of Building
--
-- Other active skills
-- Skill data (c) Grinding Gear Games
--
local skills, mod, flag, skill = ...
skills["Melee"] = {
name = "Default Attack",
hidden = true,
color = 4,
description = "Strike your foes down with a powerful blow.",
skillTypes = { [1] = true, [48] = true, [6] = true, [3] = true, [25] = true, [28] = true, [24] = true, },
baseFlags = {
attack = true,
melee = true,
projectile = true,
},
baseMods = {
skill("castTime", 1),
--"skill_can_fire_arrows" = 1
--"skill_can_fire_wand_projectiles" = 1
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[1] = { 1, },
},
}
skills["GemDetonateMines"] = {
name = "Detonate Mines",
gemTags = {
low_max_level = true,
active_skill = true,
spell = true,
},
gemTagString = "Spell",
gemStr = 33,
gemDex = 33,
gemInt = 34,
color = 4,
description = "Detonates all the Remote Mines you have placed.",
skillTypes = { [2] = true, [17] = true, [18] = true, [36] = true, },
baseFlags = {
spell = true,
},
baseMods = {
skill("castTime", 0.2),
--"base_deal_no_damage" = ?
},
qualityMods = {
mod("Speed", "INC", 5, ModFlag.Cast), --"base_cast_speed_+%" = 5
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[1] = { 8, },
[2] = { 8, },
[3] = { 8, },
[4] = { 8, },
[5] = { 8, },
[6] = { 8, },
[7] = { 8, },
[8] = { 8, },
[9] = { 8, },
[10] = { 8, },
},
}
skills["Portal"] = {
name = "Portal",
gemTags = {
low_max_level = true,
active_skill = true,
spell = true,
},
gemTagString = "Spell",
gemStr = 33,
gemDex = 33,
gemInt = 34,
color = 4,
description = "Creates a portal to the current area's town.",
skillTypes = { [2] = true, [17] = true, [18] = true, [19] = true, [36] = true, [27] = true, },
baseFlags = {
spell = true,
},
baseMods = {
skill("castTime", 2.5),
--"base_deal_no_damage" = ?
},
qualityMods = {
mod("Speed", "INC", 3, ModFlag.Cast), --"base_cast_speed_+%" = 3
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[1] = { 10, },
[2] = { 10, },
[3] = { 10, },
[4] = { 10, },
[5] = { 10, },
[6] = { 10, },
[7] = { 10, },
[8] = { 10, },
[9] = { 10, },
[10] = { 10, },
},
}
skills["SupportUniqueMjolnerLightningSpellsCastOnHit"] = {
name = "Mjolner",
hidden = true,
color = 4,
support = true,
requireSkillTypes = { 45, },
addSkillTypes = { 42, },
excludeSkillTypes = { 37, 41, 30, 44, 61, },
fromItem = true,
baseMods = {
skill("cooldown", 0.25),
mod("Damage", "INC", 100, ModFlag.Spell, 0, { type = "Condition", var = "SkillIsTriggered" }), --"triggered_spell_spell_damage_+%" = 100
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"unique_mjolner_lightning_spells_triggered" = ?
},
qualityMods = {
},
levelMods = {
[1] = nil,
},
levels = {
[1] = { 0, },
},
}
skills["SupportUniqueCosprisMaliceColdSpellsCastOnMeleeCriticalStrike"] = {
name = "Cospri's Malice",
hidden = true,
color = 4,
support = true,
requireSkillTypes = { 60, },
addSkillTypes = { },
excludeSkillTypes = { 37, 41, 30, 44, 61, },
fromItem = true,
baseMods = {
skill("cooldown", 0.25),
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"unique_cospris_malice_cold_spells_triggered" = ?
},
qualityMods = {
},
levelMods = {
[1] = nil,
},
levels = {
[1] = { 1, },
},
}
skills["RepeatingShockwave"] = {
name = "Abberath's Fury",
hidden = true,
color = 4,
description = "While you run, this skill creates a small explosion with each step, dealing fire damage in an area around you.",
skillTypes = { [11] = true, [36] = true, [42] = true, [2] = true, [10] = true, [61] = true, },
fromItem = true,
baseFlags = {
spell = true,
area = true,
},
baseMods = {
skill("castTime", 1),
skill("CritChance", 5),
skill("FireMin", 50), --"spell_minimum_base_fire_damage" = 50
skill("FireMax", 75), --"spell_maximum_base_fire_damage" = 75
mod("EnemyIgniteChance", "BASE", 10), --"base_chance_to_ignite_%" = 10
--"cast_on_gain_skill" = ?
--"cannot_knockback" = ?
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
--"is_area_damage" = ?
--"skill_can_add_multiple_charges_per_action" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[7] = { 1, },
},
}
skills["TriggeredBoneNova"] = {
name = "Bone Nova",
hidden = true,
color = 4,
description = "A spiral of bones erupts around you, dealing physical damage.",
skillTypes = { [1] = true, [48] = true, [3] = true, [10] = true, [57] = true, [47] = true, [61] = true, },
fromItem = true,
baseFlags = {
attack = true,
projectile = true,
},
baseMods = {
skill("castTime", 1),
skill("cooldown", 0.5),
mod("ProjectileCount", "BASE", 8), --"number_of_additional_projectiles" = 8
--"attack_trigger_on_killing_bleeding_enemy_%" = 100
--"monster_projectile_variation" = 15
--"projectiles_nova" = ?
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
--"base_is_projectile" = ?
flag("CannotBleed"), --"cannot_cause_bleeding" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[20] = { 1, },
},
}
skills["TriggeredConsecrate"] = {
name = "Consecrate",
hidden = true,
color = 4,
description = "Creates an area of Consecrated Ground, providing life regeneration for you and allies who stand in it.",
skillTypes = { [2] = true, [12] = true, [36] = true, [11] = true, [42] = true, [61] = true, },
fromItem = true,
baseFlags = {
spell = true,
duration = true,
area = true,
},
baseMods = {
skill("castTime", 1),
skill("cooldown", 5),
skill("duration", 5), --"base_skill_effect_duration" = 5000
mod("LifeRegenPercent", "BASE", 4, 0, 0, nil), --"life_regeneration_rate_per_minute_%" = 240
--"cast_on_crit_%" = 100
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[10] = { 1, },
},
}
skills["TriggeredSummonLesserShrine"] = {
name = "Create Lesser Shrine",
hidden = true,
color = 4,
description = "Creates a Lesser Shrine, which will grant a bonus when touched. The Lesser Shrine will disappear after a short duration, or when used. This skill starts on cooldown.",
skillTypes = { [2] = true, [36] = true, [42] = true, [61] = true, [12] = true, },
fromItem = true,
baseFlags = {
spell = true,
duration = true,
},
baseMods = {
skill("castTime", 1),
skill("cooldown", 20),
--"chance_to_cast_on_kill_%" = 100
skill("duration", 10), --"base_skill_effect_duration" = 10000
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[1] = { 1, },
},
}
skills["Envy"] = {
name = "Envy",
hidden = true,
color = 3,
description = "Casts an aura that adds chaos damage to the attacks and spells of you and your allies.",
skillTypes = { [2] = true, [11] = true, [5] = true, [15] = true, [27] = true, [16] = true, [18] = true, [44] = true, [50] = true, },
fromItem = true,
baseFlags = {
spell = true,
aura = true,
area = true,
chaos = true,
},
baseMods = {
skill("castTime", 1.2),
skill("manaCost", 50),
skill("cooldown", 1.2),
mod("ChaosMin", "BASE", 58, ModFlag.Attack, 0, { type = "GlobalEffect", effectType = "Aura" }), --"attack_minimum_added_chaos_damage" = 58
mod("ChaosMax", "BASE", 81, ModFlag.Attack, 0, { type = "GlobalEffect", effectType = "Aura" }), --"attack_maximum_added_chaos_damage" = 81
mod("AreaOfEffect", "INC", 0), --"base_skill_area_of_effect_+%" = 0
mod("ChaosMin", "BASE", 52, ModFlag.Spell, 0, { type = "GlobalEffect", effectType = "Aura" }), --"spell_minimum_added_chaos_damage" = 52
mod("ChaosMax", "BASE", 69, ModFlag.Spell, 0, { type = "GlobalEffect", effectType = "Aura" }), --"spell_maximum_added_chaos_damage" = 69
--"base_deal_no_damage" = ?
skill("radius", 36),
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[15] = { 60, },
},
}
skills["FireBurstOnHit"] = {
name = "Fire Burst",
hidden = true,
color = 4,
description = "A burst of flame errupts from the location of a hit, dealing fire damage.",
skillTypes = { [2] = true, [11] = true, [10] = true, [33] = true, [36] = true, [42] = true, [61] = true, },
fromItem = true,
baseFlags = {
spell = true,
area = true,
fire = true,
},
baseMods = {
skill("castTime", 1),
skill("damageEffectiveness", 0.5),
skill("CritChance", 5),
skill("cooldown", 0.5),
--"cast_on_hit_%" = 10
--"is_area_damage" = ?
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
[2] = skill("FireMin", nil), --"spell_minimum_base_fire_damage"
[3] = skill("FireMax", nil), --"spell_maximum_base_fire_damage"
},
levels = {
[1] = { 1, 7, 11, },
[2] = { 2, 8, 12, },
[3] = { 4, 10, 16, },
[4] = { 7, 14, 21, },
[5] = { 11, 20, 30, },
[6] = { 16, 30, 46, },
[7] = { 20, 41, 61, },
[8] = { 24, 54, 80, },
[9] = { 28, 70, 104, },
[10] = { 32, 89, 134, },
[11] = { 36, 114, 170, },
[12] = { 40, 143, 215, },
[13] = { 44, 180, 270, },
[14] = { 48, 224, 336, },
[15] = { 52, 278, 418, },
[16] = { 56, 344, 516, },
[17] = { 60, 424, 636, },
[18] = { 64, 520, 780, },
[19] = { 67, 605, 908, },
[20] = { 70, 703, 1055, },
[21] = { 72, 777, 1165, },
[22] = { 74, 858, 1286, },
[23] = { 76, 946, 1419, },
[24] = { 78, 1043, 1564, },
[25] = { 80, 1149, 1724, },
[26] = { 82, 1266, 1899, },
[27] = { 84, 1394, 2091, },
[28] = { 86, 1534, 2301, },
[29] = { 88, 1687, 2530, },
[30] = { 90, 1855, 2782, },
},
}
skills["VaalAuraElementalDamageHealing"] = {
name = "Gluttony of Elements",
hidden = true,
color = 4,
description = "Casts an aura that causes taking elemental damage to heal you and nearby allies instead.",
skillTypes = { [2] = true, [5] = true, [11] = true, [12] = true, [18] = true, [43] = true, [44] = true, },
fromItem = true,
baseFlags = {
spell = true,
aura = true,
area = true,
duration = true,
vaal = true,
},
baseMods = {
skill("castTime", 1),
skill("duration", 6), --"base_skill_effect_duration" = 6000
--"base_elemental_damage_heals" = ?
skill("radius", 36),
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[20] = { 1, },
},
}
skills["IcestormUniqueStaff12"] = {
name = "Icestorm",
hidden = true,
color = 3,
description = "Icy bolts rain down over the targeted area. They explode when landing, dealing damage to nearby enemies and chilling them, as well as causing patches of chilled ground. Skill damage is based on Intelligence.",
skillTypes = { [2] = true, [10] = true, [11] = true, [12] = true, [17] = true, [18] = true, [19] = true, [26] = true, [36] = true, [34] = true, [60] = true, },
fromItem = true,
baseFlags = {
spell = true,
area = true,
duration = true,
cold = true,
},
baseMods = {
skill("castTime", 1),
skill("manaCost", 22),
skill("damageEffectiveness", 0.3),
skill("CritChance", 5),
skill("ColdMin", 1, { type = "PerStat", stat = "Int", div = 10 }), --"spell_minimum_base_cold_damage_+_per_10_intelligence" = 1
skill("ColdMax", 3, { type = "PerStat", stat = "Int", div = 10 }), --"spell_maximum_base_cold_damage_+_per_10_intelligence" = 3
skill("duration", 1.5), --"base_skill_effect_duration" = 1500
--"fire_storm_fireball_delay_ms" = 100
--"skill_override_pvp_scaling_time_ms" = 450
--"firestorm_drop_ground_ice_duration_ms" = 500
--"skill_art_variation" = 4
--"skill_effect_duration_per_100_int" = 150
skill("showAverage", true), --"base_skill_show_average_damage_instead_of_dps" = ?
--"is_area_damage" = ?
skill("duration", 0.15, { type = "PerStat", stat = "Int", div = 100, base = 1.5 }),
skill("radius", 25),
skill("radiusSecondary", 10),
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[1] = { 1, },
},
}
skills["MerveilWarp"] = {
name = "Illusory Warp",
hidden = true,
color = 4,
description = "Teleport to a target destination. Chilled ground is spread in an area around both where the caster was and where they teleported to.",
skillTypes = { [2] = true, [38] = true, [12] = true, [34] = true, [11] = true, },
fromItem = true,
baseFlags = {
spell = true,
area = true,
duration = true,
movement = true,
cold = true,
},
baseMods = {
skill("castTime", 0.6),
skill("manaCost", 20),
skill("cooldown", 3),
skill("duration", 1.5), --"base_skill_effect_duration" = 1500
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[20] = { 1, },
},
}
skills["LightningSpell"] = {
name = "Lightning Bolt",
hidden = true,
color = 3,
description = "A bolt of lightning strikes an area, dealing lightning damage.",
skillTypes = { [2] = true, [42] = true, [35] = true, [11] = true, [10] = true, [45] = true, [61] = true, },
fromItem = true,
baseFlags = {
spell = true,
area = true,
lightning = true,
},
baseMods = {
skill("castTime", 1),
skill("CritChance", 6),
skill("cooldown", 0.5),
--"cast_on_crit_%" = 100
--"is_area_damage" = ?
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
[2] = skill("LightningMin", nil), --"spell_minimum_base_lightning_damage"
[3] = skill("LightningMax", nil), --"spell_maximum_base_lightning_damage"
},
levels = {
[1] = { 1, 10, 29, },
[2] = { 2, 11, 33, },
[3] = { 4, 14, 41, },
[4] = { 7, 18, 54, },
[5] = { 11, 25, 75, },
[6] = { 16, 36, 109, },
[7] = { 20, 47, 141, },
[8] = { 24, 60, 180, },
[9] = { 28, 76, 227, },
[10] = { 32, 94, 282, },
[11] = { 36, 116, 348, },
[12] = { 40, 142, 426, },
[13] = { 44, 173, 518, },
[14] = { 48, 209, 626, },
[15] = { 52, 251, 754, },
[16] = { 56, 301, 903, },
[17] = { 60, 359, 1078, },
[18] = { 64, 428, 1283, },
[19] = { 67, 486, 1459, },
[20] = { 70, 552, 1657, },
[21] = { 72, 601, 1802, },
[22] = { 74, 653, 1959, },
[23] = { 76, 709, 2127, },
[24] = { 78, 770, 2310, },
[25] = { 80, 835, 2506, },
[26] = { 82, 906, 2718, },
[27] = { 84, 982, 2946, },
[28] = { 86, 1064, 3192, },
[29] = { 88, 1153, 3458, },
[30] = { 90, 1248, 3743, },
},
}
skills["UniqueAnimateWeapon"] = {
name = "Manifest Dancing Dervish",
hidden = true,
color = 4,
description = "Releases Dancing Dervish to fight by your side. While Dancing Dervish is manifested, you have Onslaught and cannot use Weapons.",
skillTypes = { [2] = true, [9] = true, [21] = true, [36] = true, },
minionSkillTypes = { [1] = true, [24] = true, [25] = true, [11] = true, [38] = true, [28] = true, },
fromItem = true,
minionList = {
"UniqueAnimatedWeapon",
},
minionUses = {
["Weapon 1"] = true,
},
baseFlags = {
spell = true,
minion = true,
},
baseMods = {
skill("castTime", 1),
skill("cooldown", 0.5),
--"disable_weapons" = 1
mod("MinionModifier", "LIST", { mod = mod("Speed", "INC", 25, ModFlag.Attack) }), --"attack_speed_+%" = 25
mod("MinionModifier", "LIST", { mod = mod("Damage", "INC", 110, ModFlag.Attack) }), --"attack_damage_+%" = 110
--"chance_to_cast_on_rampage_tier_%" = 100
mod("MinionModifier", "LIST", { mod = mod("MovementSpeed", "INC", 30) }), --"minion_movement_speed_+%" = 30
mod("DisableWeapons", "FLAG", true, 0, 0, { type = "GlobalEffect", effectType = "Buff" }),
mod("Condition:Onslaught", "FLAG", true, 0, 0, { type = "GlobalEffect", effectType = "Buff" }),
skill("minionLevel", 59),
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[15] = { 1, },
},
}
skills["TriggeredMoltenStrike"] = {
name = "Molten Burst",
hidden = true,
color = 1,
description = "Launch molten projectiles from the point of impact, causing AoE attack damage to enemies where they land.",
skillTypes = { [3] = true, [1] = true, [11] = true, [33] = true, [57] = true, [47] = true, [48] = true, },
fromItem = true,
baseFlags = {
attack = true,
projectile = true,
area = true,
fire = true,
},
baseMods = {
skill("castTime", 1),
skill("cooldown", 0.15),
mod("ProjectileCount", "BASE", 2), --"number_of_additional_projectiles" = 2
--"attack_trigger_on_melee_hit_%" = 20
--"show_number_of_projectiles" = ?
--"base_is_projectile" = ?
--"is_area_damage" = ?
skill("showAverage", true), --"base_skill_show_average_damage_instead_of_dps" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[16] = { 1, },
},
}
skills["TriggeredSummonSpider"] = {
name = "Raise Spiders",
hidden = true,
color = 3,
description = "Raise two spectral spiders from each nearby corpse that will leap towards and attack your enemies. Enemies will not engage the spiders directly.",
skillTypes = { [2] = true, [9] = true, [36] = true, [49] = true, [42] = true, [61] = true, },
minionSkillTypes = { [1] = true, [24] = true, [25] = true, [28] = true, },
fromItem = true,
minionList = {
"SpiderMinion",
},
baseFlags = {
spell = true,
minion = true,
duration = true,
},
baseMods = {
skill("castTime", 1),
skill("cooldown", 2),
--"chance_to_cast_on_kill_%_target_self" = 20
skill("duration", 8), --"base_skill_effect_duration" = 8000
mod("ActiveSpiderLimit", "BASE", 20), --"number_of_spider_minions_allowed" = 20
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
--"take_no_actions_while_parent_dead" = ?
--"minion_dies_when_parent_dies" = ?
skill("minionLevelIsEnemyLevel", true), --"display_skill_minions_level_is_corpse_level" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[1] = { 1, },
},
}
skills["TriggeredShockedGround"] = {
name = "Shock Ground",
hidden = true,
color = 4,
description = "Creates a patch of Shocked Ground in a radius around you.",
skillTypes = { [2] = true, [11] = true, [36] = true, [12] = true, [42] = true, [45] = true, [61] = true, [35] = true, },
fromItem = true,
baseFlags = {
spell = true,
area = true,
duration = true,
lightning = true,
},
baseMods = {
skill("castTime", 1),
skill("cooldown", 5),
--"cast_when_hit_%" = 100
--"skill_art_variation" = 7
skill("duration", 5), --"base_skill_effect_duration" = 5000
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[1] = { 1, },
},
}
skills["SummonEssenceSpirits"] = {
name = "Spectral Spirits",
hidden = true,
color = 3,
description = "Summons three invulnerable spectral skulls that rush at nearby enemies and attack them rapidly. Enemies will not engage these spirits, and can pass through them.",
skillTypes = { [2] = true, [9] = true, [36] = true, [49] = true, [42] = true, [61] = true, },
minionSkillTypes = { [1] = true, [24] = true, [25] = true, [28] = true, },
fromItem = true,
minionList = {
"SummonedEssenceSpirit",
},
baseFlags = {
spell = true,
minion = true,
},
baseMods = {
skill("castTime", 1),
skill("minionDamageEffectiveness", -15), --"active_skill_minion_added_damage_+%_final" = -15
--"number_of_monsters_to_summon" = 3
--"cast_on_gain_skill" = ?
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
--"take_no_actions_while_parent_dead" = ?
--"minion_dies_when_parent_dies" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[1] = { 1, },
[2] = { 2, },
[3] = { 4, },
[4] = { 7, },
[5] = { 11, },
[6] = { 16, },
[7] = { 20, },
[8] = { 24, },
[9] = { 28, },
[10] = { 32, },
[11] = { 36, },
[12] = { 40, },
[13] = { 44, },
[14] = { 48, },
[15] = { 52, },
[16] = { 56, },
[17] = { 60, },
[18] = { 64, },
[19] = { 67, },
[20] = { 70, },
[21] = { 72, },
[22] = { 74, },
[23] = { 76, },
[24] = { 78, },
[25] = { 80, },
[26] = { 82, },
[27] = { 84, },
[28] = { 86, },
[29] = { 88, },
[30] = { 90, },
},
}
skills["SummonRigwaldsPack"] = {
name = "Summon Spectral Wolf",
hidden = true,
color = 4,
description = "Summons a spectral wolf companion that attacks near by enemies and dies after a duration.",
skillTypes = { [2] = true, [9] = true, [12] = true, [21] = true, [17] = true, [18] = true, [19] = true, [26] = true, [36] = true, [49] = true, [42] = true, [61] = true, },
minionSkillTypes = { [1] = true, [24] = true, [25] = true, [28] = true, },
fromItem = true,
minionList = {
"SummonedSpectralWolf",
},
baseFlags = {
spell = true,
minion = true,
duration = true,
},
baseMods = {
skill("castTime", 1),
skill("duration", 30), --"base_skill_effect_duration" = 30000
mod("ActiveWolfLimit", "BASE", 20), --"number_of_wolves_allowed" = 20
--"chance_to_cast_on_kill_%_target_self" = 10
--"display_minion_monster_type" = 8
skill("minionLevel", 65), --"display_minion_monster_level" = 65
skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ?
},
qualityMods = {
},
levelMods = {
[1] = skill("levelRequirement", nil),
},
levels = {
[18] = { 66, },
},
} | mit |
Wiladams/LJIT2perfmon | testy/showeventinfo.lua | 1 | 19887 | package.path = package.path..";".."../?.lua"
local ffi = require("ffi")
local bit = require("bit")
local band = bit.band
local bor = bit.bor
local pfm = require("pfmlib")
local common = require("test_common");
local fun = require("fun")();
local S = require("syscall");
common.appendDict(_G, common)
common.appendDict(_G, pfm)
local MAXBUF = 1024
local COMBO_MAX = 18
local options = {
compact = 0; -- int
sort = 0; -- int
encode = 0; -- int
combo = 0; -- int
combo_lim = 0; -- int
desc = 0; -- int
csv_sep = ','; -- char *
efilter = nil; -- pfm_event_info_t
ufilter = nil; -- pfm_event_attr_info_t
os = nil; -- pfm_os_t
mask = 0; -- uint64_t
}
local function code_info_t()
local obj = {
code = 0;
idx = 0;
}
return obj;
end
--static void show_event_info_compact(pfm_event_info_t *info);
if PFMLIB_WINDOWS then
--[[
int set_env_var(const char *var, const char *value, int ov)
{
size_t len;
char *str;
int ret;
len = strlen(var) + 1 + strlen(value) + 1;
str = malloc(len);
if (!str)
return PFM_ERR_NOMEM;
sprintf(str, "%s=%s", var, value);
ret = putenv(str);
free(str);
return ret ? PFM_ERR_INVAL : PFM_SUCCESS;
}
--]]
else
local function set_env_var(var, value, ov)
return S.setenv(var, value, ov);
end
end
-- indicated by a double colon
local function event_has_pname(s)
return s:find("::")
end
-- char *buf, int plm, int max_encoding
local function print_codes(buf, plm, max_encoding)
local codes = ffi.new("uint64_t *[1]");
local count = ffi.new("int[1]")
local ret = pfm.Lib.pfm_get_event_encoding(buf, bor(PFM_PLM0,PFM_PLM3), nil, nil, codes, count);
if ret ~= PFM_SUCCESS then
if ret == PFM_ERR_NOTFOUND then
errx(1, "encoding failed, try setting env variable LIBPFM_ENCODE_INACTIVE=1");
end
return -1;
end
for j = 0, max_encoding-1 do
if j < count[0] then
printf("0x%x", tonumber(codes[j]));
end
printf("%s", options.csv_sep);
end
ffi.C.free(codes[0]);
return 0;
end
local function check_valid(buf, plm)
local codes = ffi.new("uint64_t *[1]");
local count = ffi.new("int[1]")
local ret = pfm.Lib.pfm_get_event_encoding(buf, bor(PFM_PLM0,PFM_PLM3), nil, nil, codes, count);
if ret ~= pfm.PFM_SUCCESS then
return false;
end
ffi.C.free(codes[0]);
return true;
end
--pfm_event_attr_info_t *info
local function match_ufilters(info)
local ufilter1 = 0;
local ufilter2 = 0;
if (options.ufilter.is_dfl) then
ufilter1 = bor(ufilter1, 0x1);
end
if (info.is_dfl) then
ufilter2 = bor(ufilter2, 0x1);
end
if (options.ufilter.is_precise) then
ufilter1 = bor(ufilter1, 0x2);
end
if (info.is_precise) then
ufilter2 = bor(ufilter2, 0x2);
end
if (ufilter1 == 0) then
return 1;
end
-- at least one filter matches
return band(ufilter1, ufilter2);
end
--pfm_event_info_t *info
-- pmuevent info
local function match_efilters(info)
pfm_event_attr_info_t ainfo;
int n = 0;
int i, ret;
if (options.efilter.is_precise and not info.isPrecise) then
return 0;
end
memset(&ainfo, 0, sizeof(ainfo));
ainfo.size = sizeof(ainfo);
each(function(ainfo)
if match_ufilters(ainfo) then
return 1;
end
if ainfo.type == ffi.C.PFM_ATTR_UMASK then
n = n+1;
end
end, info:attributes())
--[[
pfm_for_each_event_attr(i, info) {
ret = pfm_get_event_attr_info(info->idx, i, options.os, &ainfo);
if (ret != PFM_SUCCESS)
continue;
if (match_ufilters(&ainfo))
return 1;
if (ainfo.type == PFM_ATTR_UMASK)
n++;
}
-]]
if 0 ~= n then
return 0
end
return 1
end
--[[
local function show_event_info_combo(pfm_event_info_t *info)
pfm_event_attr_info_t *ainfo;
pfm_pmu_info_t pinfo;
char buf[MAXBUF];
size_t len;
int numasks = 0;
int i, j, ret;
uint64_t total, m, u;
memset(&pinfo, 0, sizeof(pinfo));
pinfo.size = sizeof(pinfo);
ret = pfm_get_pmu_info(info->pmu, &pinfo);
if (ret != PFM_SUCCESS)
errx(1, "cannot get PMU info");
ainfo = calloc(info->nattrs, sizeof(*ainfo));
if (!ainfo)
err(1, "event %s : ", info->name);
/*
* extract attribute information and count number
* of umasks
*
* we cannot just drop non umasks because we need
* to keep attributes in order for the enumeration
* of 2^n
*/
pfm_for_each_event_attr(i, info) {
ainfo[i].size = sizeof(*ainfo);
ret = pfm_get_event_attr_info(info->idx, i, options.os, &ainfo[i]);
if (ret != PFM_SUCCESS)
errx(1, "cannot get attribute info: %s", pfm_strerror(ret));
if (ainfo[i].type == PFM_ATTR_UMASK)
numasks++;
}
if (numasks > options.combo_lim) {
warnx("event %s has too many umasks to print all combinations, dropping to simple enumeration", info->name);
free(ainfo);
show_event_info_compact(info);
return;
}
if (numasks) {
if (info->nattrs > (int)((sizeof(total)<<3))) {
warnx("too many umasks, cannot show all combinations for event %s", info->name);
goto end;
}
total = 1ULL << info->nattrs;
for (u = 1; u < total; u++) {
len = sizeof(buf);
len -= snprintf(buf, len, "%s::%s", pinfo.name, info->name);
if (len <= 0) {
warnx("event name too long%s", info->name);
goto end;
}
for(m = u, j = 0; m; m >>=1, j++) {
if (m & 0x1ULL) {
/* we have hit a non umasks attribute, skip */
if (ainfo[j].type != PFM_ATTR_UMASK)
break;
if (len < (1 + strlen(ainfo[j].name))) {
warnx("umasks combination too long for event %s", buf);
break;
}
strncat(buf, ":", len-1);buf[len-1] = '\0'; len--;
strncat(buf, ainfo[j].name, len-1);buf[len-1] = '\0';
len -= strlen(ainfo[j].name);
}
}
-- if found a valid umask combination, check encoding
if (m == 0) then
if (options.encode)
ret = print_codes(buf, bor(PFM_PLM0,PFM_PLM3), pinfo.max_encoding);
else
ret = check_valid(buf, bor(PFM_PLM0,PFM_PLM3));
if (ret)
printf("%s\n", buf);
end
}
else
snprintf(buf, sizeof(buf)-1, "%s::%s", pinfo.name, info->name);
buf[sizeof(buf)-1] = '\0';
ret = options.encode ? print_codes(buf, PFM_PLM0|PFM_PLM3, pinfo.max_encoding) : 0;
if (!ret)
printf("%s\n", buf);
end
end_label:
free(ainfo);
end
local function show_event_info_compact(pfm_event_info_t *info)
pfm_event_attr_info_t ainfo;
pfm_pmu_info_t pinfo;
char buf[MAXBUF];
int i, ret, um = 0;
memset(&ainfo, 0, sizeof(ainfo));
memset(&pinfo, 0, sizeof(pinfo));
pinfo.size = sizeof(pinfo);
ainfo.size = sizeof(ainfo);
ret = pfm_get_pmu_info(info->pmu, &pinfo);
if (ret != PFM_SUCCESS)
errx(1, "cannot get pmu info: %s", pfm_strerror(ret));
pfm_for_each_event_attr(i, info) {
ret = pfm_get_event_attr_info(info->idx, i, options.os, &ainfo);
if (ret != PFM_SUCCESS)
errx(1, "cannot get attribute info: %s", pfm_strerror(ret));
if (ainfo.type != PFM_ATTR_UMASK)
continue;
if (!match_ufilters(&ainfo))
continue;
snprintf(buf, sizeof(buf)-1, "%s::%s:%s", pinfo.name, info->name, ainfo.name);
buf[sizeof(buf)-1] = '\0';
ret = 0;
if (options.encode) {
ret = print_codes(buf, PFM_PLM0|PFM_PLM3, pinfo.max_encoding);
}
if (!ret) {
printf("%s", buf);
if (options.desc) {
printf("%s", options.csv_sep);
printf("\"%s. %s.\"", info->desc, ainfo.desc);
}
putchar('\n');
}
um++;
}
if (um == 0) {
if (!match_efilters(info))
return;
snprintf(buf, sizeof(buf)-1, "%s::%s", pinfo.name, info->name);
buf[sizeof(buf)-1] = '\0';
if (options.encode) {
ret = print_codes(buf, PFM_PLM0|PFM_PLM3, pinfo.max_encoding);
if (ret)
return;
}
printf("%s", buf);
if (options.desc) {
printf("%s", options.csv_sep);
printf("\"%s.\"", info->desc);
}
putchar('\n');
}
end
local function compare_codes(const void *a, const void *b)
const code_info_t *aa = a;
const code_info_t *bb = b;
local m = options.mask;
if ((aa->code & m) < (bb->code &m))
return -1;
if ((aa->code & m) == (bb->code & m))
return 0;
return 1;
end
--]]
--pfm_event_info_t *info
local function print_event_flags(info)
local n = 0;
if info.is_precise>0 then
common.printf("[precise] ");
n = n+1;
end
if n==0 then
common.printf("None");
end
end
--[[
local function print_attr_flags(pfm_event_attr_info_t *info)
int n = 0;
if (info->is_dfl) {
printf("[default] ");
n++;
}
if (info->is_precise) {
printf("[precise] ");
n++;
}
if (!n)
printf("None ");
end
--]]
-- pfm_event_info_t *info
local function show_event_info(info)
--[[
pfm_event_attr_info_t ainfo;
pfm_pmu_info_t pinfo;
int mod = 0, um = 0;
int i, ret;
const char *src;
memset(&ainfo, 0, sizeof(ainfo));
memset(&pinfo, 0, sizeof(pinfo));
pinfo.size = sizeof(pinfo);
ainfo.size = sizeof(ainfo);
if (!match_efilters(info))
return;
ret = pfm_get_pmu_info(info->pmu, &pinfo);
if (ret)
errx(1, "cannot get pmu info: %s", pfm_strerror(ret));
printf("#-----------------------------\n"
"IDX : %d\n"
"PMU name : %s (%s)\n"
"Name : %s\n"
"Equiv : %s\n",
info->idx,
pinfo.name,
pinfo.desc,
info->name,
info->equiv ? info->equiv : "None");
printf("Flags : ");
print_event_flags(info);
putchar('\n');
printf("Desc : %s\n", info->desc ? info->desc : "no description available");
printf("Code : 0x%"PRIx64"\n", info->code);
pfm_for_each_event_attr(i, info) {
ret = pfm_get_event_attr_info(info->idx, i, options.os, &ainfo);
if (ret != PFM_SUCCESS)
errx(1, "cannot retrieve event %s attribute info: %s", info->name, pfm_strerror(ret));
if (ainfo.ctrl >= PFM_ATTR_CTRL_MAX) {
warnx("event: %s has unsupported attribute source %d", info->name, ainfo.ctrl);
ainfo.ctrl = PFM_ATTR_CTRL_UNKNOWN;
}
src = srcs[ainfo.ctrl];
switch(ainfo.type) {
case PFM_ATTR_UMASK:
if (!match_ufilters(&ainfo))
continue;
printf("Umask-%02u : 0x%02"PRIx64" : %s : [%s] : ",
um,
ainfo.code,
src,
ainfo.name);
print_attr_flags(&ainfo);
putchar(':');
if (ainfo.equiv)
printf(" Alias to %s", ainfo.equiv);
else
printf(" %s", ainfo.desc);
putchar('\n');
um++;
break;
case PFM_ATTR_MOD_BOOL:
printf("Modif-%02u : 0x%02"PRIx64" : %s : [%s] : %s (boolean)\n", mod, ainfo.code, src, ainfo.name, ainfo.desc);
mod++;
break;
case PFM_ATTR_MOD_INTEGER:
printf("Modif-%02u : 0x%02"PRIx64" : %s : [%s] : %s (integer)\n", mod, ainfo.code, src, ainfo.name, ainfo.desc);
mod++;
break;
default:
printf("Attr-%02u : 0x%02"PRIx64" : %s : [%s] : %s\n", i, ainfo.code, ainfo.name, src, ainfo.desc);
}
}
--]]
end
-- char *event, regex_t *preg
local function show_info(event, preg)
--[[
pfm_pmu_info_t pinfo;
pfm_event_info_t info;
int i, j, ret, match = 0, pname;
size_t len, l = 0;
char *fullname = NULL;
memset(&pinfo, 0, sizeof(pinfo));
memset(&info, 0, sizeof(info));
pinfo.size = sizeof(pinfo);
info.size = sizeof(info);
pname = event_has_pname(event);
/*
* scan all supported events, incl. those
* from undetected PMU models
*/
pfm_for_all_pmus(j) {
ret = pfm_get_pmu_info(j, &pinfo);
if (ret != PFM_SUCCESS)
continue;
/* no pmu prefix, just look for detected PMU models */
if (!pname && !pinfo.is_present)
continue;
for (i = pinfo.first_event; i != -1; i = pfm_get_event_next(i)) {
ret = pfm_get_event_info(i, options.os, &info);
if (ret != PFM_SUCCESS)
errx(1, "cannot get event info: %s", pfm_strerror(ret));
len = strlen(info.name) + strlen(pinfo.name) + 1 + 2;
if (len > l) {
l = len;
fullname = realloc(fullname, l);
if (!fullname)
err(1, "cannot allocate memory");
}
sprintf(fullname, "%s::%s", pinfo.name, info.name);
if (regexec(preg, fullname, 0, NULL, 0) == 0) {
if (options.compact)
if (options.combo)
show_event_info_combo(&info);
else
show_event_info_compact(&info);
else
show_event_info(&info);
match++;
}
}
}
if (fullname)
free(fullname);
--]]
return match;
end
-- char *event, regex_t *preg
local function show_info_sorted(event, preg)
--[[
pfm_pmu_info_t pinfo;
pfm_event_info_t info;
unsigned int j;
int i, ret, n, match = 0;
size_t len, l = 0;
char *fullname = NULL;
code_info_t *codes;
memset(&pinfo, 0, sizeof(pinfo));
memset(&info, 0, sizeof(info));
pinfo.size = sizeof(pinfo);
info.size = sizeof(info);
pfm_for_all_pmus(j) {
ret = pfm_get_pmu_info(j, &pinfo);
if (ret != PFM_SUCCESS)
continue;
codes = malloc(pinfo.nevents * sizeof(*codes));
if (!codes)
err(1, "cannot allocate memory\n");
/* scans all supported events */
n = 0;
for (i = pinfo.first_event; i != -1; i = pfm_get_event_next(i)) {
ret = pfm_get_event_info(i, options.os, &info);
if (ret != PFM_SUCCESS)
errx(1, "cannot get event info: %s", pfm_strerror(ret));
if (info.pmu != j)
continue;
codes[n].idx = info.idx;
codes[n].code = info.code;
n++;
}
qsort(codes, n, sizeof(*codes), compare_codes);
for(i=0; i < n; i++) {
ret = pfm_get_event_info(codes[i].idx, options.os, &info);
if (ret != PFM_SUCCESS)
errx(1, "cannot get event info: %s", pfm_strerror(ret));
len = strlen(info.name) + strlen(pinfo.name) + 1 + 2;
if (len > l) {
l = len;
fullname = realloc(fullname, l);
if (!fullname)
err(1, "cannot allocate memory");
}
sprintf(fullname, "%s::%s", pinfo.name, info.name);
if (regexec(preg, fullname, 0, NULL, 0) == 0) {
if (options.compact)
show_event_info_compact(&info);
else
show_event_info(&info);
match++;
}
}
free(codes);
}
if (fullname)
free(fullname);
--]]
return match;
end
local function usage()
common.printf([[
showevtinfo [-L] [-E] [-h] [-s] [-m mask]
-L list one event per line (compact mode)
-E list one event per line with encoding (compact mode)
-M display all valid unit masks combination (use with -L or -E)
-h get help
-s sort event by PMU and by code based on -m mask
-l maximum number of umasks to list all combinations (default: %d)
-F show only events and attributes with certain flags (precise,...)
-m mask hexadecimal event code mask, bits to match when sorting
-x sep use sep as field separator in compact mode
-D print event description in compact mode
-O os show attributes for the specific operating system]],
COMBO_MAX);
end
--[[
/*
* keep: [pmu::]event
* drop everything else
*/
static void
drop_event_attributes(char *str)
{
char *p;
p = strchr(str, ':');
if (!p)
return;
str = p+1;
/* keep PMU name */
if (*str == ':')
str++;
/* stop string at 1st attribute */
p = strchr(str, ':');
if (p)
*p = '\0';
}
--]]
--[[
struct attr_flags {
const char *name;
int ebit; /* bit position in pfm_event_info_t.flags, -1 means ignore */
int ubit; /* bit position in pfm_event_attr_info_t.flags, -1 means ignore */
};
--]]
local event_flags={
[0] = {name = "precise", ebit = 0, ubit=1},
[1] = {name = "pebs", ebit=0, ubit=1},
[2] = {name = "default", ebit=-1, ubit=0},
[3] = {name = "dfl", ebit=-1, ubit=0},
[4] = {name = nil, ebit=0, ubit=0}
};
-- char *arg
local function parse_filters(arg)
--[[
-- arg represents a comma separated list of event arguments
-- iterate over them, matching to items in event_flags
const struct attr_flags *attr;
char *p;
while (arg) {
p = strchr(arg, ',');
if (p)
*p++ = 0;
for (attr = event_flags; attr->name; attr++) {
if (!strcasecmp(attr->name, arg)) {
switch(attr->ebit) {
case 0:
options.efilter.is_precise = 1;
break;
case -1:
break;
default:
errx(1, "unknown event flag %d", attr->ebit);
}
switch (attr->ubit) {
case 0:
options.ufilter.is_dfl = 1;
break;
case 1:
options.ufilter.is_precise = 1;
break;
case -1:
break;
default:
errx(1, "unknown umaks flag %d", attr->ubit);
}
break;
}
}
arg = p;
}
--]]
end
local supported_oses={
{ name = "none", os = ffi.C.PFM_OS_NONE },
{ name = "raw", os = ffi.C.PFM_OS_NONE },
{ name = "pmu", os = ffi.C.PFM_OS_NONE },
{ name = "perf", os = PFM_OS_PERF_EVENT},
{ name = "perf_ext", os = PFM_OS_PERF_EVENT_EXT},
{ name = nil, }
};
local pmu_types={
[ffi.C.PFM_PMU_TYPE_UNKNOWN] = "unknown type",
[ffi.C.PFM_PMU_TYPE_CORE] = "core",
[ffi.C.PFM_PMU_TYPE_UNCORE] = "uncore",
[ffi.C.PFM_PMU_TYPE_OS_GENERIC] = "OS generic",
};
local function setup_os(ostr)
for idx, entry in ipairs(supported_oses) do
if entry.name == ostr then
options.os = entry.os;
return;
end
end
common.printf("unknown OS layer %s, choose from:", ostr);
-- print the valid choices
for _,entry in ipairs(supported_oses) do
io.write(string.format("%s, ", entry.name))
end
print();
error()
end
local function main(argc, argv)
local default_sep = "\t";
local ostr = nil;
local endptr = nil;
--[[
static char *argv_all[2] = { ".*", NULL };
char **args;
int i, match;
regex_t preg;
int ret, c;
--]]
pinfo = ffi.new("pfm_pmu_info_t");
--memset(&pinfo, 0, sizeof(pinfo));
pinfo.size = ffi.sizeof(pinfo);
--[[
while ((c=getopt(argc, argv,"hELsm:Ml:F:x:DO:")) ~= -1) {
switch(c) {
case 'L':
options.compact = 1;
break;
case 'F':
parse_filters(optarg);
break;
case 'E':
options.compact = 1;
options.encode = 1;
break;
case 'M':
options.combo = 1;
break;
case 's':
options.sort = 1;
break;
case 'D':
options.desc = 1;
break;
case 'l':
options.combo_lim = atoi(optarg);
break;
case 'x':
options.csv_sep = optarg;
break;
case 'O':
ostr = optarg;
break;
case 'm':
options.mask = strtoull(optarg, &endptr, 16);
if (*endptr)
errx(1, "mask must be in hexadecimal\n");
break;
case 'h':
usage();
return 0;
default:
errx(1, "unknown option error");
}
}
--]]
-- to allow encoding of events from non detected PMU models
--ret = set_env_var("LIBPFM_ENCODE_INACTIVE", "1", 1);
--if (ret ~= PFM_SUCCESS) then
-- errx(1, "cannot force inactive encoding");
--end
if (options.mask == 0) then
options.mask = bnot(0);
end
if (optind == argc) then
args = argv_all;
else
args = argv + optind;
end
if (not options.csv_sep) then
options.csv_sep = default_sep;
end
-- avoid combinatorial explosion
if (options.combo_lim == 0) then
options.combo_lim = COMBO_MAX;
end
if (ostr) then
setup_os(ostr);
else
options.os = ffi.C.PFM_OS_NONE;
end
--[[
if (not options.compact) then
int total_supported_events = 0;
int total_available_events = 0;
printf("Supported PMU models:\n");
pfm_for_all_pmus(i) {
ret = pfm_get_pmu_info(i, &pinfo);
if (ret != PFM_SUCCESS)
continue;
printf("\t[%d, %s, \"%s\"]\n", i, pinfo.name, pinfo.desc);
}
printf("Detected PMU models:\n");
pfm_for_all_pmus(i) {
ret = pfm_get_pmu_info(i, &pinfo);
if (ret != PFM_SUCCESS)
continue;
if (pinfo.is_present) {
if (pinfo.type >= PFM_PMU_TYPE_MAX)
pinfo.type = PFM_PMU_TYPE_UNKNOWN;
printf("\t[%d, %s, \"%s\", %d events, %d max encoding, %d counters, %s PMU]\n",
i,
pinfo.name,
pinfo.desc,
pinfo.nevents,
pinfo.max_encoding,
pinfo.num_cntrs + pinfo.num_fixed_cntrs,
pmu_types[pinfo.type]);
total_supported_events += pinfo.nevents;
}
total_available_events += pinfo.nevents;
}
printf("Total events: %d available, %d supported\n", total_available_events, total_supported_events);
}
while(*args) {
/* drop umasks and modifiers */
drop_event_attributes(*args);
if (regcomp(&preg, *args, REG_ICASE))
errx(1, "error in regular expression for event \"%s\"", *argv);
if (options.sort)
match = show_info_sorted(*args, &preg);
else
match = show_info(*args, &preg);
if (match == 0)
errx(1, "event %s not found", *args);
args++;
}
regfree(&preg);
--]]
pfm.Lib.pfm_terminate();
return 0;
end
return main(#arg, arg)
| mit |
akh00/kong | spec/02-integration/05-proxy/10-server_tokens_spec.lua | 4 | 7331 | local helpers = require "spec.helpers"
local constants = require "kong.constants"
local default_server_header = _KONG._NAME .. "/" .. _KONG._VERSION
local function start(config)
return function()
helpers.dao.apis:insert {
name = "api-1",
upstream_url = "http://localhost:9999/headers-inspect",
hosts = {
"headers-inspect.com",
}
}
config = config or {}
config.nginx_conf = "spec/fixtures/custom_nginx.template"
assert(helpers.start_kong(config))
end
end
describe("Server Tokens", function()
local client
before_each(function()
client = helpers.proxy_client()
end)
after_each(function()
if client then
client:close()
end
end)
describe("(with default configration values)", function()
setup(start {
nginx_conf = "spec/fixtures/custom_nginx.template",
})
teardown(helpers.stop_kong)
it("should return Kong 'Via' header but not change the 'Server' header when request was proxied", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "headers-inspect.com",
}
})
assert.res_status(200, res)
assert.not_equal(default_server_header, res.headers["server"])
assert.equal(default_server_header, res.headers["via"])
end)
it("should return Kong 'Server' header but not the Kong 'Via' header when no API matched (no proxy)", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "404.com",
}
})
assert.res_status(404, res)
assert.equal(default_server_header, res.headers["server"])
assert.is_nil(res.headers["via"])
end)
end)
describe("(with server_tokens = on)", function()
setup(start {
nginx_conf = "spec/fixtures/custom_nginx.template",
server_tokens = "on",
})
teardown(helpers.stop_kong)
it("should return Kong 'Via' header but not change the 'Server' header when request was proxied", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "headers-inspect.com",
}
})
assert.res_status(200, res)
assert.not_equal(default_server_header, res.headers["server"])
assert.equal(default_server_header, res.headers["via"])
end)
it("should return Kong 'Server' header but not the Kong 'Via' header when no API matched (no proxy)", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "404.com",
}
})
assert.res_status(404, res)
assert.equal(default_server_header, res.headers["server"])
assert.is_nil(res.headers["via"])
end)
end)
describe("(with server_tokens = off)", function()
setup(start {
nginx_conf = "spec/fixtures/custom_nginx.template",
server_tokens = "off",
})
teardown(helpers.stop_kong)
it("should not return Kong 'Via' header but it should forward the 'Server' header when request was proxied", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "headers-inspect.com",
}
})
assert.res_status(200, res)
assert.response(res).has.header "server"
assert.response(res).has_not.header "via"
assert.not_equal(default_server_header, res.headers["server"])
end)
it("should not return Kong 'Server' or 'Via' headers when no API matched (no proxy)", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "404.com",
}
})
assert.res_status(404, res)
assert.is_nil(res.headers["server"])
assert.is_nil(res.headers["via"])
end)
end)
end)
describe("Latency Tokens", function()
local client
before_each(function()
client = helpers.proxy_client()
end)
after_each(function()
if client then
client:close()
end
end)
describe("(with default configration values)", function()
setup(start {
nginx_conf = "spec/fixtures/custom_nginx.template",
})
teardown(helpers.stop_kong)
it("should be returned when request was proxied", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "headers-inspect.com",
}
})
assert.res_status(200, res)
assert.is_not_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY])
assert.is_not_nil(res.headers[constants.HEADERS.PROXY_LATENCY])
end)
it("should not be returned when no API matched (no proxy)", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "404.com",
}
})
assert.res_status(404, res)
assert.is_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY])
assert.is_nil(res.headers[constants.HEADERS.PROXY_LATENCY])
end)
end)
describe("(with latency_tokens = on)", function()
setup(start {
nginx_conf = "spec/fixtures/custom_nginx.template",
latency_tokens = "on",
})
teardown(helpers.stop_kong)
it("should be returned when request was proxied", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "headers-inspect.com"
}
})
assert.res_status(200, res)
assert.is_not_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY])
assert.is_not_nil(res.headers[constants.HEADERS.PROXY_LATENCY])
end)
it("should not be returned when no API matched (no proxy)", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "404.com",
}
})
assert.res_status(404, res)
assert.is_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY])
assert.is_nil(res.headers[constants.HEADERS.PROXY_LATENCY])
end)
end)
describe("(with latency_tokens = off)", function()
setup(start {
nginx_conf = "spec/fixtures/custom_nginx.template",
latency_tokens = "off",
})
teardown(function()
helpers.stop_kong()
end)
it("should not be returned when request was proxied", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "headers-inspect.com",
}
})
assert.res_status(200, res)
assert.is_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY])
assert.is_nil(res.headers[constants.HEADERS.PROXY_LATENCY])
end)
it("should not be returned when no API matched (no proxy)", function()
local res = assert(client:send {
method = "GET",
path = "/get",
headers = {
host = "404.com",
}
})
assert.res_status(404, res)
assert.is_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY])
assert.is_nil(res.headers[constants.HEADERS.PROXY_LATENCY])
end)
end)
end)
| apache-2.0 |
UnluckyNinja/PathOfBuilding | Classes/ImportTab.lua | 1 | 32862 | -- Path of Building
--
-- Module: Import Tab
-- Import/Export tab for the current build.
--
local launch, main = ...
local ipairs = ipairs
local t_insert = table.insert
local ImportTabClass = common.NewClass("ImportTab", "ControlHost", "Control", function(self, build)
self.ControlHost()
self.Control()
self.build = build
self.charImportMode = build.targetVersion == liveTargetVersion and "GETACCOUNTNAME" or "VERSIONWARNING"
self.charImportStatus = "Idle"
self.controls.sectionCharImport = common.New("SectionControl", {"TOPLEFT",self,"TOPLEFT"}, 10, 18, 600, 230, "Character Import")
self.controls.charImportVersionWarning = common.New("LabelControl", {"TOPLEFT",self.controls.sectionCharImport,"TOPLEFT"}, 6, 20, 0, 16, colorCodes.WARNING..[[
Warning:^7 Characters may not import into this build correctly,
as the build's game version is different from the live game version.
Some passives may be deallocated, and some gems may not be recognised.
If possible, change the game version in the Configuration tab before importing.]])
self.controls.charImportVersionWarning.shown = function()
return self.charImportMode == "VERSIONWARNING"
end
self.controls.charImportVersionWarningGo = common.New("ButtonControl", {"TOPLEFT",self.controls.charImportVersionWarning,"TOPLEFT"}, 0, 70, 80, 20, "Continue", function()
self.charImportMode = "GETACCOUNTNAME"
end)
self.controls.charImportStatusLabel = common.New("LabelControl", {"TOPLEFT",self.controls.sectionCharImport,"TOPLEFT"}, 6, 14, 200, 16, function()
return "^7Character import status: "..self.charImportStatus
end)
self.controls.charImportStatusLabel.shown = function()
return self.charImportMode ~= "VERSIONWARNING"
end
-- Stage: input account name
self.controls.accountNameHeader = common.New("LabelControl", {"TOPLEFT",self.controls.sectionCharImport,"TOPLEFT"}, 6, 40, 200, 16, "^7To start importing a character, enter the character's account name:")
self.controls.accountNameHeader.shown = function()
return self.charImportMode == "GETACCOUNTNAME"
end
self.controls.accountName = common.New("EditControl", {"TOPLEFT",self.controls.accountNameHeader,"BOTTOMLEFT"}, 0, 4, 200, 20, main.lastAccountName or "", nil, "%c")
self.controls.accountName.pasteFilter = function(text)
return text:gsub("[\128-\255]",function(c)
return codePointToUTF8(c:byte(1)):gsub(".",function(c)
return string.format("%%%X", c:byte(1))
end)
end)
end
-- Region options
self.controls.accountRegion = common.New("DropDownControl", {"LEFT",self.controls.accountName,"RIGHT"}, 4, 0, 80, 20, { "GGG", "Tencent" })
self.controls.accountNameGo = common.New("ButtonControl", {"LEFT",self.controls.accountRegion,"RIGHT"}, 8, 0, 60, 20, "Start", function()
self.controls.sessionInput.buf = ""
self:DownloadCharacterList()
end)
self.controls.accountNameGo.enabled = function()
return self.controls.accountName.buf:match("%S")
end
self.controls.accountNameUnicode = common.New("LabelControl", {"TOPLEFT",self.controls.accountName,"BOTTOMLEFT"}, 0, 16, 0, 14, "^7Note: if the account name contains non-ASCII characters then it must be URL encoded first.")
self.controls.accountNameURLEncoder = common.New("ButtonControl", {"TOPLEFT",self.controls.accountNameUnicode,"BOTTOMLEFT"}, 0, 4, 170, 18, "^x4040FFhttps://www.urlencoder.org/", function()
OpenURL("https://www.urlencoder.org/")
end)
-- Stage: input POESESSID
self.controls.sessionHeader = common.New("LabelControl", {"TOPLEFT",self.controls.sectionCharImport,"TOPLEFT"}, 6, 40, 200, 14)
self.controls.sessionHeader.label = function()
return [[
^7The list of characters on ']]..self.controls.accountName.buf..[[' couldn't be retrieved. This may be because:
1. The account name is wrong, or
2. The account's privacy settings hide the characters tab (this is the default setting).
If this is your account, you can either:
1. Change your privacy settings to show you characters tab and then retry, or
2. Enter a valid POESESSID below.
You can get this from your web browser's cookies while logged into the Path of Exile website.
]]
end
self.controls.sessionHeader.shown = function()
return self.charImportMode == "GETSESSIONID"
end
self.controls.sessionRetry = common.New("ButtonControl", {"TOPLEFT",self.controls.sessionHeader,"TOPLEFT"}, 0, 108, 60, 20, "Retry", function()
self.controls.sessionInput.buf = ""
self:DownloadCharacterList()
end)
self.controls.sessionCancel = common.New("ButtonControl", {"LEFT",self.controls.sessionRetry,"RIGHT"}, 8, 0, 60, 20, "Cancel", function()
self.charImportMode = "GETACCOUNTNAME"
self.charImportStatus = "Idle"
end)
self.controls.sessionInput = common.New("EditControl", {"TOPLEFT",self.controls.sessionRetry,"BOTTOMLEFT"}, 0, 8, 350, 20, "", "POESESSID", "%X", 32)
self.controls.sessionGo = common.New("ButtonControl", {"LEFT",self.controls.sessionInput,"RIGHT"}, 8, 0, 60, 20, "Go", function()
self:DownloadCharacterList()
end)
self.controls.sessionGo.enabled = function()
return #self.controls.sessionInput.buf == 32
end
-- Stage: select character and import data
self.controls.charSelectHeader = common.New("LabelControl", {"TOPLEFT",self.controls.sectionCharImport,"TOPLEFT"}, 6, 40, 200, 16, "^7Choose character to import data from:")
self.controls.charSelectHeader.shown = function()
return self.charImportMode == "SELECTCHAR" or self.charImportMode == "IMPORTING"
end
self.controls.charSelect = common.New("DropDownControl", {"TOPLEFT",self.controls.charSelectHeader,"BOTTOMLEFT"}, 0, 4, 400, 18)
self.controls.charSelect.enabled = function()
return self.charImportMode == "SELECTCHAR"
end
self.controls.charImportHeader = common.New("LabelControl", {"TOPLEFT",self.controls.charSelect,"BOTTOMLEFT"}, 0, 16, 200, 16, "Import:")
self.controls.charImportTree = common.New("ButtonControl", {"LEFT",self.controls.charImportHeader, "RIGHT"}, 8, 0, 170, 20, "Passive Tree and Jewels", function()
if self.build.spec:CountAllocNodes() > 0 then
main:OpenConfirmPopup("Character Import", "Importing the passive tree will overwrite your current tree.", "Import", function()
self:DownloadPassiveTree()
end)
else
self:DownloadPassiveTree()
end
end)
self.controls.charImportTree.enabled = function()
return self.charImportMode == "SELECTCHAR"
end
self.controls.charImportTreeClearJewels = common.New("CheckBoxControl", {"LEFT",self.controls.charImportTree,"RIGHT"}, 90, 0, 18, "Delete jewels:")
self.controls.charImportTreeClearJewels.tooltipText = "Delete all existing jewels when importing."
self.controls.charImportItems = common.New("ButtonControl", {"LEFT",self.controls.charImportTree, "LEFT"}, 0, 36, 110, 20, "Items and Skills", function()
self:DownloadItems()
end)
self.controls.charImportItems.enabled = function()
return self.charImportMode == "SELECTCHAR"
end
self.controls.charImportItemsClearSkills = common.New("CheckBoxControl", {"LEFT",self.controls.charImportItems,"RIGHT"}, 85, 0, 18, "Delete skills:")
self.controls.charImportItemsClearSkills.tooltipText = "Delete all existing skills when importing."
self.controls.charImportItemsClearItems = common.New("CheckBoxControl", {"LEFT",self.controls.charImportItems,"RIGHT"}, 220, 0, 18, "Delete equipment:")
self.controls.charImportItemsClearItems.tooltipText = "Delete all equipped items when importing."
self.controls.charBanditNote = common.New("LabelControl", {"TOPLEFT",self.controls.charImportHeader,"BOTTOMLEFT"}, 0, 50, 200, 14, "^7Tip: After you finish importing a character, make sure you update the bandit choices,\nas these cannot be imported.")
self.controls.charDone = common.New("ButtonControl", {"TOPLEFT",self.controls.charImportHeader,"BOTTOMLEFT"}, 0, 90, 60, 20, "Done", function()
self.charImportMode = "GETACCOUNTNAME"
self.charImportStatus = "Idle"
end)
-- Build import/export
self.controls.sectionBuild = common.New("SectionControl", {"TOPLEFT",self.controls.sectionCharImport,"BOTTOMLEFT"}, 0, 18, 600, 200, "Build Sharing")
self.controls.generateCodeLabel = common.New("LabelControl", {"TOPLEFT",self.controls.sectionBuild,"TOPLEFT"}, 6, 14, 0, 16, "^7Generate a code to share this build with other Path of Building users:")
self.controls.generateCode = common.New("ButtonControl", {"LEFT",self.controls.generateCodeLabel,"RIGHT"}, 4, 0, 80, 20, "Generate", function()
self.controls.generateCodeOut:SetText(common.base64.encode(Deflate(self.build:SaveDB("code"))):gsub("+","-"):gsub("/","_"))
end)
self.controls.generateCodeOut = common.New("EditControl", {"TOPLEFT",self.controls.generateCodeLabel,"BOTTOMLEFT"}, 0, 8, 250, 20, "", "Code", "%Z")
self.controls.generateCodeOut.enabled = function()
return #self.controls.generateCodeOut.buf > 0
end
self.controls.generateCodeCopy = common.New("ButtonControl", {"LEFT",self.controls.generateCodeOut,"RIGHT"}, 8, 0, 60, 20, "Copy", function()
Copy(self.controls.generateCodeOut.buf)
self.controls.generateCodeOut:SetText("")
end)
self.controls.generateCodeCopy.enabled = function()
return #self.controls.generateCodeOut.buf > 0
end
self.controls.generateCodePastebin = common.New("ButtonControl", {"LEFT",self.controls.generateCodeCopy,"RIGHT"}, 8, 0, 140, 20, "Share with Pastebin", function()
local id = LaunchSubScript([[
local code, proxyURL = ...
local curl = require("lcurl.safe")
local page = ""
local easy = curl.easy()
easy:setopt_url("https://pastebin.com/api/api_post.php")
easy:setopt(curl.OPT_POST, true)
easy:setopt(curl.OPT_POSTFIELDS, "api_dev_key=c4757f22e50e65e21c53892fd8e0a9ff&api_paste_private=1&api_option=paste&api_paste_code="..code)
easy:setopt(curl.OPT_ACCEPT_ENCODING, "")
if proxyURL then
easy:setopt(curl.OPT_PROXY, proxyURL)
end
easy:setopt_writefunction(function(data)
page = page..data
return true
end)
easy:perform()
easy:close()
if page:match("pastebin.com") then
return page
else
return nil, page
end
]], "", "", self.controls.generateCodeOut.buf, launch.proxyURL)
if id then
self.controls.generateCodeOut:SetText("")
self.controls.generateCodePastebin.label = "Creating paste..."
launch:RegisterSubScript(id, function(pasteLink, errMsg)
self.controls.generateCodePastebin.label = "Share with Pastebin"
if errMsg then
main:OpenMessagePopup("Pastebin.com", "Error creating paste:\n"..errMsg)
else
self.controls.generateCodeOut:SetText(pasteLink)
end
end)
end
end)
self.controls.generateCodePastebin.enabled = function()
return #self.controls.generateCodeOut.buf > 0 and not self.controls.generateCodeOut.buf:match("pastebin%.com")
end
self.controls.generateCodeNote = common.New("LabelControl", {"TOPLEFT",self.controls.generateCodeOut,"BOTTOMLEFT"}, 0, 4, 0, 14, "^7Note: this code can be very long; you can use 'Share with Pastebin' to shrink it.")
self.controls.importCodeHeader = common.New("LabelControl", {"TOPLEFT",self.controls.generateCodeNote,"BOTTOMLEFT"}, 0, 26, 0, 16, "^7To import a build, enter the code here:")
self.controls.importCodeIn = common.New("EditControl", {"TOPLEFT",self.controls.importCodeHeader,"BOTTOMLEFT"}, 0, 4, 250, 20, "", nil, "^%w_%-=", nil, function(buf)
if #buf == 0 then
self.importCodeState = nil
return
end
self.importCodeState = "INVALID"
local xmlText = Inflate(common.base64.decode(buf:gsub("-","+"):gsub("_","/")))
if not xmlText then
return
end
self.importCodeState = "VALID"
self.importCodeXML = xmlText
if not self.build.dbFileName then
self.controls.importCodeMode.selIndex = 2
end
end)
self.controls.importCodeState = common.New("LabelControl", {"LEFT",self.controls.importCodeIn,"RIGHT"}, 4, 0, 0, 16)
self.controls.importCodeState.label = function()
return (self.importCodeState == "VALID" and colorCodes.POSITIVE.."Code is valid") or (self.importCodeState == "INVALID" and colorCodes.NEGATIVE.."Invalid code") or ""
end
self.controls.importCodePastebin = common.New("ButtonControl", {"LEFT",self.controls.importCodeIn,"RIGHT"}, 90, 0, 160, 20, "Import from Pastebin...", function()
self:OpenPastebinImportPopup()
end)
self.controls.importCodeMode = common.New("DropDownControl", {"TOPLEFT",self.controls.importCodeIn,"BOTTOMLEFT"}, 0, 4, 160, 20, { "Import to this build", "Import to a new build" })
self.controls.importCodeMode.enabled = function()
return self.importCodeState == "VALID" and self.build.dbFileName
end
self.controls.importCodeGo = common.New("ButtonControl", {"TOPLEFT",self.controls.importCodeMode,"BOTTOMLEFT"}, 0, 8, 60, 20, "Import", function()
if self.controls.importCodeMode.selIndex == 1 then
main:OpenConfirmPopup("Build Import", colorCodes.WARNING.."Warning:^7 Importing to the current build will erase ALL existing data for this build.", "Import", function()
self.build:Shutdown()
self.build:Init(self.build.dbFileName, self.build.buildName, self.importCodeXML)
self.build.viewMode = "TREE"
end)
else
self.build:Shutdown()
self.build:Init(false, "Imported build", self.importCodeXML)
self.build.viewMode = "TREE"
end
end)
self.controls.importCodeGo.enabled = function()
return self.importCodeState == "VALID"
end
end)
function ImportTabClass:Draw(viewPort, inputEvents)
self.x = viewPort.x
self.y = viewPort.y
self.width = viewPort.width
self.height = viewPort.height
self:ProcessControlsInput(inputEvents, viewPort)
main:DrawBackground(viewPort)
self:DrawControls(viewPort)
end
function ImportTabClass:DownloadCharacterList()
self.charImportMode = "DOWNLOADCHARLIST"
self.charImportStatus = "Retrieving character list..."
local accountName = self.controls.accountName.buf
local sessionID = #self.controls.sessionInput.buf == 32 and self.controls.sessionInput.buf or main.accountSessionIDs[accountName]
-- Region API determination
local getCharsApi = "https://www.pathofexile.com/character-window/get-characters?accountName="
if self.controls.accountRegion.selIndex == 2 then
getCharsApi = "https://poe.game.qq.com/character-window/get-characters?accountName="
end
launch:DownloadPage(getCharsApi..accountName, function(page, errMsg)
if errMsg == "Response code: 403" then
self.charImportStatus = colorCodes.NEGATIVE.."Account profile is private."
self.charImportMode = "GETSESSIONID"
return
elseif errMsg == "Response code: 404" then
self.charImportStatus = colorCodes.NEGATIVE.."Account name is incorrect."
self.charImportMode = "GETACCOUNTNAME"
return
elseif errMsg then
self.charImportStatus = colorCodes.NEGATIVE.."Error retrieving character list, try again ("..errMsg:gsub("\n"," ")..")"
self.charImportMode = "GETACCOUNTNAME"
return
end
local charList, errMsg = self:ProcessJSON(page)
if errMsg then
self.charImportStatus = colorCodes.NEGATIVE.."Error processing character list, try again later"
self.charImportMode = "GETACCOUNTNAME"
return
end
--ConPrintTable(charList)
if #charList == 0 then
self.charImportStatus = colorCodes.NEGATIVE.."The account has no characters to import."
self.charImportMode = "GETACCOUNTNAME"
return
end
-- Region API determination
local getProfileApi = "https://www.pathofexile.com/account/view-profile/"
if self.controls.accountRegion.selIndex == 2 then
getProfileApi = "https://poe.game.qq.com/account/view-profile/"
end
-- GGG's character API has an issue where for /get-characters the account name is not case-sensitive, but for /get-passive-skills and /get-items it is.
-- This workaround grabs the profile page and extracts the correct account name from one of the URLs.
launch:DownloadPage(getProfileApi..accountName, function(page, errMsg)
if errMsg then
self.charImportStatus = colorCodes.NEGATIVE.."Error retrieving character list, try again ("..errMsg:gsub("\n"," ")..")"
self.charImportMode = "GETACCOUNTNAME"
return
end
local realAccountName = page:match("/account/view%-profile/([^/]+)/characters"):gsub(".", function(c) if c:byte(1) > 127 then return string.format("%%%2X",c:byte(1)) else return c end end)
if not realAccountName then
self.charImportStatus = colorCodes.NEGATIVE.."Failed to retrieve character list."
self.charImportMode = "GETSESSIONID"
return
end
self.controls.accountName:SetText(realAccountName)
accountName = realAccountName
self.charImportStatus = "Character list successfully retrieved."
self.charImportMode = "SELECTCHAR"
main.lastAccountName = accountName
if sessionID then
main.accountSessionIDs[accountName] = sessionID
end
wipeTable(self.controls.charSelect.list)
for i, char in ipairs(charList) do
t_insert(self.controls.charSelect.list, {
label = string.format("%s: Level %d %s in %s", char.name or "?", char.level or 0, char.class or "?", char.league or "?"),
char = char,
})
end
table.sort(self.controls.charSelect.list, function(a,b)
return a.char.name:lower() < b.char.name:lower()
end)
end, sessionID and "POESESSID="..sessionID)
end, sessionID and "POESESSID="..sessionID)
end
function ImportTabClass:DownloadPassiveTree()
self.charImportMode = "IMPORTING"
self.charImportStatus = "Retrieving character passive tree..."
local accountName = self.controls.accountName.buf
local sessionID = #self.controls.sessionInput.buf == 32 and self.controls.sessionInput.buf or main.accountSessionIDs[accountName]
local charSelect = self.controls.charSelect
local charData = charSelect.list[charSelect.selIndex].char
-- Region API determination
local getPassivesApi = "https://www.pathofexile.com/character-window/get-passive-skills?accountName="
if self.controls.accountRegion.selIndex == 2 then
getPassivesApi = "https://poe.game.qq.com/character-window/get-passive-skills?accountName="
end
launch:DownloadPage(getPassivesApi..accountName.."&character="..charData.name, function(page, errMsg)
self.charImportMode = "SELECTCHAR"
if errMsg then
self.charImportStatus = colorCodes.NEGATIVE.."Error importing character data, try again ("..errMsg:gsub("\n"," ")..")"
return
elseif page == "false" then
self.charImportStatus = colorCodes.NEGATIVE.."Failed to retrieve character data, try again."
return
end
local charPassiveData, errMsg = self:ProcessJSON(page)
if errMsg then
self.charImportStatus = colorCodes.NEGATIVE.."Error processing character data, try again later."
return
end
self.charImportStatus = colorCodes.POSITIVE.."Passive tree and jewels successfully imported."
--ConPrintTable(charPassiveData)
if self.controls.charImportTreeClearJewels.state then
for _, slot in pairs(self.build.itemsTab.slots) do
if slot.selItemId ~= 0 and slot.nodeId then
self.build.itemsTab:DeleteItem(self.build.itemsTab.items[slot.selItemId])
end
end
end
local sockets = { }
for i, slot in pairs(charPassiveData.jewel_slots) do
sockets[i] = tonumber(slot.passiveSkill.hash)
end
for _, itemData in pairs(charPassiveData.items) do
self:ImportItem(itemData, sockets)
end
self.build.itemsTab:PopulateSlots()
self.build.itemsTab:AddUndoState()
self.build.spec:ImportFromNodeList(charData.classId, charData.ascendancyClass, charPassiveData.hashes)
self.build.spec:AddUndoState()
self.build.characterLevel = charData.level
self.build.controls.characterLevel:SetText(charData.level)
self.build.buildFlag = true
end, sessionID and "POESESSID="..sessionID)
end
function ImportTabClass:DownloadItems()
self.charImportMode = "IMPORTING"
self.charImportStatus = "Retrieving character items..."
local accountName = self.controls.accountName.buf
local sessionID = #self.controls.sessionInput.buf == 32 and self.controls.sessionInput.buf or main.accountSessionIDs[accountName]
local charSelect = self.controls.charSelect
local charData = charSelect.list[charSelect.selIndex].char
-- Region API determination
local getItemsApi = "https://www.pathofexile.com/character-window/get-items?accountName="
if self.controls.accountRegion.selIndex == 2 then
getItemsApi = "https://poe.game.qq.com/character-window/get-items?accountName="
end
launch:DownloadPage(getItemsApi..accountName.."&character="..charData.name, function(page, errMsg)
self.charImportMode = "SELECTCHAR"
if errMsg then
self.charImportStatus = colorCodes.NEGATIVE.."Error importing character data, try again ("..errMsg:gsub("\n"," ")..")"
return
elseif page == "false" then
self.charImportStatus = colorCodes.NEGATIVE.."Failed to retrieve character data, try again."
return
end
local charItemData, errMsg = self:ProcessJSON(page)
if errMsg then
self.charImportStatus = colorCodes.NEGATIVE.."Error processing character data, try again later."
return
end
if self.controls.charImportItemsClearItems.state then
for _, slot in pairs(self.build.itemsTab.slots) do
if slot.selItemId ~= 0 and not slot.nodeId then
self.build.itemsTab:DeleteItem(self.build.itemsTab.items[slot.selItemId])
end
end
end
local skillOrder
if self.controls.charImportItemsClearSkills.state then
skillOrder = { }
for _, socketGroup in ipairs(self.build.skillsTab.socketGroupList) do
for _, gem in ipairs(socketGroup.gemList) do
if gem.grantedEffect and not gem.grantedEffect.support then
t_insert(skillOrder, gem.grantedEffect.name)
end
end
end
wipeTable(self.build.skillsTab.socketGroupList)
end
self.charImportStatus = colorCodes.POSITIVE.."Items and skills successfully imported."
--ConPrintTable(charItemData)
for _, itemData in pairs(charItemData.items) do
self:ImportItem(itemData)
end
if skillOrder then
local groupOrder = { }
for index, socketGroup in ipairs(self.build.skillsTab.socketGroupList) do
groupOrder[socketGroup] = index
end
table.sort(self.build.skillsTab.socketGroupList, function(a, b)
local orderA
for _, gem in ipairs(a.gemList) do
if gem.grantedEffect and not gem.grantedEffect.support then
local i = isValueInArray(skillOrder, gem.grantedEffect.name)
if i and (not orderA or i < orderA) then
orderA = i
end
end
end
local orderB
for _, gem in ipairs(b.gemList) do
if gem.grantedEffect and not gem.grantedEffect.support then
local i = isValueInArray(skillOrder, gem.grantedEffect.name)
if i and (not orderB or i < orderB) then
orderB = i
end
end
end
if orderA and orderB then
if orderA ~= orderB then
return orderA < orderB
else
return groupOrder[a] < groupOrder[b]
end
elseif not orderA and not orderB then
return groupOrder[a] < groupOrder[b]
else
return orderA
end
end)
end
self.build.itemsTab:PopulateSlots()
self.build.itemsTab:AddUndoState()
self.build.skillsTab:AddUndoState()
self.build.buildFlag = true
end, sessionID and "POESESSID="..sessionID)
end
local rarityMap = { [0] = "NORMAL", "MAGIC", "RARE", "UNIQUE", [9] = "RELIC" }
local colorMap = { S = "R", D = "G", I = "B", G = "W" }
local slotMap = { ["Weapon"] = "Weapon 1", ["Offhand"] = "Weapon 2", ["Weapon2"] = "Weapon 1 Swap", ["Offhand2"] = "Weapon 2 Swap", ["Helm"] = "Helmet", ["BodyArmour"] = "Body Armour", ["Gloves"] = "Gloves", ["Boots"] = "Boots", ["Amulet"] = "Amulet", ["Ring"] = "Ring 1", ["Ring2"] = "Ring 2", ["Belt"] = "Belt" }
function ImportTabClass:ImportItem(itemData, sockets)
local slotName
if itemData.inventoryId == "PassiveJewels" and sockets then
slotName = "Jewel "..sockets[itemData.x + 1]
elseif itemData.inventoryId == "Flask" then
slotName = "Flask "..(itemData.x + 1)
else
slotName = slotMap[itemData.inventoryId]
end
if not slotName then
-- Ignore any items that won't go into known slots
return
end
local item = { }
-- Determine rarity, display name and base type of the item
item.rarity = rarityMap[itemData.frameType]
if #itemData.name > 0 then
item.title = itemLib.sanitiseItemText(itemData.name)
item.baseName = itemLib.sanitiseItemText(itemData.typeLine)
item.name = item.title .. ", " .. item.baseName
if item.baseName == "Two-Toned Boots" then
-- Hack for Two-Toned Boots
item.baseName = "Two-Toned Boots (Armour/Energy Shield)"
end
item.base = self.build.data.itemBases[item.baseName]
if item.base then
item.type = item.base.type
else
ConPrintf("Unrecognised base in imported item: %s", item.baseName)
end
else
item.name = itemLib.sanitiseItemText(itemData.typeLine)
for baseName, baseData in pairs(self.build.data.itemBases) do
local s, e = item.name:find(baseName, 1, true)
if s then
item.baseName = baseName
item.namePrefix = item.name:sub(1, s - 1)
item.nameSuffix = item.name:sub(e + 1)
item.type = baseData.type
break
end
end
if not item.baseName then
local s, e = item.name:find("Two-Toned Boots", 1, true)
if s then
-- Hack for Two-Toned Boots
item.baseName = "Two-Toned Boots (Armour/Energy Shield)"
item.namePrefix = item.name:sub(1, s - 1)
item.nameSuffix = item.name:sub(e + 1)
item.type = "Boots"
end
end
item.base = self.build.data.itemBases[item.baseName]
end
if not item.base or not item.rarity then
return
end
-- Import item data
item.uniqueID = itemData.id
if itemData.ilvl > 0 then
item.itemLevel = itemData.ilvl
end
if item.base.weapon or item.base.armour or item.base.flask then
item.quality = 0
end
if itemData.properties then
for _, property in pairs(itemData.properties) do
if property.name == "Quality" then
item.quality = tonumber(property.values[1][1]:match("%d+"))
elseif property.name == "Radius" then
for index, data in pairs(self.build.data.jewelRadius) do
if property.values[1][1] == data.label then
item.jewelRadiusIndex = index
break
end
end
elseif property.name == "Limited to" then
item.limit = tonumber(property.values[1][1])
elseif property.name == "Evasion Rating" then
if item.baseName == "Two-Toned Boots (Armour/Energy Shield)" then
-- Another hack for Two-Toned Boots
item.baseName = "Two-Toned Boots (Armour/Evasion)"
item.base = self.build.data.itemBases[item.baseName]
end
elseif property.name == "Energy Shield" then
if item.baseName == "Two-Toned Boots (Armour/Evasion)" then
-- Yet another hack for Two-Toned Boots
item.baseName = "Two-Toned Boots (Evasion/Energy Shield)"
item.base = self.build.data.itemBases[item.baseName]
end
end
end
end
if itemData.corrupted then
item.corrupted = true
end
if itemData.sockets[1] then
item.sockets = { }
for i, socket in pairs(itemData.sockets) do
item.sockets[i] = { group = socket.group, color = colorMap[socket.attr] }
end
end
if itemData.socketedItems then
self:ImportSocketedSkills(item, itemData.socketedItems, slotName)
end
if itemData.requirements and (not itemData.socketedItems or not itemData.socketedItems[1]) then
-- Requirements cannot be trusted if there are socketed gems, as they may override the item's natural requirements
item.requirements = { }
for _, req in ipairs(itemData.requirements) do
if req.name == "Level" then
item.requirements.level = req.values[1][1]
end
end
end
item.modLines = { }
item.implicitLines = 0
if itemData.implicitMods then
item.implicitLines = item.implicitLines + #itemData.implicitMods
for _, line in ipairs(itemData.implicitMods) do
line = line:gsub("\n"," ")
local modList, extra = modLib.parseMod[self.build.targetVersion](line)
t_insert(item.modLines, { line = line, extra = extra, mods = modList or { } })
end
end
if itemData.enchantMods then
item.implicitLines = item.implicitLines + #itemData.enchantMods
for _, line in ipairs(itemData.enchantMods) do
line = line:gsub("\n"," ")
local modList, extra = modLib.parseMod[self.build.targetVersion](line)
t_insert(item.modLines, { line = line, extra = extra, mods = modList or { }, crafted = true })
end
end
if itemData.explicitMods then
for _, line in ipairs(itemData.explicitMods) do
for line in line:gmatch("[^\n]+") do
local modList, extra = modLib.parseMod[self.build.targetVersion](line)
t_insert(item.modLines, { line = line, extra = extra, mods = modList or { } })
end
end
end
if itemData.craftedMods then
for _, line in ipairs(itemData.craftedMods) do
for line in line:gmatch("[^\n]+") do
local modList, extra = modLib.parseMod[self.build.targetVersion](line)
t_insert(item.modLines, { line = line, extra = extra, mods = modList or { }, crafted = true })
end
end
end
-- Add and equip the new item
item.raw = itemLib.createItemRaw(item)
-- ConPrintf("%s", item.raw)
local newItem = itemLib.makeItemFromRaw(self.build.targetVersion, item.raw)
if newItem then
local repIndex, repItem
for index, item in pairs(self.build.itemsTab.items) do
if item.uniqueID == itemData.id then
repIndex = index
repItem = item
break
end
end
if repIndex then
-- Item already exists in the build, overwrite it
newItem.id = repItem.id
self.build.itemsTab.items[newItem.id] = newItem
itemLib.buildItemModList(newItem)
else
self.build.itemsTab:AddItem(newItem, true)
end
self.build.itemsTab.slots[slotName]:SetSelItemId(newItem.id)
end
end
function ImportTabClass:ImportSocketedSkills(item, socketedItems, slotName)
-- Build socket group list
local itemSocketGroupList = { }
for _, socketedItem in ipairs(socketedItems) do
local gem = { level = 20, quality = 0, enabled = true}
gem.nameSpec = socketedItem.typeLine:gsub(" Support","")
gem.support = socketedItem.support
for _, property in pairs(socketedItem.properties) do
if property.name == "Level" then
gem.level = tonumber(property.values[1][1]:match("%d+"))
elseif property.name == "Quality" then
gem.quality = tonumber(property.values[1][1]:match("%d+"))
end
end
local groupID = item.sockets[socketedItem.socket + 1].group
if not itemSocketGroupList[groupID] then
itemSocketGroupList[groupID] = { label = "", enabled = true, gemList = { }, slot = slotName }
end
local socketGroup = itemSocketGroupList[groupID]
if not socketedItem.support and socketGroup.gemList[1] and socketGroup.gemList[1].support then
-- If the first gem is a support gem, put the first active gem before it
t_insert(socketGroup.gemList, 1, gem)
else
t_insert(socketGroup.gemList, gem)
end
end
-- Import the socket groups
for _, itemSocketGroup in pairs(itemSocketGroupList) do
-- Check if this socket group matches an existing one
local repGroup
for index, socketGroup in pairs(self.build.skillsTab.socketGroupList) do
if #socketGroup.gemList == #itemSocketGroup.gemList and (not socketGroup.slot or socketGroup.slot == slotName) then
local match = true
for gemIndex, gem in pairs(socketGroup.gemList) do
if gem.nameSpec:lower() ~= itemSocketGroup.gemList[gemIndex].nameSpec:lower() then
match = false
break
end
end
if match then
repGroup = socketGroup
break
end
end
end
if repGroup then
-- Update the existing one
for gemIndex, gem in pairs(repGroup.gemList) do
local itemGem = itemSocketGroup.gemList[gemIndex]
gem.level = itemGem.level
gem.quality = itemGem.quality
end
else
t_insert(self.build.skillsTab.socketGroupList, itemSocketGroup)
end
self.build.skillsTab:ProcessSocketGroup(itemSocketGroup)
end
end
function ImportTabClass:OpenPastebinImportPopup()
local controls = { }
controls.editLabel = common.New("LabelControl", nil, 0, 20, 0, 16, "Enter Pastebin.com link:")
controls.edit = common.New("EditControl", nil, 0, 40, 250, 18, "", nil, nil, nil, function(buf)
controls.msg.label = ""
end)
controls.msg = common.New("LabelControl", nil, 0, 58, 0, 16, "")
controls.import = common.New("ButtonControl", nil, -45, 80, 80, 20, "Import", function()
controls.import.enabled = false
controls.msg.label = "Retrieving paste..."
launch:DownloadPage(controls.edit.buf:gsub("pastebin%.com/(%w+)$","pastebin.com/raw/%1"), function(page, errMsg)
if errMsg then
controls.msg.label = "^1"..errMsg
controls.import.enabled = true
else
self.controls.importCodeIn:SetText(page, true)
main:ClosePopup()
end
end)
end)
controls.import.enabled = function()
return #controls.edit.buf > 0 and controls.edit.buf:match("pastebin%.com/%w+")
end
controls.cancel = common.New("ButtonControl", nil, 45, 80, 80, 20, "Cancel", function()
main:ClosePopup()
end)
main:OpenPopup(280, 110, "Import from Pastebin", controls, "import", "edit")
end
function ImportTabClass:ProcessJSON(json)
local func, errMsg = loadstring("return "..jsonToLua(json))
if errMsg then
return nil, errMsg
end
setfenv(func, { }) -- Sandbox the function just in case
local data = func()
if type(data) ~= "table" then
return nil, "Return type is not a table"
end
return data
end
| mit |
djkamran021/BY | plugins/msg-checks.lua | 8 | 13951 | --Begin msg_checks.lua By @SoLiD
local TIME_CHECK = 2
local function pre_process(msg)
local data = load_data(_config.moderation.data)
local chat = msg.to.id
local user = msg.from.id
local is_channel = msg.to.type == "channel"
local is_chat = msg.to.type == "chat"
local auto_leave = 'auto_leave_bot'
local hash = "gp_lang:"..chat
local lang = redis:get(hash)
local muteallchk = 'muteall:'..msg.to.id
if is_channel or is_chat then
local TIME_CHECK = 2
if data[tostring(chat)] then
if data[tostring(chat)]['settings']['time_check'] then
TIME_CHECK = tonumber(data[tostring(chat)]['settings']['time_check'])
end
end
if msg.text then
if msg.text:match("(.*)") then
if not data[tostring(msg.to.id)] and not redis:get(auto_leave) and not is_admin(msg) then
tdcli.sendMessage(msg.to.id, "", 0, "_This Is Not One Of My_ *Groups*", 0, "md")
tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil)
end
end
end
if redis:get(muteallchk) and not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if not redis:get('autodeltime') then
redis:setex('autodeltime', 14400, true)
run_bash("rm -rf ~/.telegram-cli/data/sticker/*")
run_bash("rm -rf ~/.telegram-cli/data/photo/*")
run_bash("rm -rf ~/.telegram-cli/data/animation/*")
run_bash("rm -rf ~/.telegram-cli/data/video/*")
run_bash("rm -rf ~/.telegram-cli/data/audio/*")
run_bash("rm -rf ~/.telegram-cli/data/voice/*")
run_bash("rm -rf ~/.telegram-cli/data/temp/*")
run_bash("rm -rf ~/.telegram-cli/data/thumb/*")
run_bash("rm -rf ~/.telegram-cli/data/document/*")
run_bash("rm -rf ~/.telegram-cli/data/profile_photo/*")
run_bash("rm -rf ~/.telegram-cli/data/encrypted/*")
run_bash("rm -rf ./data/photos/*")
end
if data[tostring(chat)] and data[tostring(chat)]['mutes'] then
mutes = data[tostring(chat)]['mutes']
else
return
end
if mutes.mute_gif then
mute_gif = mutes.mute_gif
else
mute_gif = 'no'
end
if mutes.mute_photo then
mute_photo = mutes.mute_photo
else
mute_photo = 'no'
end
if mutes.mute_sticker then
mute_sticker = mutes.mute_sticker
else
mute_sticker = 'no'
end
if mutes.mute_contact then
mute_contact = mutes.mute_contact
else
mute_contact = 'no'
end
if mutes.mute_inline then
mute_inline = mutes.mute_inline
else
mute_inline = 'no'
end
if mutes.mute_game then
mute_game = mutes.mute_game
else
mute_game = 'no'
end
if mutes.mute_text then
mute_text = mutes.mute_text
else
mute_text = 'no'
end
if mutes.mute_keyboard then
mute_keyboard = mutes.mute_keyboard
else
mute_keyboard = 'no'
end
if mutes.mute_forward then
mute_forward = mutes.mute_forward
else
mute_forward = 'no'
end
if mutes.mute_location then
mute_location = mutes.mute_location
else
mute_location = 'no'
end
if mutes.mute_document then
mute_document = mutes.mute_document
else
mute_document = 'no'
end
if mutes.mute_voice then
mute_voice = mutes.mute_voice
else
mute_voice = 'no'
end
if mutes.mute_audio then
mute_audio = mutes.mute_audio
else
mute_audio = 'no'
end
if mutes.mute_video then
mute_video = mutes.mute_video
else
mute_video = 'no'
end
if mutes.mute_tgservice then
mute_tgservice = mutes.mute_tgservice
else
mute_tgservice = 'no'
end
if data[tostring(chat)] and data[tostring(chat)]['settings'] then
settings = data[tostring(chat)]['settings']
else
return
end
if settings.lock_link then
lock_link = settings.lock_link
else
lock_link = 'no'
end
if settings.lock_join then
lock_join = settings.lock_join
else
lock_join = 'no'
end
if settings.lock_tag then
lock_tag = settings.lock_tag
else
lock_tag = 'no'
end
if settings.lock_pin then
lock_pin = settings.lock_pin
else
lock_pin = 'no'
end
if settings.lock_arabic then
lock_arabic = settings.lock_arabic
else
lock_arabic = 'no'
end
if settings.lock_mention then
lock_mention = settings.lock_mention
else
lock_mention = 'no'
end
if settings.lock_edit then
lock_edit = settings.lock_edit
else
lock_edit = 'no'
end
if settings.lock_spam then
lock_spam = settings.lock_spam
else
lock_spam = 'no'
end
if settings.lock_flood then
lock_flood = settings.lock_flood
else
lock_flood = 'no'
end
if settings.lock_markdown then
lock_markdown = settings.lock_markdown
else
lock_markdown = 'no'
end
if settings.lock_webpage then
lock_webpage = settings.lock_webpage
else
lock_webpage = 'no'
end
if msg.adduser or msg.joinuser or msg.deluser then
if mute_tgservice == "yes" then
del_msg(chat, tonumber(msg.id))
end
end
if not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) then
if msg.adduser or msg.joinuser then
if lock_join == "yes" then
function join_kick(arg, data)
kick_user(data.id_, msg.to.id)
end
if msg.adduser then
tdcli.getUser(msg.adduser, join_kick, nil)
elseif msg.joinuser then
tdcli.getUser(msg.joinuser, join_kick, nil)
end
end
end
end
if msg.pinned and is_channel then
if lock_pin == "yes" then
if is_owner(msg) then
return
end
if tonumber(msg.from.id) == our_id then
return
end
local pin_msg = data[tostring(chat)]['pin']
if pin_msg then
tdcli.pinChannelMessage(msg.to.id, pin_msg, 1)
elseif not pin_msg then
tdcli.unpinChannelMessage(msg.to.id)
end
if lang then
tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>شما اجازه دسترسی به سنجاق پیام را ندارید، به همین دلیل پیام قبلی مجدد سنجاق میگردد</i>', 0, "html")
elseif not lang then
tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>You Have Not Permission To Pin Message, Last Message Has Been Pinned Again</i>', 0, "html")
end
end
end
if not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) then
if msg.edited and lock_edit == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.forward_info_ and mute_forward == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.photo_ and mute_photo == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.video_ and mute_video == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.document_ and mute_document == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.sticker_ and mute_sticker == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.animation_ and mute_gif == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.contact_ and mute_contact == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.location_ and mute_location == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.voice_ and mute_voice == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.content_ and mute_keyboard == "yes" then
if msg.reply_markup_ and msg.reply_markup_.ID == "ReplyMarkupInlineKeyboard" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if tonumber(msg.via_bot_user_id_) ~= 0 and mute_inline == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.game_ and mute_game == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.audio_ and mute_audio == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.media.caption then
local link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.media.caption:match("[Tt].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if link_caption
and lock_link == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local tag_caption = msg.media.caption:match("@") or msg.media.caption:match("#")
if tag_caption and lock_tag == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if is_filter(msg, msg.media.caption) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local arabic_caption = msg.media.caption:match("[\216-\219][\128-\191]")
if arabic_caption and lock_arabic == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.text then
local _nl, ctrl_chars = string.gsub(msg.text, '%c', '')
local max_chars = 40
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_char'] then
max_chars = tonumber(data[tostring(msg.to.id)]['settings']['set_char'])
end
end
local _nl, real_digits = string.gsub(msg.text, '%d', '')
local max_real_digits = tonumber(max_chars) * 50
local max_len = tonumber(max_chars) * 51
if lock_spam == "yes" then
if string.len(msg.text) > max_len or ctrl_chars > max_chars or real_digits > max_real_digits then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
local link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.text:match("[Tt].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if link_msg
and lock_link == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local tag_msg = msg.text:match("@") or msg.text:match("#")
if tag_msg and lock_tag == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if is_filter(msg, msg.text) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local arabic_msg = msg.text:match("[\216-\219][\128-\191]")
if arabic_msg and lock_arabic == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.text:match("(.*)")
and mute_text == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_ and msg.content_.entities_[0] then
if msg.content_.entities_[0].ID == "MessageEntityMentionName" then
if lock_mention == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_[0].ID == "MessageEntityUrl" or msg.content_.entities_[0].ID == "MessageEntityTextUrl" then
if lock_webpage == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_[0].ID == "MessageEntityBold" or msg.content_.entities_[0].ID == "MessageEntityCode" or msg.content_.entities_[0].ID == "MessageEntityPre" or msg.content_.entities_[0].ID == "MessageEntityItalic" then
if lock_markdown == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
end
if msg.to.type ~= 'pv' then
if lock_flood == "yes" then
if is_mod(msg) and is_whitelist(msg.from.id, msg.to.id) then
return
end
if msg.adduser or msg.joinuser then
return
end
local hash = 'user:'..user..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local NUM_MSG_MAX = 5
if data[tostring(chat)] then
if data[tostring(chat)]['settings']['num_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(chat)]['settings']['num_msg_max'])
end
end
if msgs > NUM_MSG_MAX then
if msg.from.username then
user_name = "@"..msg.from.username
else
user_name = msg.from.first_name
end
if redis:get('sender:'..user..':flood') then
return
else
del_msg(chat, msg.id)
kick_user(user, chat)
redis:del(hash)
if not lang then
tdcli.sendMessage(chat, msg.id, 0, "_User_ "..user_name.." `[ "..user.." ]` _has been_ *kicked* _because of_ *flooding*", 0, "md")
elseif lang then
tdcli.sendMessage(chat, msg.id, 0, "_کاربر_ "..user_name.." `[ "..user.." ]` _به دلیل ارسال پیام های مکرر اخراج شد_", 0, "md")
end
redis:setex('sender:'..user..':flood', 30, true)
end
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
end
end
return msg
end
return {
patterns = {},
patterns_fa = {},
pre_process = pre_process
}
--End msg_checks.lua--
| gpl-3.0 |
spoconnor/ElixirMessagingServer | EclipseWorkspace/LuaClient/runtime/win32/http.lua | 45 | 12330 | -----------------------------------------------------------------------------
-- HTTP/1.1 client support for the Lua language.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-------------------------------------------------------------------------------
local socket = require("socket")
local url = require("socket.url")
local ltn12 = require("ltn12")
local mime = require("mime")
local string = require("string")
local headers = require("socket.headers")
local base = _G
local table = require("table")
socket.http = {}
local _M = socket.http
-----------------------------------------------------------------------------
-- Program constants
-----------------------------------------------------------------------------
-- connection timeout in seconds
TIMEOUT = 60
-- default port for document retrieval
_M.PORT = 80
-- user agent field sent in request
_M.USERAGENT = socket._VERSION
-----------------------------------------------------------------------------
-- Reads MIME headers from a connection, unfolding where needed
-----------------------------------------------------------------------------
local function receiveheaders(sock, headers)
local line, name, value, err
headers = headers or {}
-- get first line
line, err = sock:receive()
if err then return nil, err end
-- headers go until a blank line is found
while line ~= "" do
-- get field-name and value
name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)"))
if not (name and value) then return nil, "malformed reponse headers" end
name = string.lower(name)
-- get next line (value might be folded)
line, err = sock:receive()
if err then return nil, err end
-- unfold any folded values
while string.find(line, "^%s") do
value = value .. line
line = sock:receive()
if err then return nil, err end
end
-- save pair in table
if headers[name] then headers[name] = headers[name] .. ", " .. value
else headers[name] = value end
end
return headers
end
-----------------------------------------------------------------------------
-- Extra sources and sinks
-----------------------------------------------------------------------------
socket.sourcet["http-chunked"] = function(sock, headers)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
-- get chunk size, skip extention
local line, err = sock:receive()
if err then return nil, err end
local size = base.tonumber(string.gsub(line, ";.*", ""), 16)
if not size then return nil, "invalid chunk size" end
-- was it the last chunk?
if size > 0 then
-- if not, get chunk and skip terminating CRLF
local chunk, err, part = sock:receive(size)
if chunk then sock:receive() end
return chunk, err
else
-- if it was, read trailers into headers table
headers, err = receiveheaders(sock, headers)
if not headers then return nil, err end
end
end
})
end
socket.sinkt["http-chunked"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then return sock:send("0\r\n\r\n") end
local size = string.format("%X\r\n", string.len(chunk))
return sock:send(size .. chunk .. "\r\n")
end
})
end
-----------------------------------------------------------------------------
-- Low level HTTP API
-----------------------------------------------------------------------------
local metat = { __index = {} }
function _M.open(host, port, create)
-- create socket with user connect function, or with default
local c = socket.try((create or socket.tcp)())
local h = base.setmetatable({ c = c }, metat)
-- create finalized try
h.try = socket.newtry(function() h:close() end)
-- set timeout before connecting
h.try(c:settimeout(_M.TIMEOUT))
h.try(c:connect(host, port or _M.PORT))
-- here everything worked
return h
end
function metat.__index:sendrequestline(method, uri)
local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri)
return self.try(self.c:send(reqline))
end
function metat.__index:sendheaders(tosend)
local canonic = headers.canonic
local h = "\r\n"
for f, v in base.pairs(tosend) do
h = (canonic[f] or f) .. ": " .. v .. "\r\n" .. h
end
self.try(self.c:send(h))
return 1
end
function metat.__index:sendbody(headers, source, step)
source = source or ltn12.source.empty()
step = step or ltn12.pump.step
-- if we don't know the size in advance, send chunked and hope for the best
local mode = "http-chunked"
if headers["content-length"] then mode = "keep-open" end
return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step))
end
function metat.__index:receivestatusline()
local status = self.try(self.c:receive(5))
-- identify HTTP/0.9 responses, which do not contain a status line
-- this is just a heuristic, but is what the RFC recommends
if status ~= "HTTP/" then return nil, status end
-- otherwise proceed reading a status line
status = self.try(self.c:receive("*l", status))
local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)"))
return self.try(base.tonumber(code), status)
end
function metat.__index:receiveheaders()
return self.try(receiveheaders(self.c))
end
function metat.__index:receivebody(headers, sink, step)
sink = sink or ltn12.sink.null()
step = step or ltn12.pump.step
local length = base.tonumber(headers["content-length"])
local t = headers["transfer-encoding"] -- shortcut
local mode = "default" -- connection close
if t and t ~= "identity" then mode = "http-chunked"
elseif base.tonumber(headers["content-length"]) then mode = "by-length" end
return self.try(ltn12.pump.all(socket.source(mode, self.c, length),
sink, step))
end
function metat.__index:receive09body(status, sink, step)
local source = ltn12.source.rewind(socket.source("until-closed", self.c))
source(status)
return self.try(ltn12.pump.all(source, sink, step))
end
function metat.__index:close()
return self.c:close()
end
-----------------------------------------------------------------------------
-- High level HTTP API
-----------------------------------------------------------------------------
local function adjusturi(reqt)
local u = reqt
-- if there is a proxy, we need the full url. otherwise, just a part.
if not reqt.proxy and not PROXY then
u = {
path = socket.try(reqt.path, "invalid path 'nil'"),
params = reqt.params,
query = reqt.query,
fragment = reqt.fragment
}
end
return url.build(u)
end
local function adjustproxy(reqt)
local proxy = reqt.proxy or PROXY
if proxy then
proxy = url.parse(proxy)
return proxy.host, proxy.port or 3128
else
return reqt.host, reqt.port
end
end
local function adjustheaders(reqt)
-- default headers
local lower = {
["user-agent"] = _M.USERAGENT,
["host"] = reqt.host,
["connection"] = "close, TE",
["te"] = "trailers"
}
-- if we have authentication information, pass it along
if reqt.user and reqt.password then
lower["authorization"] =
"Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password))
end
-- override with user headers
for i,v in base.pairs(reqt.headers or lower) do
lower[string.lower(i)] = v
end
return lower
end
-- default url parts
local default = {
host = "",
port = _M.PORT,
path ="/",
scheme = "http"
}
local function adjustrequest(reqt)
-- parse url if provided
local nreqt = reqt.url and url.parse(reqt.url, default) or {}
-- explicit components override url
for i,v in base.pairs(reqt) do nreqt[i] = v end
if nreqt.port == "" then nreqt.port = 80 end
socket.try(nreqt.host and nreqt.host ~= "",
"invalid host '" .. base.tostring(nreqt.host) .. "'")
-- compute uri if user hasn't overriden
nreqt.uri = reqt.uri or adjusturi(nreqt)
-- ajust host and port if there is a proxy
nreqt.host, nreqt.port = adjustproxy(nreqt)
-- adjust headers in request
nreqt.headers = adjustheaders(nreqt)
return nreqt
end
local function shouldredirect(reqt, code, headers)
return headers.location and
string.gsub(headers.location, "%s", "") ~= "" and
(reqt.redirect ~= false) and
(code == 301 or code == 302 or code == 303 or code == 307) and
(not reqt.method or reqt.method == "GET" or reqt.method == "HEAD")
and (not reqt.nredirects or reqt.nredirects < 5)
end
local function shouldreceivebody(reqt, code)
if reqt.method == "HEAD" then return nil end
if code == 204 or code == 304 then return nil end
if code >= 100 and code < 200 then return nil end
return 1
end
-- forward declarations
local trequest, tredirect
--[[local]] function tredirect(reqt, location)
local result, code, headers, status = trequest {
-- the RFC says the redirect URL has to be absolute, but some
-- servers do not respect that
url = url.absolute(reqt.url, location),
source = reqt.source,
sink = reqt.sink,
headers = reqt.headers,
proxy = reqt.proxy,
nredirects = (reqt.nredirects or 0) + 1,
create = reqt.create
}
-- pass location header back as a hint we redirected
headers = headers or {}
headers.location = headers.location or location
return result, code, headers, status
end
--[[local]] function trequest(reqt)
-- we loop until we get what we want, or
-- until we are sure there is no way to get it
local nreqt = adjustrequest(reqt)
local h = _M.open(nreqt.host, nreqt.port, nreqt.create)
-- send request line and headers
h:sendrequestline(nreqt.method, nreqt.uri)
h:sendheaders(nreqt.headers)
-- if there is a body, send it
if nreqt.source then
h:sendbody(nreqt.headers, nreqt.source, nreqt.step)
end
local code, status = h:receivestatusline()
-- if it is an HTTP/0.9 server, simply get the body and we are done
if not code then
h:receive09body(status, nreqt.sink, nreqt.step)
return 1, 200
end
local headers
-- ignore any 100-continue messages
while code == 100 do
headers = h:receiveheaders()
code, status = h:receivestatusline()
end
headers = h:receiveheaders()
-- at this point we should have a honest reply from the server
-- we can't redirect if we already used the source, so we report the error
if shouldredirect(nreqt, code, headers) and not nreqt.source then
h:close()
return tredirect(reqt, headers.location)
end
-- here we are finally done
if shouldreceivebody(nreqt, code) then
h:receivebody(headers, nreqt.sink, nreqt.step)
end
h:close()
return 1, code, headers, status
end
local function srequest(u, b)
local t = {}
local reqt = {
url = u,
sink = ltn12.sink.table(t)
}
if b then
reqt.source = ltn12.source.string(b)
reqt.headers = {
["content-length"] = string.len(b),
["content-type"] = "application/x-www-form-urlencoded"
}
reqt.method = "POST"
end
local code, headers, status = socket.skip(1, trequest(reqt))
return table.concat(t), code, headers, status
end
_M.request = socket.protect(function(reqt, body)
if base.type(reqt) == "string" then return srequest(reqt, body)
else return trequest(reqt) end
end)
return _M | mit |
magx2/nsn-money-changer | gnuplot/share/lua/gnuplot-tikz.lua | 1 | 77068 | --[[
This is the execution script for the `Lua generic terminal' driver.
This script provides an interface to the PGF/TikZ package for LaTeX.
Copyright 2008 Peter Hedwig <peter@affenbande.org>
Permission to use, copy, and distribute this software and its
documentation for any purpose with or without fee is hereby granted,
provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear
in supporting documentation.
Permission to modify the software is granted, but not the right to
distribute the complete modified source code. Modifications are to
be distributed as patches to the released version. Permission to
distribute binaries produced by compiling modified sources is granted,
provided you
1. distribute the corresponding source modifications from the
released version in the form of a patch file along with the binaries,
2. add special version identification to distinguish your version
in addition to the base release version number,
3. provide your name and address as the primary contact for the
support of your modified version, and
4. retain our contact information in regard to use of the base
software.
Permission to distribute the released version of the source code along
with corresponding source modifications in the form of a patch file is
granted with same provisions 2 through 4 for binary distributions.
This software is provided "as is" without express or implied warranty
to the extent permitted by applicable law.
$Date: 2012/02/07 17:54:15 $
$Author: sfeam $
$Rev: 100 $
]]--
--[[
`term' gnuplot term_api -> local interface
`gp' local -> gnuplot interface
are both initialized by the terminal
]]--
--
-- internal variables
--
local pgf = {}
local gfx = {}
-- the terminal default size in cm
pgf.DEFAULT_CANVAS_SIZE_X = 12.5
pgf.DEFAULT_CANVAS_SIZE_Y = 8.75
-- tic default size in cm
pgf.DEFAULT_TIC_SIZE = 0.18
-- the terminal resolution in "dots" per cm.
pgf.DEFAULT_RESOLUTION = 1000
-- default font size in TeX pt
pgf.DEFAULT_FONT_SIZE = 10
-- default sizes for CM@10pt and default resolution
-- there is no need to adapt these values when changing
-- pgf.DEFAULT_FONT_SIZE or pgf.DEFAULT_RESOLUTION !
pgf.DEFAULT_FONT_H_CHAR = 184
pgf.DEFAULT_FONT_V_CHAR = 308
pgf.STYLE_FILE_BASENAME = "gnuplot-lua-tikz" -- \usepackage{gnuplot-lua-tikz}
pgf.REVISION = string.sub("$Rev: 100 $",7,-3)
pgf.REVISION_DATE = string.gsub("$Date: 2012/02/07 17:54:15 $",
"$Date: ([0-9]+).([0-9]+).([0-9]+) .*","%1/%2/%3")
pgf.styles = {}
-- the styles are used in conjunction with the 'tikzarrows'
-- and the style number directly corresponds to the used
-- angle in the gnuplot style definition
pgf.styles.arrows = {
[1] = {"gp arrow 1", ">=latex"},
[2] = {"gp arrow 2", ">=angle 90"},
[3] = {"gp arrow 3", ">=angle 60"},
[4] = {"gp arrow 4", ">=angle 45"},
[5] = {"gp arrow 5", ">=o"},
[6] = {"gp arrow 6", ">=*"},
[7] = {"gp arrow 7", ">=diamond"},
[8] = {"gp arrow 8", ">=open diamond"},
[9] = {"gp arrow 9", ">={]}"},
[10] = {"gp arrow 10", ">={[}"},
[11] = {"gp arrow 11", ">=)"},
[12] = {"gp arrow 12", ">=("}
}
-- plot styles are corresponding with linetypes and must have the same number of entries
-- see option 'tikzplot' for usage
pgf.styles.plotstyles_axes = {
[1] = {"gp plot axes", ""},
[2] = {"gp plot border", ""},
}
pgf.styles.plotstyles = {
[1] = {"gp plot 0", "smooth"},
[2] = {"gp plot 1", "smooth"},
[3] = {"gp plot 2", "smooth"},
[4] = {"gp plot 3", "smooth"},
[5] = {"gp plot 4", "smooth"},
[6] = {"gp plot 5", "smooth"},
[7] = {"gp plot 6", "smooth"},
[8] = {"gp plot 7", "smooth"}
}
pgf.styles.linetypes_axes = {
[1] = {"gp lt axes", "dotted"}, -- An lt of -1 is used for the X and Y axes.
[2] = {"gp lt border", "solid"}, -- An lt of -2 is used for the border of the plot.
}
pgf.styles.linetypes = {
[1] = {"gp lt plot 0", "solid"}, -- first graph
[2] = {"gp lt plot 1", "dashed"}, -- second ...
[3] = {"gp lt plot 2", "dash pattern=on 1.5pt off 2.25pt"},
[4] = {"gp lt plot 3", "dash pattern=on \\pgflinewidth off 1.125"},
[5] = {"gp lt plot 4", "dash pattern=on 4.5pt off 1.5pt on \\pgflinewidth off 1.5pt"},
[6] = {"gp lt plot 5", "dash pattern=on 2.25pt off 2.25pt on \\pgflinewidth off 2.25pt"},
[7] = {"gp lt plot 6", "dash pattern=on 1.5pt off 1.5pt on 1.5pt off 4.5pt"},
[8] = {"gp lt plot 7", "dash pattern=on \\pgflinewidth off 1.5pt on 4.5pt off 1.5pt on \\pgflinewidth off 1.5pt"}
}
-- corresponds to pgf.styles.linetypes
pgf.styles.lt_colors_axes = {
[1] = {"gp lt color axes", "black!30"},
[2] = {"gp lt color border", "black"},
}
pgf.styles.lt_colors = {
[1] = {"gp lt color 0", "red"},
[2] = {"gp lt color 1", "green"},
[3] = {"gp lt color 2", "blue"},
[4] = {"gp lt color 3", "magenta"},
[5] = {"gp lt color 4", "cyan"},
[6] = {"gp lt color 5", "yellow"},
[7] = {"gp lt color 6", "orange"},
[8] = {"gp lt color 7", "purple"}
}
pgf.styles.patterns = {
[1] = {"gp pattern 0", "white"},
[2] = {"gp pattern 1", "pattern=north east lines"},
[3] = {"gp pattern 2", "pattern=north west lines"},
[4] = {"gp pattern 3", "pattern=crosshatch"},
[5] = {"gp pattern 4", "pattern=grid"},
[6] = {"gp pattern 5", "pattern=vertical lines"},
[7] = {"gp pattern 6", "pattern=horizontal lines"},
[8] = {"gp pattern 7", "pattern=dots"},
[9] = {"gp pattern 8", "pattern=crosshatch dots"},
[10] = {"gp pattern 9", "pattern=fivepointed stars"},
[11] = {"gp pattern 10", "pattern=sixpointed stars"},
[12] = {"gp pattern 11", "pattern=bricks"}
}
pgf.styles.plotmarks = {
[1] = {"gp mark 0", "mark size=.5\\pgflinewidth,mark=*"}, -- point (-1)
[2] = {"gp mark 1", "mark=+"},
[3] = {"gp mark 2", "mark=x"},
[4] = {"gp mark 3", "mark=star"},
[5] = {"gp mark 4", "mark=square"},
[6] = {"gp mark 5", "mark=square*"},
[7] = {"gp mark 6", "mark=o"},
[8] = {"gp mark 7", "mark=*"},
[9] = {"gp mark 8", "mark=triangle"},
[10] = {"gp mark 9", "mark=triangle*"},
[11] = {"gp mark 10", "mark=triangle,every mark/.append style={rotate=180}"},
[12] = {"gp mark 11", "mark=triangle*,every mark/.append style={rotate=180}"},
[13] = {"gp mark 12", "mark=diamond"},
[14] = {"gp mark 13", "mark=diamond*"},
[15] = {"gp mark 14", "mark=otimes"},
[16] = {"gp mark 15", "mark=oplus"}
}
--[[===============================================================================================
helper functions
]]--===============================================================================================
-- from the Lua wiki
explode = function(div,str)
if (div=='') then return false end
local pos,arr = 0,{}
local trim = function(s) return (string.gsub(s,"^%s*(.-)%s*$", "%1")) end
-- for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr, trim(string.sub(str,pos,st-1))) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr, trim(string.sub(str,pos))) -- Attach chars right of last divider
return arr
end
--[[===============================================================================================
The PGF/TikZ output routines
]]--===============================================================================================
pgf.transform_xcoord = function(coord)
return (coord+gfx.origin_xoffset)*gfx.scalex
end
pgf.transform_ycoord = function(coord)
return (coord+gfx.origin_yoffset)*gfx.scaley
end
pgf.format_coord = function(xc, yc)
return string.format("%.3f,%.3f", pgf.transform_xcoord(xc), pgf.transform_ycoord(yc))
end
pgf.write_doc_begin = function(preamble)
gp.write(gfx.format[gfx.opt.tex_format].docheader)
gp.write(preamble)
gp.write(gfx.format[gfx.opt.tex_format].begindocument)
end
pgf.write_doc_end = function()
gp.write(gfx.format[gfx.opt.tex_format].enddocument)
end
pgf.write_graph_begin = function (font, noenv)
local global_opt = "" -- unused
if gfx.opt.full_doc then
gp.write(gfx.format[gfx.opt.tex_format].beforetikzpicture)
end
if noenv then
gp.write("%% ") -- comment out
end
gp.write(string.format("%s[gnuplot%s]\n", gfx.format[gfx.opt.tex_format].begintikzpicture, global_opt))
gp.write(string.format("%%%% generated with GNUPLOT %sp%s (%s; terminal rev. %s, script rev. %s)\n",
term.gp_version, term.gp_patchlevel, _VERSION, string.sub(term.lua_term_revision,7,-3), pgf.REVISION))
if not gfx.opt.notimestamp then
gp.write(string.format("%%%% %s\n", os.date()))
end
if font ~= "" then
gp.write(string.format("\\tikzset{every node/.append style={font=%s}}\n", font))
end
if gfx.opt.fontscale ~= nil then
gp.write(string.format("\\tikzset{every node/.append style={scale=%.2f}}\n", gfx.opt.fontscale))
end
if not gfx.opt.lines_dashed then
gp.write("\\gpsolidlines\n")
end
if not gfx.opt.lines_colored then
gp.write("\\gpmonochromelines\n")
end
if gfx.opt.bgcolor ~= nil then
gp.write(string.format("\\gpsetbgcolor{%.3f,%.3f,%.3f}\n", gfx.opt.bgcolor[1], gfx.opt.bgcolor[2], gfx.opt.bgcolor[3]))
end
end
pgf.write_graph_end = function(noenv)
if noenv then
gp.write("%% ") -- comment out
end
if gfx.opt.full_doc then
gp.write(gfx.format[gfx.opt.tex_format].beforeendtikzpicture)
end
gp.write(gfx.format[gfx.opt.tex_format].endtikzpicture .. "\n")
if gfx.opt.full_doc then
gp.write(gfx.format[gfx.opt.tex_format].aftertikzpicture)
end
end
pgf.draw_path = function(t)
local use_plot = false
local c_str = '--'
-- is the current linetype in the list of plots?
if #gfx.opt.plot_list > 0 then
for k, v in pairs(gfx.opt.plot_list) do
if gfx.linetype_idx_set == v then
use_plot = true
c_str = ' '
break
end
end
end
gp.write("\\draw[gp path] ")
if use_plot then
gp.write("plot["..pgf.styles.plotstyles[((gfx.linetype_idx_set) % #pgf.styles.plotstyles)+1][1].."] coordinates {")
end
gp.write("("..pgf.format_coord(t[1][1], t[1][2])..")")
for i = 2,#t-1 do
-- pretty printing
if (i % 6) == 0 then
gp.write("%\n ")
end
gp.write(c_str.."("..pgf.format_coord(t[i][1], t[i][2])..")")
end
if (#t % 6) == 0 then
gp.write("%\n ")
end
-- check for a cyclic path
if (t[1][1] == t[#t][1]) and (t[1][2] == t[#t][2]) and (not use_plot) then
gp.write("--cycle")
else
gp.write(c_str.."("..pgf.format_coord(t[#t][1], t[#t][2])..")")
end
if use_plot then
gp.write("}")
end
gp.write(";\n")
end
pgf.draw_arrow = function(t, direction, headstyle)
gp.write("\\draw[gp path")
if direction ~= '' then
gp.write(","..direction)
end
if headstyle > 0 then
gp.write(",gp arrow "..headstyle)
end
gp.write("]")
gp.write("("..pgf.format_coord(t[1][1], t[1][2])..")")
for i = 2,#t do
if (i % 6) == 0 then
gp.write("%\n ")
end
gp.write("--("..pgf.format_coord(t[i][1], t[i][2])..")")
end
gp.write(";\n")
end
pgf.draw_points = function(t, pm)
gp.write("\\gppoint{"..pm.."}{")
for i,v in ipairs(t) do
gp.write("("..pgf.format_coord(v[1], v[2])..")")
end
gp.write("}\n")
end
pgf.set_linetype = function(linetype)
gp.write("\\gpsetlinetype{"..linetype.."}\n")
end
pgf.set_color = function(color)
gp.write("\\gpcolor{"..color.."}\n")
end
pgf.set_linewidth = function(width)
gp.write(string.format("\\gpsetlinewidth{%.2f}\n", width))
end
pgf.set_pointsize = function(size)
gp.write(string.format("\\gpsetpointsize{%.2f}\n", 4*size))
end
pgf.write_text_node = function(t, text, angle, justification, font)
local node_options = justification
if angle ~= 0 then
node_options = node_options .. ",rotate=" .. angle
end
if font ~= '' then
node_options = node_options .. ",font=" .. font
end
gp.write(string.format("\\node[%s] at (%s) {%s};\n",
node_options, pgf.format_coord(t[1], t[2]), text))
end
pgf.draw_fill = function(t, pattern, color, saturation, opacity)
local fill_path = ''
local fill_style = color
if saturation < 100 then
fill_style = fill_style .. ",color=.!"..saturation;
end
fill_path = fill_path .. '('..pgf.format_coord(t[1][1], t[1][2])..')'
-- draw 2nd to n-1 corners
for i = 2,#t-1 do
if (i % 5) == 0 then
-- pretty printing
fill_path = fill_path .. "%\n "
end
fill_path = fill_path .. '--('..pgf.format_coord(t[i][1], t[i][2])..')'
end
if (#t % 5) == 0 then
gp.write("%\n ")
end
-- draw last corner
-- 'cycle' is just for the case that we want to draw a
-- line around the filled area
if (t[1][1] == t[#t][1]) and (t[1][2] == t[#t][2]) then -- cyclic
fill_path = fill_path .. '--cycle'
else
fill_path = fill_path
.. '--('..pgf.format_coord(t[#t][1], t[#t][2])..')--cycle'
end
if pattern == '' then
-- solid fills
-- fill_style = 'color='..color
if opacity < 100 then
fill_style = fill_style..string.format(",opacity=%.2f", opacity/100)
else
-- fill_style = "" -- color ?
end
else
-- pattern fills
fill_style = fill_style..','..pattern..',pattern color=.'
end
local out = ''
if (pattern ~= '') and (opacity == 100) then
-- have to fill bg for opaque patterns
gp.write("\\def\\gpfillpath{"..fill_path.."}\n"
.. "\\gpfill{color=gpbgfillcolor} \\gpfillpath;\n"
.. "\\gpfill{"..fill_style.."} \\gpfillpath;\n")
else
gp.write("\\gpfill{"..fill_style.."} "..fill_path..";\n")
end
end
pgf.load_image_file = function(ll, ur, xfile)
gp.write(string.format("\\gploadimage{%.3f}{%.3f}{%.3f}{%.3f}{%s}\n",
pgf.transform_xcoord(ll[1]), pgf.transform_ycoord(ll[2]),
(pgf.transform_xcoord(ur[1]) - pgf.transform_xcoord(ll[1])),
(pgf.transform_ycoord(ur[2]) - pgf.transform_ycoord(ll[2])),
xfile))
end
pgf.draw_raw_rgb_image = function(t, m, n, ll, ur, xfile)
local gw = gp.write
local sf = string.format
local xs = sf("%.3f", pgf.transform_xcoord(ur[1]) - pgf.transform_xcoord(ll[1]))
local ys = sf("%.3f", pgf.transform_ycoord(ur[2]) - pgf.transform_ycoord(ll[2]))
gw("\\def\\gprawrgbimagedata{%\n ")
for cnt = 1,#t do
gw(sf("%02x%02x%02x", 255*t[cnt][1]+0.5, 255*t[cnt][2]+0.5, 255*t[cnt][3]+0.5))
if (cnt % 16) == 0 then
gw("%\n ")
end
end
gw("}%\n")
gw("\\gprawimage{rgb}{"..sf("%.3f", pgf.transform_xcoord(ll[1])).."}"
.."{"..sf("%.3f", pgf.transform_ycoord(ll[2])).."}"
.."{"..m.."}{"..n.."}{"..xs.."}{"..ys.."}{\\gprawrgbimagedata}{"..xfile.."}\n")
end
pgf.draw_raw_cmyk_image = function(t, m, n, ll, ur, xfile)
local gw = gp.write
local sf = string.format
local min = math.min
local max = math.max
local mf = math.floor
local UCRBG = {1,1,1,1} -- default corrections
local rgb2cmyk255 = function(r,g,b)
local c = 1-r
local m = 1-g
local y = 1-b
local k = min(c,m,y)
c = mf(255*min(1, max(0, c - UCRBG[1]*k))+0.5)
m = mf(255*min(1, max(0, m - UCRBG[2]*k))+0.5)
y = mf(255*min(1, max(0, y - UCRBG[3]*k))+0.5)
k = mf(255*min(1, max(0, UCRBG[4]*k))+0.5)
return c,m,y,k
end
local xs = sf("%.3f", pgf.transform_xcoord(ur[1]) - pgf.transform_xcoord(ll[1]))
local ys = sf("%.3f", pgf.transform_ycoord(ur[2]) - pgf.transform_ycoord(ll[2]))
gw("\\def\\gprawcmykimagedata{%\n ")
for cnt = 1,#t do
gw(sf("%02x%02x%02x%02x", rgb2cmyk255(t[cnt][1],t[cnt][2],t[cnt][3])))
if (cnt % 12) == 0 then
gw("%\n ")
end
end
gw("}%\n")
gw("\\gprawimage{cmyk}{"..sf("%.3f", pgf.transform_xcoord(ll[1])).."}"
.."{"..sf("%.3f", pgf.transform_ycoord(ll[2])).."}"
.."{"..m.."}{"..n.."}{"..xs.."}{"..ys.."}{\\gprawcmykimagedata}{"..xfile.."}\n")
end
pgf.write_clipbox_begin = function (ll, ur)
gp.write(gfx.format[gfx.opt.tex_format].beginscope.."\n")
gp.write(string.format("\\clip (%s) rectangle (%s);\n",
pgf.format_coord(ll[1],ll[2]),pgf.format_coord(ur[1],ur[2])))
end
pgf.write_clipbox_end = function()
gp.write(gfx.format[gfx.opt.tex_format].endscope.."\n")
end
pgf.write_boundingbox = function(t, num)
gp.write("%% coordinates of the plot area\n")
gp.write("\\gpdefrectangularnode{gp plot "..num.."}{"
..string.format("\\pgfpoint{%.3fcm}{%.3fcm}", pgf.transform_xcoord(t.xleft), pgf.transform_ycoord(t.ybot)).."}{"
..string.format("\\pgfpoint{%.3fcm}{%.3fcm}", pgf.transform_xcoord(t.xright), pgf.transform_ycoord(t.ytop)).."}\n")
end
pgf.write_variables = function(t)
gp.write("%% gnuplot variables\n")
for k, v in pairs(t) do
gp.write(string.format("\\gpsetvar{%s}{%s}\n",k,v))
end
end
-- write style to seperate file, or whatever...
pgf.create_style = function()
local name_common = pgf.STYLE_FILE_BASENAME.."-common.tex"
local name_latex = pgf.STYLE_FILE_BASENAME..".sty"
local name_tex = pgf.STYLE_FILE_BASENAME..".tex"
local name_context = "t-"..pgf.STYLE_FILE_BASENAME..".tex"
-- LaTeX
local f_latex = io.open(name_latex, "w+")
f_latex:write([[
%%
%% LaTeX wrapper for gnuplot-tikz style file
%%
\NeedsTeXFormat{LaTeX2e}
]])
f_latex:write("\\ProvidesPackage{"..pgf.STYLE_FILE_BASENAME.."}%\n")
f_latex:write(" ["..pgf.REVISION_DATE.." (rev. "..pgf.REVISION..") GNUPLOT Lua terminal style]\n\n")
f_latex:write([[
\RequirePackage{tikz}
\usetikzlibrary{arrows,patterns,plotmarks,backgrounds}
]])
f_latex:write("\\input "..name_common.."\n")
f_latex:write([[
\endinput
]])
f_latex:close()
-- ConTeXt
local f_context = io.open(name_context, "w+")
f_context:write([[
%%
%% ConTeXt wrapper for gnuplot-tikz style file
%%
\usemodule[tikz]
\usetikzlibrary[arrows,patterns,plotmarks,backgrounds]
\edef\tikzatcode{\the\catcode`\@}
\edef\tikzbarcode{\the\catcode`\|}
\edef\tikzexclaimcode{\the\catcode`\!}
\catcode`\@=11
\catcode`\|=12
\catcode`\!=12
]])
f_context:write("\\input "..name_common.."\n")
f_context:write([[
\catcode`\@=\tikzatcode
\catcode`\|=\tikzbarcode
\catcode`\!=\tikzexclaimcode
\endinput
]])
f_context:close()
-- plain TeX
local f_tex = io.open(name_tex, "w+")
f_tex:write([[
%%
%% plain TeX wrapper for gnuplot-tikz style file
%%
\input tikz.tex
\usetikzlibrary{arrows,patterns,plotmarks,backgrounds}
\edef\tikzatcode{\the\catcode`\@}
\catcode`\@=11
]])
f_tex:write("\\input "..name_common.."\n\n")
f_tex:write([[
\catcode`\@=\tikzatcode
\endinput
]])
f_tex:close()
-- common
local f = io.open(name_common, "w+")
f:write([[
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Common style file for TeX, LaTeX and ConTeXt
%%
%% It is associated with the 'gnuplot.lua' script, and usually generated
%% automatically. So take care whenever you make any changes!
%%
% check for the correct TikZ version
\def\gpchecktikzversion#1.#2\relax{%
\ifnum#1<2%
\PackageError{gnuplot-lua-tikz}{PGF/TikZ version >= 2.0 is required, but version \pgfversion\space was found}{}%
\fi}
\expandafter\gpchecktikzversion\pgfversion\relax
% FIXME: is there a more elegant way to determine the output format?
\def\pgfsysdriver@a{pgfsys-dvi.def} % ps
\def\pgfsysdriver@b{pgfsys-dvipdfm.def} % pdf
\def\pgfsysdriver@c{pgfsys-dvipdfmx.def} % pdf
\def\pgfsysdriver@d{pgfsys-dvips.def} % ps
\def\pgfsysdriver@e{pgfsys-pdftex.def} % pdf
\def\pgfsysdriver@f{pgfsys-tex4ht.def} % html
\def\pgfsysdriver@g{pgfsys-textures.def} % ps
\def\pgfsysdriver@h{pgfsys-vtex.def} % ps
\def\pgfsysdriver@i{pgfsys-xetex.def} % pdf
\newif\ifgppdfout\gppdfoutfalse
\newif\ifgppsout\gppsoutfalse
\ifx\pgfsysdriver\pgfsysdriver@a
\gppsouttrue
\else\ifx\pgfsysdriver\pgfsysdriver@b
\gppdfouttrue
\else\ifx\pgfsysdriver\pgfsysdriver@c
\gppdfouttrue
\else\ifx\pgfsysdriver\pgfsysdriver@d
\gppsouttrue
\else\ifx\pgfsysdriver\pgfsysdriver@e
\gppdfouttrue
\else\ifx\pgfsysdriver\pgfsysdriver@f
% tex4ht
\else\ifx\pgfsysdriver\pgfsysdriver@g
\gppsouttrue
\else\ifx\pgfsysdriver\pgfsysdriver@h
\gppsouttrue
\else\ifx\pgfsysdriver\pgfsysdriver@i
\gppdfouttrue
\fi\fi\fi\fi\fi\fi\fi\fi\fi
% uncomment the following lines to make font values "appendable"
% and if you are really sure about that ;-)
% \pgfkeyslet{/tikz/font/.@cmd}{\undefined}
% \tikzset{font/.initial={}}
% \def\tikz@textfont{\pgfkeysvalueof{/tikz/font}}
%
% image related stuff
%
\def\gp@rawimage@pdf#1#2#3#4#5#6{%
\def\gp@tempa{cmyk}%
\def\gp@tempb{#1}%
\ifx\gp@tempa\gp@tempb%
\def\gp@temp{/CMYK}%
\else%
\def\gp@temp{/RGB}%
\fi%
\pgf@sys@bp{#4}\pgfsysprotocol@literalbuffered{0 0}\pgf@sys@bp{#5}%
\pgfsysprotocol@literalbuffered{0 0 cm}%
\pgfsysprotocol@literalbuffered{BI /W #2 /H #3 /CS \gp@temp}%
\pgfsysprotocol@literalbuffered{/BPC 8 /F /AHx ID}%
\pgfsysprotocol@literal{#6 > EI}%
}
\def\gp@rawimage@ps#1#2#3#4#5#6{%
\def\gp@tempa{cmyk}%
\def\gp@tempb{#1}%
\ifx\gp@tempa\gp@tempb%
\def\gp@temp{4}%
\else%
\def\gp@temp{3}%
\fi%
\pgfsysprotocol@literalbuffered{0 0 translate}%
\pgf@sys@bp{#4}\pgf@sys@bp{#5}\pgfsysprotocol@literalbuffered{scale}%
\pgfsysprotocol@literalbuffered{#2 #3 8 [#2 0 0 -#3 0 #3]}%
\pgfsysprotocol@literalbuffered{currentfile /ASCIIHexDecode filter}%
\pgfsysprotocol@literalbuffered{false \gp@temp\space colorimage}%
\pgfsysprotocol@literal{#6 >}%
}
\def\gp@rawimage@html#1#2#3#4#5#6{%
% FIXME: print a warning message here
}
\ifgppdfout
\def\gp@rawimage{\gp@rawimage@pdf}
\else
\ifgppsout
\def\gp@rawimage{\gp@rawimage@ps}
\else
\def\gp@rawimage{\gp@rawimage@html}
\fi
\fi
\def\gploadimage#1#2#3#4#5{%
\pgftext[left,bottom,x=#1cm,y=#2cm] {\pgfimage[interpolate=false,width=#3cm,height=#4cm]{#5}};%
}
\def\gp@set@size#1{%
\def\gp@image@size{#1}%
}
\def\gp@rawimage@#1#2#3#4#5#6#7#8{
\tikz@scan@one@point\gp@set@size(#6,#7)\relax%
\tikz@scan@one@point\pgftransformshift(#2,#3)\relax%
\pgftext {%
\pgfsys@beginpurepicture%
\gp@image@size% fill \pgf@x and \pgf@y
\gp@rawimage{#1}{#4}{#5}{\pgf@x}{\pgf@y}{#8}%
\pgfsys@endpurepicture%
}%
}
%% \gprawimage{color model}{xcoord}{ycoord}{# of xpixel}{# of ypixel}{xsize}{ysize}{rgb/cmyk hex data RRGGBB/CCMMYYKK ...}{file name}
%% color model is 'cmyk' or 'rgb' (default)
\def\gprawimage#1#2#3#4#5#6#7#8#9{%
\ifx	&%
\gp@rawimage@{#1}{#2}{#3}{#4}{#5}{#6}{#7}{#8}
\else
\ifgppsout
\gp@rawimage@{#1}{#2}{#3}{#4}{#5}{#6}{#7}{#8}
\else
\gploadimage{#2}{#3}{#6}{#7}{#9}
\fi
\fi
}
%
% gnuplottex comapatibility
% (see http://www.ctan.org/tex-archive/help/Catalogue/entries/gnuplottex.html)
%
\def\gnuplottexextension@lua{\string tex}
\def\gnuplottexextension@tikz{\string tex}
%
% gnuplot variables getter and setter
%
\def\gpsetvar#1#2{%
\expandafter\xdef\csname gp@var@#1\endcsname{#2}
}
\def\gpgetvar#1{%
\csname gp@var@#1\endcsname %
}
%
% some wrapper code
%
% short for a filled path
\def\gpfill#1{\path[line width=0.1\gpbaselw,draw,fill,#1]}
% short for changing the line width
\def\gpsetlinewidth#1{\pgfsetlinewidth{#1\gpbaselw}}
% short for changing the line type
\def\gpsetlinetype#1{\tikzset{gp path/.style={#1,#1 add}}}
% short for changing the point size
\def\gpsetpointsize#1{\tikzset{gp point/.style={mark size=#1\gpbasems}}}
% wrapper for color settings
\def\gpcolor#1{\tikzset{global #1}}
\tikzset{rgb color/.code={\pgfutil@definecolor{.}{rgb}{#1}\tikzset{color=.}}}
\tikzset{global rgb color/.code={\pgfutil@definecolor{.}{rgb}{#1}\pgfutil@color{.}}}
\tikzset{global color/.code={\pgfutil@color{#1}}}
% prevent plot mark distortions due to changes in the PGF transformation matrix
% use `\gpscalepointstrue' and `\gpscalepointsfalse' for enabling and disabling
% point scaling
%
\newif\ifgpscalepoints
\tikzset{gp shift only/.style={%
\ifgpscalepoints\else shift only\fi%
}}
\def\gppoint#1#2{%
\path[solid] plot[only marks,gp point,mark options={gp shift only},#1] coordinates {#2};%
}
%
% char size calculation, that might be used with gnuplottex
%
% Example code (needs gnuplottex.sty):
%
% % calculate the char size when the "gnuplot" style is used
% \tikzset{gnuplot/.append style={execute at begin picture=\gpcalccharsize}}
%
% \tikzset{gnuplot/.append style={font=\ttfamily\footnotesize}}
%
% \begin{tikzpicture}[gnuplot]
% \begin{gnuplot}[terminal=lua,%
% terminaloptions={tikz solid nopic charsize \the\gphcharsize,\the\gpvcharsize}]
% test
% \end{gnuplot}
% \end{tikzpicture}
%
%%%
% The `\gpcalccharsize' command fills the lengths \gpvcharsize and \gphcharsize with
% the values of the current default font used within nodes and is meant to be called
% within a tikzpicture environment.
%
\newdimen\gpvcharsize
\newdimen\gphcharsize
\def\gpcalccharsize{%
\pgfinterruptboundingbox%
\pgfsys@begininvisible%
\node at (0,0) {%
\global\gphcharsize=1.05\fontcharwd\font`0%
\global\gpvcharsize=1.05\fontcharht\font`0%
\global\advance\gpvcharsize by 1.05\fontchardp\font`g%
};%
\pgfsys@endinvisible%
\endpgfinterruptboundingbox%
}
%
% define a rectangular node in tikz e.g. for the plot area
%
% #1 node name
% #2 coordinate of "south west"
% #3 coordinate of "north east"
%
\def\gpdefrectangularnode#1#2#3{%
\expandafter\gdef\csname pgf@sh@ns@#1\endcsname{rectangle}
\expandafter\gdef\csname pgf@sh@np@#1\endcsname{%
\def\southwest{#2}%
\def\northeast{#3}%
}
\pgfgettransform\pgf@temp%
% once it is defined, no more transformations will be applied, I hope
\expandafter\xdef\csname pgf@sh@nt@#1\endcsname{\pgf@temp}%
\expandafter\xdef\csname pgf@sh@pi@#1\endcsname{\pgfpictureid}%
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% You may want to adapt the following to fit your needs (in your
%% individual style file and/or within your document).
%%
%
% style for every plot
%
\tikzset{gnuplot/.style={%
>=stealth',%
line cap=round,%
line join=round,%
}}
\tikzset{gp node left/.style={anchor=mid west,yshift=-.12ex}}
\tikzset{gp node center/.style={anchor=mid,yshift=-.12ex}}
\tikzset{gp node right/.style={anchor=mid east,yshift=-.12ex}}
% basic plot mark size (points)
\newdimen\gpbasems
\gpbasems=.4pt
% basic linewidth
\newdimen\gpbaselw
\gpbaselw=.4pt
% this is the default color for pattern backgrounds
\colorlet{gpbgfillcolor}{white}
% set background color and fill color
\def\gpsetbgcolor#1{%
\pgfutil@definecolor{gpbgfillcolor}{rgb}{#1}%
\tikzset{tight background,background rectangle/.style={fill=gpbgfillcolor},show background rectangle}%
}
% this should reverse the normal text node presets, for the
% later referencing as described below
\tikzset{gp refnode/.style={coordinate,yshift=.12ex}}
% to add an empty label with the referenceable name "my node"
% to the plot, just add the following line to your gnuplot
% file:
%
% set label "" at 1,1 font ",gp refnode,name=my node"
%
% enlargement of the bounding box in standalone mode (only used by LaTeX/ConTeXt)
\def\gpbboxborder{0mm}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% The following TikZ-styles are derived from the 'pgf.styles.*' tables
%% in the Lua script.
%% To change the number of used styles you should change them there and
%% regenerate this style file.
%%
]])
f:write("% arrow styles settings\n")
for i = 1, #pgf.styles.arrows do
f:write("\\tikzset{"..pgf.styles.arrows[i][1].."/.style={"..pgf.styles.arrows[i][2].."}}\n")
end
f:write("\n% plotmark settings\n")
for i = 1, #pgf.styles.plotmarks do
f:write("\\tikzset{"..pgf.styles.plotmarks[i][1].."/.style={"..pgf.styles.plotmarks[i][2].."}}\n")
end
f:write("\n% pattern settings\n")
for i = 1, #pgf.styles.patterns do
f:write("\\tikzset{"..pgf.styles.patterns[i][1].."/.style={"..pgf.styles.patterns[i][2].."}}\n")
end
f:write("\n% if the 'tikzplot' option is used the corresponding lines will be smoothed by default\n")
for i = 1, #pgf.styles.plotstyles_axes do
f:write("\\tikzset{"..pgf.styles.plotstyles_axes[i][1].."/.style="..pgf.styles.plotstyles_axes[i][2].."}\n")
end
for i = 1, #pgf.styles.plotstyles do
f:write("\\tikzset{"..pgf.styles.plotstyles[i][1].."/.style="..pgf.styles.plotstyles[i][2].."}\n")
end
-- line styles for borders etc ...
f:write("\n% linestyle settings\n")
for i = 1, #pgf.styles.linetypes_axes do
f:write("\\tikzset{"..pgf.styles.linetypes_axes[i][1].."/.style="..pgf.styles.linetypes_axes[i][2].."}\n")
end
f:write("\n% linestyle \"addon\" settings for overwriting a default linestyle within the\n")
f:write("% TeX document via eg. \\tikzset{gp lt plot 1 add/.style={fill=black,draw=none}} etc.\n")
for i = 1, #pgf.styles.linetypes_axes do
f:write("\\tikzset{"..pgf.styles.linetypes_axes[i][1].." add/.style={}}\n")
end
for i = 1, #pgf.styles.linetypes do
f:write("\\tikzset{"..pgf.styles.linetypes[i][1].." add/.style={}}\n")
end
f:write("\n% linestyle color settings\n")
for i = 1, #pgf.styles.lt_colors_axes do
f:write("\\colorlet{"..pgf.styles.lt_colors_axes[i][1].."}{"..pgf.styles.lt_colors_axes[i][2].."}\n")
end
-- line styles for the plots
f:write("\n% command for switching to dashed lines\n")
f:write("\\def\\gpdashedlines{%\n")
for i = 1, #pgf.styles.linetypes do
f:write(" \\tikzset{"..pgf.styles.linetypes[i][1].."/.style={"..pgf.styles.linetypes[i][2].."}}\n")
end
f:write("}\n")
f:write("\n% command for switching to colored lines\n")
f:write("\\def\\gpcoloredlines{%\n")
for i = 1, #pgf.styles.lt_colors do
f:write(" \\colorlet{"..pgf.styles.lt_colors[i][1].."}{"..pgf.styles.lt_colors[i][2].."}%\n")
end
f:write("}\n")
f:write("\n% command for switching to solid lines\n")
f:write("\\def\\gpsolidlines{%\n")
for i = 1, #pgf.styles.linetypes do
f:write(" \\tikzset{"..pgf.styles.linetypes[i][1].."/.style=solid}%\n")
end
f:write("}\n")
f:write("\n% command for switching to monochrome (black) lines\n")
f:write("\\def\\gpmonochromelines{%\n")
for i = 1, #pgf.styles.lt_colors do
f:write(" \\colorlet{"..pgf.styles.lt_colors[i][1].."}{black}%\n")
end
f:write("}\n\n")
f:write([[
%
% some initialisations
%
% by default all lines will be colored and dashed
\gpcoloredlines
\gpdashedlines
\gpsetpointsize{4}
\gpsetlinetype{gp lt solid}
\gpscalepointsfalse
\endinput
]])
f:close()
end
pgf.print_help = function(fwrite)
fwrite([[
{latex | tex | context}
{color | monochrome}
{dashed | solid}
{nooriginreset | originreset}
{nogparrows | gparrows}
{nogppoints | gppoints}
{picenvironment | nopicenvironment}
{noclip | clip}
{notightboundingbox | tightboundingbox}
{background "<colorpec>"}
{size <x>{unit},<y>{unit}}
{scale <x>,<y>}
{plotsize <x>{unit},<y>{unit}}
{charsize <x>{unit},<y>{unit}}
{font "<fontdesc>"}
{{fontscale | textscale} <scale>}
{nofulldoc | nostandalone | fulldoc | standalone}
{{preamble | header} "<preamble_string>"}
{tikzplot <ltn>,...}
{notikzarrows | tikzarrows}
{rgbimages | cmykimages}
{noexternalimages|externalimages}
{bitmap | nobitmap}
{providevars <var name>,...}
{createstyle}
{help}
For all options that expect lengths as their arguments they
will default to 'cm' if no unit is specified. For all lengths
the following units may be used: 'cm', 'mm', 'in' or 'inch',
'pt', 'pc', 'bp', 'dd', 'cc'. Blanks between numbers and units
are not allowed.
'monochrome' disables line coloring and switches to grayscaled
fills.
'solid' use only solid lines.
'originreset' moves the origin of the TikZ picture to the lower
left corner of the plot. It may be used to align several plots
within one tikzpicture environment. This is not tested with
multiplots and pm3d plots!
'gparrows' use gnuplot's internal arrow drawing function
instead of the ones provided by TikZ.
'gppoints' use gnuplot's internal plotmark drawing function
instead of the ones provided by TikZ.
'nopicenvironment' omits the declaration of the 'tikzpicture'
environment in order to set it manually. This permits putting
some PGF/TikZ code directly before or after the plot.
'clip' crops the plot at the defined canvas size. Default is
'noclip' by which only a minimum bounding box of the canvas size
is set. Neither a fixed bounding box nor a crop box is set if the
'plotsize' or 'tightboundingbox' option is used.
If 'tightboundingbox' is set the 'clip' option is ignored and the
final bounding box is the natural bounding box calculated by tikz.
'background' sets the background color to the value specified in
the <colorpec> argument. <colorspec> must be a valid color name or
a 3 byte RGB code as a hexadecimal number with a preceding number
sign ('#'). E.g. '#ff0000' specifies pure red. If omitted the
background is transparent.
The 'size' option expects two lenghts <x> and <y> as the canvas
size. The default size of the canvas is ]]..pgf.DEFAULT_CANVAS_SIZE_X..[[cm x ]]..pgf.DEFAULT_CANVAS_SIZE_Y..[[cm.
The 'scale' option works similar to the 'size' option but expects
scaling factors <x> and <y> instead of lengths.
The 'plotsize' option permits setting the size of the plot area
instead of the canvas size, which is the usual gnuplot behaviour.
Using this option may lead to slightly asymmetric tic lengths.
Like 'originreset' this option may not lead to convenient results
if used with multiplots or pm3d plots. An alternative approach
is to set all margins to zero and to use the 'noclip' option.
The plot area has then the dimensions of the given canvas sizes.
The 'charsize' option expects the average horizontal and vertical
size of the used font. Look at the generated style file for an
example of how to use it from within your TeX document.
'fontscale' or 'textscale' expects a scaling factor as a parameter.
All texts in the plot are scaled by this factor then.
The options 'tex', 'latex' and 'context' choose the TeX output
format. LaTeX is the default. To load the style file put the
according line at the beginning of your document:
\input ]]..pgf.STYLE_FILE_BASENAME..[[.tex % (for plain TeX)
\usepackage{]]..pgf.STYLE_FILE_BASENAME..[[} % (for LaTeX)
\usemodule[]]..pgf.STYLE_FILE_BASENAME..[[] % (for ConTeXt)
'createstyle' derives the TeX/LaTeX/ConTeXt styles from the script
and writes them to the appropriate files.
'fulldoc' or 'standalone' produces a full LaTeX document for direct
compilation.
'preamble' or 'header' may be used to put any additional LaTeX code
into the document preamble in standalone mode.
With the 'tikzplot' option the '\path plot' command will be used
instead of only '\path'. The following list of numbers of linetypes
(<ltn>,...) defines the affected plotlines. There exists a plotstyle
for every linetype. The default plotstyle is 'smooth' for every
linetype >= 1.
By using the 'tikzarrows' option the gnuplot arrow styles defined by
the user will be mapped to TikZ arrow styles. This is done by 'misusing'
the angle value of the arrow definition. E.g. an arrow style with the
angle '7' will be mapped to the TikZ style 'gp arrow 7' ignoring all the
other given values. By default the TikZ terminal uses the stealth' arrow
tips for all arrows. To obtain the default gnuplot behaviour please use
the 'gparrows' option.
With 'cmykimages' the CMYK color model will be used for inline image data
instead of the RGB model. All other colors (like line colors etc.) are
not affected by this option, since they are handled e.g. by LaTeX's
xcolor package. This option is ignored if images are externalized.
By using the 'externalimages' option all bitmap images will be written
as external PNG images and included at compile time of the document.
Generating DVI and later postscript files requires to convert the PNGs
into EPS files in a seperate step e.g. by using ImageMagick's `convert`.
Transparent bitmap images are always generated as an external PNGs.
The 'nobitmap' option let images be rendered as filled rectangles instead
of the nativ PS or PDF inline image format. This option is ignored if
images are externalized.
The 'providevars' options makes gnuplot's internal and user variables
available by using the '\gpgetvar{<var name>}' commmand within the TeX
script. Use gnuplot's 'show variables all' command to see the list
of valid variables.
The <fontdesc> string may contain any valid TeX/LaTeX/ConTeXt font commands
like e.g. '\small'. It is passed directly as a node parameter in form of
"font={<fontdesc>}". This can be 'misused' to add further code to a node,
e.g. '\small,yshift=1ex' or ',yshift=1ex' are also valid while the
latter does not change the current font settings. One exception is
the second argument of the list. If it is a number of the form
<number>{unit} it will be interpreted as a fontsize like in other
terminals and will be appended to the first argument. If the unit is
omitted the value is interpreted as 'pt'. As an example the string
'\sffamily,12,fill=red' sets the font to LaTeX's sans serif font at
a size of 12pt and red background color.
The same applies to ConTeXt, e.g. '\switchtobodyfont[iwona],10' changes the
font to Iwona at a size of 10pt.
Plain TeX users have to change the font size explicitly within the first
argument. The second should be set to the same value to get proper scaling
of text boxes.
Strings have to be put in single or double quotes. Double quoted
strings may contain special characters like newlines '\n' etc.
]])
end
--[[===============================================================================================
gfx.* helper functions
Main intention is to prevent redundancies in the drawing
operations and keep the pgf.* API as consistent as possible.
]]--===============================================================================================
-- path coordinates
gfx.path = {}
gfx.posx = nil
gfx.posy = nil
gfx.linetype_idx = nil -- current linetype intended for the plot
gfx.linetype_idx_set = nil -- current linetype set in the plot
gfx.linewidth = nil
gfx.linewidth_set = nil
-- internal calculated scaling factors
gfx.scalex = 1
gfx.scaley = 1
-- recalculate the origin of the plot
-- used for moving the origin to the lower left
-- corner...
gfx.origin_xoffset = 0
gfx.origin_yoffset = 0
-- color set in the document
gfx.color = ''
gfx.color_set = ''
gfx.pointsize = nil
gfx.pointsize_set = nil
gfx.text_font = ''
gfx.text_justify = "center"
gfx.text_angle = 0
-- option vars
gfx.opt = {
latex_preamble = '',
default_font = '',
lines_dashed = true,
lines_colored = true,
-- use gnuplot arrows or points instead of TikZ?
gp_arrows = false,
gp_points = false,
-- don't put graphic commands into a tikzpicture environment
nopicenv = false,
-- produce full LaTeX document?
full_doc = false,
-- in gnuplot all sizes refer to the size of the canvas
-- and not the size of plot itself
plotsize_x = nil,
plotsize_y = nil,
set_plotsize = false,
-- recalculate the origin of the plot
-- used for moving the origin to the lower left
-- corner...
set_origin = false,
-- list of _linetypes_ of plots that should be drawn as with the \plot
-- command instead of \path
plot_list = {},
-- uses some pdf/ps specials with image function that will only work
-- with pdf/ps generation!
direct_image = true,
-- list of gnuplot variables that should be made available via
-- \gpsetvar{name}{val}
gnuplot_vars = {},
-- if true, the gnuplot arrow will be mapped to TikZ arrow styles by the
-- given angle. E.g. an arrow with the angle `7' will be mapped to `gp arrow 7'
-- style.
tikzarrows = false,
-- if true, cmyk image model will be used for bitmap images
cmykimage = false,
-- output TeX flavor, default is LaTeX
tex_format = 'latex',
-- for regression tests etc. we can turn off the timestamp
notimestamp = false,
-- background color, contains RGB triplet when set
bgcolor = nil,
-- crop to the given canvas size
clip = false,
-- if true, the natural bounding box will be used and 'clip' is ignored
tightboundingbox = false,
-- fontscale
fontscale = nil
}
-- Formats for the various TeX flavors
gfx.format = {}
gfx.format.tex = {
docheader = "\\input "..pgf.STYLE_FILE_BASENAME..".tex\n",
begindocument = "",
enddocument = "\\bye\n",
beforetikzpicture= "", -- standalone only
aftertikzpicture = "", -- standalone only
begintikzpicture = "\\tikzpicture",
endtikzpicture = "\\endtikzpicture",
beginscope = "\\scope",
endscope = "\\endscope",
beforeendtikzpicture = "", -- standalone only
fontsize = ""
}
gfx.format.latex = {
docheader = "\\documentclass["..pgf.DEFAULT_FONT_SIZE.."pt]{article}\n"
.."\\usepackage[T1]{fontenc}\n"
.."\\usepackage{textcomp}\n\n"
.."\\usepackage[utf8x]{inputenc}\n\n"
.."\\usepackage{"..pgf.STYLE_FILE_BASENAME.."}\n"
.."\\pagestyle{empty}\n"
.."\\usepackage[active,tightpage]{preview}\n"
.."\\PreviewEnvironment{tikzpicture}\n"
.."\\setlength\\PreviewBorder{\\gpbboxborder}\n",
begindocument = "\\begin{document}\n",
enddocument = "\\end{document}\n",
beforetikzpicture= "", -- standalone only
aftertikzpicture = "", -- standalone only
begintikzpicture = "\\begin{tikzpicture}",
endtikzpicture = "\\end{tikzpicture}",
beginscope = "\\begin{scope}",
endscope = "\\end{scope}",
beforeendtikzpicture = "", -- standalone only
fontsize = "\\fontsize{%spt}{%spt}\\selectfont"
}
gfx.format.context = {
docheader = "\\usemodule["..pgf.STYLE_FILE_BASENAME.."]\n",
begindocument = "\\starttext\n",
enddocument = "\\stoptext\n",
beforetikzpicture= "\\startTEXpage\n", -- standalone only
aftertikzpicture = "\\stopTEXpage\n", -- standalone only
begintikzpicture = "\\starttikzpicture",
endtikzpicture = "\\stoptikzpicture",
beginscope = "\\startscope",
endscope = "\\stopscope",
beforeendtikzpicture = "\\path[use as bounding box] ([shift={(-\\gpbboxborder,-\\gpbboxborder)}]current bounding box.south west)"
.." rectangle ([shift={(\\gpbboxborder,\\gpbboxborder)}]current bounding box.north east);\n", -- standalone only
fontsize = "\\switchtobodyfont[%spt]"
}
-- within tikzpicture environment or not
gfx.in_picture = false
-- have not determined the plotbox, see the 'plotsize' option
gfx.have_plotbox = false
gfx.current_boundingbox = {
xleft = nil, xright = nil, ytop = nil, ybot = nil
}
-- plot bounding boxes counter
gfx.boundingbox_cnt = 0
gfx.TEXT_ANCHOR = {
["left"] = "gp node left",
["center"] = "gp node center",
["right"] = "gp node right"
}
gfx.HEAD_STR = {"", "->", "<-", "<->"}
-- conversion factors in `cm'
gfx.units = {
[''] = 1, -- default
['cm'] = 1,
['mm'] = 0.1,
['in'] = 2.54,
['inch']= 2.54,
['pt'] = 0.035146, -- Pica Point (72.27pt = 1in)
['pc'] = 0.42176, -- Pica (1 Pica = 1/6 inch)
['bp'] = 0.035278, -- Big Point (72bp = 1in)
['dd'] = 0.0376, -- Didot Point (1cm = 26.6dd)
['cc'] = 0.45113 -- Cicero (1cc = 12 dd)
}
gfx.parse_number_unit = function (str, from, to)
to = to or 'cm'
from = from or 'cm'
local num, unit = string.match(str, '^([%d%.]+)([a-z]*)$')
if unit and (string.len(unit) > 0) then
from = unit
else
unit = false
end
local factor_from = gfx.units[from]
local factor_to = gfx.units[to]
num = tonumber(num)
if num and factor_from then
-- to cm and then to our target unit
return num*(factor_from/factor_to), unit
else
return false, false
end
end
gfx.parse_font_string = function (str)
local size,rets,toks = nil, str, explode(',', str)
-- if at least two tokens
if #toks > 1 then
-- add first element to font string
rets = table.remove(toks,1)
-- no unit means 'pt'
size, _ = gfx.parse_number_unit(toks[1],'pt','pt')
if (size) then
table.remove(toks,1)
rets = rets .. string.format(gfx.format[gfx.opt.tex_format].fontsize,size,size*1.2)
end
-- add grouping braces for the font settings
if #rets > 0 then
rets = "{" .. rets .. "}"
end
-- add remaining parts
for k,v in ipairs(toks) do
rets = rets .. ',' .. v
end
else
if #rets > 0 then
rets = "{" .. rets .. "}"
end
end
return rets, size
end
gfx.write_boundingbox = function()
local t = gp.get_boundingbox()
for k, v in pairs (t) do
if v ~= gfx.current_boundingbox[k] then
gfx.boundingbox_cnt = gfx.boundingbox_cnt + 1
gfx.current_boundingbox = t
pgf.write_boundingbox(t, gfx.boundingbox_cnt)
break
end
end
end
gfx.adjust_plotbox = function()
local t = gp.get_boundingbox()
if gfx.opt.set_origin then
-- move origin to the lower left corner of the plot
gfx.origin_xoffset = - t.xleft
gfx.origin_yoffset = - t.ybot
end
if gfx.opt.set_plotsize then
if (t.xright - t.xleft) > 0 then
gfx.scalex = gfx.scalex*gfx.opt.plotsize_x * pgf.DEFAULT_RESOLUTION/(t.xright - t.xleft)
gfx.scaley = gfx.scaley*gfx.opt.plotsize_y * pgf.DEFAULT_RESOLUTION/(t.ytop - t.ybot)
else
-- could not determin a valid bounding box, so keep using the
-- plotsize as the canvas size
gp.term_out("WARNING: PGF/TikZ Terminal: `plotsize' option used, but I could not determin the plot area!\n")
end
elseif not gfx.opt.tightboundingbox then
if gfx.opt.clip then
gp.write("\\clip")
else
gp.write("\\path")
end
gp.write(" (" .. pgf.format_coord(0,0) ..") rectangle (" .. pgf.format_coord(term.xmax, term.ymax) .. ");\n")
end
end
gfx.check_variables = function()
local vl = gfx.opt.gnuplot_vars
local t = gp.get_all_variables()
local sl = {}
for i=1,#vl do
if t[vl[i]] then
sl[vl[i]] = t[vl[i]][3]
if t[vl[i]][4] then
sl[vl[i].." Im"] = t[vl[i]][4]
end
end
end
pgf.write_variables(sl)
end
-- check if the current path should be drawn
gfx.check_in_path = function()
-- also check the bounding box here
-- bounding box data is available with the first drawing command
if (not gfx.have_plotbox) and gfx.in_picture then
gfx.adjust_plotbox()
gfx.have_plotbox = true
end
-- ignore zero length paths
if #gfx.path > 1 then
-- check all line properties and draw current path
gfx.check_color()
gfx.check_linetype()
gfx.check_linewidth()
pgf.draw_path(gfx.path)
-- remember last coordinates
gfx.start_path(gfx.path[#gfx.path][1], gfx.path[#gfx.path][2])
end
end
-- did the linetype change?
gfx.check_linetype = function()
if gfx.linetype_idx ~= gfx.linetype_idx_set then
local lt
if gfx.linetype_idx < 0 then
lt = pgf.styles.linetypes_axes[math.abs(gfx.linetype_idx)][1]
else
lt = pgf.styles.linetypes[(gfx.linetype_idx % #pgf.styles.linetypes)+1][1]
end
pgf.set_linetype(lt)
gfx.linetype_idx_set = gfx.linetype_idx
end
end
-- did the color change?
gfx.check_color = function()
if gfx.color_set ~= gfx.color then
pgf.set_color(gfx.color)
gfx.color_set = gfx.color
end
end
-- sanity check if we already are at this position in our path
-- and save this position
gfx.check_coord = function(x, y)
if (x == gfx.posx) and (y == gfx.posy) then
return true
end
gfx.posx = x
gfx.posy = y
return false
end
-- did the linewidth change?
gfx.check_linewidth = function()
if gfx.linewidth ~= gfx.linewidth_set then
pgf.set_linewidth(gfx.linewidth)
gfx.linewidth_set = gfx.linewidth
end
end
-- did the pointsize change?
gfx.check_pointsize = function()
if gfx.pointsize ~= gfx.pointsize_set then
pgf.set_pointsize(gfx.pointsize)
gfx.pointsize_set = gfx.pointsize
end
end
gfx.start_path = function(x, y)
-- init path with first coords
gfx.path = {{x,y}}
gfx.posx = x
gfx.posy = y
end
-- ctype string LT|RGB|GRAY
-- val table {name}|{r,g,b}
gfx.format_color = function(ctype, val)
local c
if ctype == 'LT' then
if val[1] < 0 then
if val[1] < -2 then -- LT_NODRAW, LT_BACKGROUND, LT_UNDEFINED
c = 'color=gpbgfillcolor'
else
c = 'color='..pgf.styles.lt_colors_axes[math.abs(val[1])][1]
end
else
c = 'color='..pgf.styles.lt_colors[(val[1] % #pgf.styles.lt_colors)+1][1]
end
-- c = pgf.styles.lt_colors[((val[1]+3) % #pgf.styles.lt_colors) + 1][1]
elseif ctype == 'RGB' then
c = string.format("rgb color={%.3f,%.3f,%.3f}", val[1], val[2], val[3])
elseif ctype == 'RGBA' then
c = string.format("rgb color={%.3f,%.3f,%.3f},opacity=%.3f", val[1], val[2], val[3], val[4])
elseif ctype == 'GRAY' then
c = string.format("color=black!%i", 100*val[1]+0.5)
end
return c
end
gfx.set_color = function(ctype, val)
gfx.color = gfx.format_color(ctype, val)
end
--[[===============================================================================================
The terminal layer
The term.* functions are usually called from the gnuplot Lua terminal
]]--===============================================================================================
if arg then
-- when called from the command line we have
-- to initialize the table `term' manually
-- to avoid errors
term = {}
else
--
-- gnuplot terminal default parameters and flags
--
term.xmax = pgf.DEFAULT_RESOLUTION * pgf.DEFAULT_CANVAS_SIZE_X
term.ymax = pgf.DEFAULT_RESOLUTION * pgf.DEFAULT_CANVAS_SIZE_Y
term.h_tic = pgf.DEFAULT_RESOLUTION * pgf.DEFAULT_TIC_SIZE
term.v_tic = pgf.DEFAULT_RESOLUTION * pgf.DEFAULT_TIC_SIZE
-- default size for CM@10pt
term.h_char = math.floor(pgf.DEFAULT_FONT_H_CHAR * (pgf.DEFAULT_FONT_SIZE/10) * (pgf.DEFAULT_RESOLUTION/1000) + .5)
term.v_char = math.floor(pgf.DEFAULT_FONT_V_CHAR * (pgf.DEFAULT_FONT_SIZE/10) * (pgf.DEFAULT_RESOLUTION/1000) + .5)
term.description = "Lua PGF/TikZ terminal for TeX and friends"
term_default_flags = term.TERM_BINARY + term.TERM_CAN_MULTIPLOT + term.TERM_CAN_DASH + term.TERM_ALPHA_CHANNEL
+ term.TERM_LINEWIDTH + term.TERM_IS_LATEX + term.TERM_FONTSCALE
term.flags = term_default_flags + term.TERM_CAN_CLIP
end
--
-- initial = 1 for the initial "set term" call
-- 0 for subsequent option changes -- currently unused, since the changeable options
-- are hardcoded within gnuplot :-(
--
-- t_count see e.g. int_error()
--
term.options = function(opt_str, initial, t_count)
local o_next = ""
local o_type = nil
local s_start, s_end = 1, 1
local term_opt = ""
local term_opt_font, term_opt_size, term_opt_background, term_opt_fontscale, term_opt_scale, term_opt_preamble = "", "", "", "", "", ""
local charsize_h, charsize_v, fontsize, fontscale = nil, nil, nil, nil
-- trim spaces
opt_str = opt_str:gsub("^%s*(.-)%s*$", "%1")
local opt_len = string.len(opt_str)
t_count = t_count - 1
local set_t_count = function(num)
-- gnuplot handles commas as regular tokens
t_count = t_count + 2*num - 2
end
local almost_equals = function(param, opt)
local op1, op2
local st, _ = string.find(opt, "$", 2, true)
if st then
op1 = string.sub(opt, 1, st-1)
op2 = string.sub(opt, st+1)
if (string.sub(param, 1, st-1) == op1)
and (string.find(op1..op2, param, 1, true) == 1) then
return true
end
elseif opt == param then
return true
end
return false
end
--
-- simple parser for options and strings
--
local get_next_token = function()
-- beyond the limit?
if s_start > opt_len then
o_next = ""
o_type = nil
return
end
t_count = t_count + 1
-- search the start of the next token
s_start, _ = string.find (opt_str, '[^%s]', s_start)
if not s_start then
o_next = ""
o_type = nil
return
end
-- a new string argument?
local next_char = string.sub(opt_str, s_start, s_start)
if next_char == '"' or next_char == "'" then
-- find the end of the string by searching for
-- the next not escaped quote
_ , s_end = string.find (opt_str, '[^\\]'..next_char, s_start+1)
if s_end then
o_next = string.sub(opt_str, s_start+1, s_end-1)
if next_char == '"' then
-- Wow! this is to resolve all string escapes, kind of "unescape string"
o_next = assert(loadstring("return(\""..o_next.."\")"))()
end
o_type = "string"
else
-- FIXME: error: string does not end...
-- seems that gnuplot adds missing quotes
-- so this will never happen...
end
else
-- ok, it's not a string...
-- then find the next white space or end of line
-- comma separated strings are regarded as one token
s_end, _ = string.find (opt_str, '[^,][%s]+[^,]', s_start)
if not s_end then -- reached the end of the string
s_end = opt_len + 1
else
s_end = s_end + 1
end
o_next = string.sub(opt_str, s_start, s_end-1)
if tonumber(o_next) ~= nil then
o_type = 'number'
else
o_type = "op"
end
end
s_start = s_end + 1
return
end
local get_two_sizes = function(str)
local args = explode(',', str)
set_t_count(#args)
local num1, num2, unit
if #args ~= 2 then
return false, nil
else
num1, unit = gfx.parse_number_unit(args[1])
if unit then
t_count = t_count + 1
end
num2, unit = gfx.parse_number_unit(args[2])
if unit then
t_count = t_count + 1
end
if not (num1 and num2) then
return false, nil
end
end
return num1, num2
end
local print_help = false
while true do
get_next_token()
if not o_type then break end
if almost_equals(o_next, "he$lp") then
print_help = true
elseif almost_equals(o_next, "mono$chrome") then
-- no colored lines
-- Setting `term.TERM_MONOCHROME' would internally disable colors for all drawings.
-- We do it the `soft' way by redefining all colors via a TeX command.
-- Maybe an additional terminal option is useful here...
gfx.opt.lines_colored = false
elseif almost_equals(o_next, "c$olor") or almost_equals(o_next, "c$olour") then
-- colored lines
gfx.opt.lines_colored = true
elseif almost_equals(o_next, "so$lid") then
-- no dashed and dotted etc. lines
gfx.opt.lines_dashed = false
elseif almost_equals(o_next, "notime$stamp") then
-- omit output of the timestamp
gfx.opt.notimestamp = true
elseif almost_equals(o_next, "da$shed") then
-- dashed and dotted etc. lines
gfx.opt.lines_dashed = true
elseif almost_equals(o_next, "gparr$ows") then
-- use gnuplot arrows instead of TikZ
gfx.opt.gp_arrows = true
elseif almost_equals(o_next, "nogparr$ows") then
-- use gnuplot arrows instead of TikZ
gfx.opt.gp_arrows = false
elseif almost_equals(o_next, "gppoint$s") then
-- use gnuplot points instead of TikZ
gfx.opt.gp_points = true
elseif almost_equals(o_next, "nogppoint$s") then
-- use gnuplot points instead of TikZ
gfx.opt.gp_points = false
elseif almost_equals(o_next, "nopic$environment") then
-- omit the 'tikzpicture' environment
gfx.opt.nopicenv = true
elseif almost_equals(o_next, "pic$environment") then
-- omit the 'tikzpicture' environment
gfx.opt.nopicenv = false
elseif almost_equals(o_next, "origin$reset") then
-- moves the origin of the TikZ picture to the lower left corner of the plot
gfx.opt.set_origin = true
elseif almost_equals(o_next, "noorigin$reset") then
-- moves the origin of the TikZ picture to the lower left corner of the plot
gfx.opt.set_origin = false
elseif almost_equals(o_next, "plot$size") then
get_next_token()
gfx.opt.plotsize_x, gfx.opt.plotsize_y = get_two_sizes(o_next)
if not gfx.opt.plotsize_x then
gp.int_error(t_count, string.format("error: two comma seperated lengths expected, got `%s'.", o_next))
end
gfx.opt.set_plotsize = true
term_opt_size = string.format("plotsize %s,%s ", gfx.opt.plotsize_x, gfx.opt.plotsize_y)
-- we set the canvas size to the plotsize to keep the aspect ratio as good as possible
-- and rescale later once we know the actual plot size...
term.xmax = gfx.opt.plotsize_x*pgf.DEFAULT_RESOLUTION
term.ymax = gfx.opt.plotsize_y*pgf.DEFAULT_RESOLUTION
elseif almost_equals(o_next, "si$ze") then
get_next_token()
local plotsize_x, plotsize_y = get_two_sizes(o_next)
if not plotsize_x then
gp.int_error(t_count, string.format("error: two comma seperated lengths expected, got `%s'.", o_next))
end
gfx.opt.set_plotsize = false
term_opt_size = string.format("size %s,%s ", plotsize_x, plotsize_y)
term.xmax = plotsize_x*pgf.DEFAULT_RESOLUTION
term.ymax = plotsize_y*pgf.DEFAULT_RESOLUTION
elseif almost_equals(o_next, "char$size") then
get_next_token()
charsize_h, charsize_v = get_two_sizes(o_next)
if not charsize_h then
gp.int_error(t_count, string.format("error: two comma seperated lengths expected, got `%s'.", o_next))
end
elseif almost_equals(o_next, "sc$ale") then
get_next_token()
local xscale, yscale = get_two_sizes(o_next)
if not xscale then
gp.int_error(t_count, string.format("error: two comma seperated numbers expected, got `%s'.", o_next))
end
term_opt_scale = string.format("scale %s,%s ",xscale, yscale)
term.xmax = term.xmax * xscale
term.ymax = term.ymax * yscale
elseif almost_equals(o_next, "tikzpl$ot") then
get_next_token()
local args = explode(',', o_next)
set_t_count(#args)
for i = 1,#args do
args[i] = tonumber(args[i])
if args[i] == nil then
gp.int_error(t_count, string.format("error: list of comma seperated numbers expected, got `%s'.", o_next))
end
args[i] = args[i] - 1
end
gfx.opt.plot_list = args
elseif almost_equals(o_next, "provide$vars") then
get_next_token()
local args = explode(',', o_next)
set_t_count(#args)
gfx.opt.gnuplot_vars = args
elseif almost_equals(o_next, "tikzar$rows") then
-- map the arrow angles to TikZ arrow styles
gfx.opt.tikzarrows = true
elseif almost_equals(o_next, "notikzar$rows") then
-- don't map the arrow angles to TikZ arrow styles
gfx.opt.tikzarrows = false
elseif almost_equals(o_next, "nobit$map") then
-- render images as filled rectangles instead of the nativ
-- PS or PDF image format
gfx.opt.direct_image = false
elseif almost_equals(o_next, "bit$map") then
-- render images as nativ PS or PDF image
gfx.opt.direct_image = true
elseif almost_equals(o_next, "cmyk$image") then
-- use cmyk color model for images
gfx.opt.cmykimage = true
elseif almost_equals(o_next, "rgb$image") then
-- use cmyk color model for images
gfx.opt.cmykimage = false
elseif almost_equals(o_next, "full$doc") or almost_equals(o_next, "stand$alone") then
-- produce full tex document
gfx.opt.full_doc = true
elseif almost_equals(o_next, "nofull$doc") or almost_equals(o_next, "nostand$alone") then
-- produce full tex document
gfx.opt.full_doc = true
elseif almost_equals(o_next, "create$style") then
-- creates the coresponding LaTeX style from the script
pgf.create_style()
elseif almost_equals(o_next, "backg$round") then
-- set background color
get_next_token()
-- ignore rgbcolor keyword if present
if almost_equals(o_next, "rgb$color") then get_next_token() end
if o_type == 'string' then
gfx.opt.bgcolor = gp.parse_color_name(t_count, o_next)
term_opt_background = string.format("background '%s'", o_next)
else
gp.int_error(t_count, string.format("error: string expected, got `%s'.", o_next))
end
elseif almost_equals(o_next, "fo$nt") then
get_next_token()
if o_type == 'string' then
gfx.opt.default_font, fontsize = gfx.parse_font_string(o_next)
else
gp.int_error(t_count, string.format("error: string expected, got `%s'.", o_next))
end
term_opt_font = string.format("font %q ", o_next)
elseif almost_equals(o_next, "fonts$cale") or almost_equals(o_next, "texts$cale") then
get_next_token()
if o_type == 'number' then
fontscale = tonumber(o_next)
if fontscale < 0 then
fontscale = 1.0
end
else
gp.int_error(t_count, string.format("error: number expected, got `%s'.", o_next))
end
elseif almost_equals(o_next, "externalimages") then
if term.external_images ~= nil then
term.external_images = true;
else
gp.int_warn(t_count, "Externalization of images is not supported.")
end
elseif almost_equals(o_next, "noexternalimages") then
if term.external_images ~= nil then
term.external_images = false;
else
gp.int_warn(t_count, "Externalization of images is not supported.")
end
elseif almost_equals(o_next, "pre$amble") or almost_equals(o_next, "header") then
get_next_token()
if o_type == 'string' then
term_opt_preamble = term_opt_preamble .. string.format("preamble %q ", o_next)
gfx.opt.latex_preamble = gfx.opt.latex_preamble .. o_next .. "\n"
else
gp.int_error(t_count, string.format("error: string expected, got `%s'.", o_next))
end
elseif almost_equals(o_next, "nopre$amble") or almost_equals(o_next, "noheader") then
gfx.opt.latex_preamble = ''
elseif almost_equals(o_next, "con$text") then
gfx.opt.tex_format = "context"
-- ConTeXt has a default of 12pt
fontsize = 12
elseif almost_equals(o_next, "tex") then
gfx.opt.tex_format = "tex"
elseif almost_equals(o_next, "latex") then
gfx.opt.tex_format = "latex"
elseif almost_equals(o_next, "clip") then
gfx.opt.clip = true
term.flags = term_default_flags
term.flags = term_default_flags + term.TERM_CAN_CLIP
elseif almost_equals(o_next, "noclip") then
gfx.opt.clip = false
term.flags = term_default_flags
elseif almost_equals(o_next, "tight$boundingbox") then
gfx.opt.tightboundingbox = true
elseif almost_equals(o_next, "notight$boundingbox") then
gfx.opt.tightboundingbox = false
else
gp.int_warn(t_count, string.format("unknown option `%s'.", o_next))
end
end
-- determine "internal" font size
-- FIXME: what happens on "set termoptions font ..." or subsequent terminal calls
local term_h_char, term_v_char = term.h_char, term.v_char
if fontsize ~= nil then
term_h_char = pgf.DEFAULT_FONT_H_CHAR * (fontsize/10) * (pgf.DEFAULT_RESOLUTION/1000)
term_v_char = pgf.DEFAULT_FONT_V_CHAR * (fontsize/10) * (pgf.DEFAULT_RESOLUTION/1000)
-- on change apply old text scaling
if not fontscale then
fontscale = gfx.opt.fontscale;
end
end
-- a given character size overwrites font size
if charsize_h ~= nil then
term_h_char = charsize_h*pgf.DEFAULT_RESOLUTION
term_v_char = charsize_v*pgf.DEFAULT_RESOLUTION
-- on change apply old text scaling
if not fontscale then
fontscale = gfx.opt.fontscale;
end
end
if fontscale ~= nil then
term_h_char = term_h_char * fontscale
term_v_char = term_v_char * fontscale
gfx.opt.fontscale = fontscale;
term_opt_fontscale = string.format("fontscale %s", gfx.opt.fontscale)
end
term.h_char = math.floor(term_h_char + .5)
term.v_char = math.floor(term_v_char + .5)
if print_help then
pgf.print_help(gp.term_out)
end
local tf = function(b,y,n)
local addopt = ''
if b then
addopt = y
else
addopt = n
end
if (string.len(addopt) > 0) then
term_opt = term_opt .. addopt .. ' '
end
end
tf(true, gfx.opt.tex_format, nil)
tf(true, term_opt_font, nil)
tf(true, term_opt_size, nil)
tf(true, term_opt_background, nil)
tf(true, term_opt_fontscale, nil)
tf((#gfx.opt.latex_preamble>0), term_opt_preamble, 'nopreamble')
tf(gfx.opt.lines_colored, 'color', 'monochrome')
tf(gfx.opt.full_doc, 'standalone', 'nostandalone')
tf(gfx.opt.lines_dashed, 'dashed', 'solid')
tf(gfx.opt.gp_arrows, 'gparrows', 'nogparrows')
tf(gfx.opt.tikzarrows, 'tikzarrows', 'notikzarrows')
tf(gfx.opt.gp_points, 'gppoints', 'nogppoints')
tf(gfx.opt.nopicenv, 'nopicenvironment', 'picenvironment')
tf(gfx.opt.set_origin, 'originreset', 'nooriginreset')
tf(gfx.opt.direct_image, 'bitmap', 'nobitmap')
tf(gfx.opt.cmykimage, 'cmykimage', 'rgbimage')
tf(gfx.opt.clip, 'clip', 'noclip')
tf(gfx.opt.tightboundingbox, 'tightboundingbox', 'notightboundingbox')
if term.external_images ~= nil then
tf(term.external_images, 'externalimages', 'noexternalimages')
end
gp.term_options(term_opt)
return 1
end
-- Called once, when the device is first selected.
term.init = function()
if gfx.opt.full_doc then
pgf.write_doc_begin(gfx.opt.latex_preamble)
end
return 1
end
-- Called just before a plot is going to be displayed.
term.graphics = function()
-- reset some state variables
gfx.linetype_idx_set = nil
gfx.linewidth_set = nil
gfx.pointsize_set = nil
gfx.color_set = nil
gfx.in_picture = true
gfx.have_plotbox = false
gfx.boundingbox_cnt = 0
gfx.scalex = 1/pgf.DEFAULT_RESOLUTION
gfx.scaley = 1/pgf.DEFAULT_RESOLUTION
gfx.current_boundingbox = {
xleft = nil, xright = nil, ytop = nil, ybot = nil
}
-- put a newline between subsequent plots in fulldoc mode...
if gfx.opt.full_doc then
gp.write("\n")
end
pgf.write_graph_begin(gfx.opt.default_font, gfx.opt.nopicenv)
return 1
end
term.vector = function(x, y)
if #gfx.path == 0 then
gfx.start_path(gfx.posx, gfx.posy)
elseif not gfx.check_coord(x, y) then
-- checked for zero path length and add the path coords to gfx.path
gfx.path[#gfx.path+1] = {x,y}
end
return 1
end
term.move = function(x, y)
-- only "move" if we change our latest position
if not gfx.check_coord(x, y) then
-- finish old path and start a new one
gfx.check_in_path()
gfx.start_path(x, y)
end
return 1
end
term.linetype = function(ltype)
gfx.check_in_path()
gfx.set_color('LT', {ltype})
if (ltype < -2) then -- LT_NODRAW, LT_BACKGROUND, LT_UNDEFINED
ltype = -2
end
gfx.linetype_idx = ltype
return 1
end
term.point = function(x, y, num)
if gfx.opt.gp_points then
return 0
else
gfx.check_in_path()
gfx.check_color()
gfx.check_linewidth()
gfx.check_pointsize()
local pm
if num == -1 then
pm = pgf.styles.plotmarks[1][1]
else
pm = pgf.styles.plotmarks[(num % (#pgf.styles.plotmarks-1)) + 2][1]
end
pgf.draw_points({{x,y}}, pm)
return 1
end
end
--[[
this differs from the original API
one may use the additional parameters to define own styles
e.g. "misuse" angle for numbering predefined styles...
int length /* head length */
double angle /* head angle in degrees */
double backangle /* head back angle in degrees */
int filled /* arrow head filled or not */
]]
term.arrow = function(sx, sy, ex, ey, head, length, angle, backangle, filled)
if gfx.opt.gp_arrows then
return 0
else
local headstyle = 0
if gfx.opt.tikzarrows then
headstyle = angle
end
gfx.check_in_path()
gfx.check_color()
gfx.check_linetype()
gfx.check_linewidth()
pgf.draw_arrow({{sx,sy},{ex,ey}}, gfx.HEAD_STR[head+1], headstyle)
return 1
end
end
-- Called immediately after a plot is displayed.
term.text = function()
gfx.check_in_path()
pgf.write_graph_end(gfx.opt.nopicenv)
gfx.in_picture = false
return 1
end
term.put_text = function(x, y, txt)
gfx.check_in_path()
gfx.check_color()
if (txt ~= '') or (gfx.text_font ~= '') then -- omit empty nodes
pgf.write_text_node({x, y}, txt, gfx.text_angle, gfx.TEXT_ANCHOR[gfx.text_justify], gfx.text_font)
end
return 1
end
term.justify_text = function(justify)
gfx.text_justify = justify
return 1
end
term.text_angle = function(ang)
gfx.text_angle = ang
return 1
end
term.linewidth = function(width)
if gfx.linewidth ~= width then
gfx.check_in_path()
gfx.linewidth = width
end
return 1
end
term.pointsize = function(size)
if gfx.pointsize ~= size then
gfx.check_in_path()
gfx.pointsize = size
end
return 1
end
term.set_font = function(font)
gfx.text_font = gfx.parse_font_string(font)
return 1
end
-- at the moment this is only used to check
-- the plot's bounding box as seldom as possible
term.layer = function(l)
if l == 'end_text' then
-- called after a plot is finished (also after each "mutiplot")
gfx.write_boundingbox()
end
return 1
end
-- we don't use this, because we are implicitly testing
-- for closed paths
term.path = function(p)
return 1
end
term.filled_polygon = function(style, fillpar, t)
local pattern = nil
local color = nil
local opacity = 100
local saturation = 100
gfx.check_in_path()
if style == 'EMPTY' then
-- FIXME: should be the "background color" and not gpbgfillcolor
pattern = ''
color = 'gpbgfillcolor'
saturation = 100
opacity = 100
elseif style == 'DEFAULT' or style == 'OPAQUE' then -- FIXME: not shure about the opaque style
pattern = ''
color = gfx.color
saturation = 100
opacity = 100
elseif style == 'SOLID' then
pattern = ''
color = gfx.color
if fillpar < 100 then
saturation = fillpar
else
saturation = 100
end
opacity = 100
elseif style == 'PATTERN' then
pattern = pgf.styles.patterns[(fillpar % #pgf.styles.patterns) + 1][1]
color = gfx.color
saturation = 100
opacity = 100
elseif style == 'TRANSPARENT_SOLID' then
pattern = ''
color = gfx.color
saturation = 100
opacity = fillpar
elseif style == 'TRANSPARENT_PATTERN' then
pattern = pgf.styles.patterns[(fillpar % #pgf.styles.patterns) + 1][1]
color = gfx.color
saturation = 100
opacity = 0
end
pgf.draw_fill(t, pattern, color, saturation, opacity)
return 1
end
term.boxfill = function(style, fillpar, x1, y1, width, height)
local t = {{x1, y1}, {x1+width, y1}, {x1+width, y1+height}, {x1, y1+height}}
return term.filled_polygon(style, fillpar, t)
end
-- points[row][column]
-- m: #cols, n: #rows
-- corners: clip box and draw box coordinates
-- ctype: "RGB" or "RGBA" or "PALETTE"
term.image = function(m, n, points, corners, ctype, xfile)
gfx.check_in_path()
pgf.write_clipbox_begin({corners[3][1],corners[3][2]},{corners[4][1],corners[4][2]})
local ll = {corners[1][1],corners[2][2]}
local ur = {corners[2][1],corners[1][2]}
local xxfile
if xfile ~= nil then
-- strip file extension
xxfile = string.match(xfile, "^(.*).png$")
else
xxfile = ""
end
-- load exclusively an external file and don't generate inline images
if xfile ~= nil and term.external_images == true then
pgf.load_image_file(ll, ur, xxfile)
elseif gfx.opt.direct_image then
if gfx.opt.cmykimage then
pgf.draw_raw_cmyk_image(points, m, n, ll, ur, xxfile)
else
pgf.draw_raw_rgb_image(points, m, n, ll, ur, xxfile)
end
else
-- draw as filled squares
local w = (corners[2][1] - corners[1][1])/m
local h = (corners[1][2] - corners[2][2])/n
local yy,yyy,xx,xxx
for cnt = 1,#points do
xx = corners[1][1]+(cnt%m-1)*w
yy = corners[1][2]-math.floor(cnt/m)*h
yyy = yy-h
xxx = xx+w
pgf.draw_fill({{xx, yy}, {xxx, yy}, {xxx, yyy}, {xx, yyy}}, '', gfx.format_color(ctype, points[cnt]) , 100, 100)
end
end
pgf.write_clipbox_end()
end
term.make_palette = function()
-- continuous number of colours
return 0
end
term.previous_palette = function()
return 1
end
term.set_color = function(ctype, lt, value, r, g, b)
gfx.check_in_path()
-- FIXME gryscale on monochrome?? ... or use xcolor?
if ctype == 'LT' then
gfx.set_color('LT', {lt})
elseif ctype == 'FRAC' then
if gfx.opt.lines_colored then
gfx.set_color('RGB', {r, g , b})
else
gfx.set_color('GRAY', {value})
end
elseif ctype == 'RGB' then
gfx.set_color('RGB', {r, g , b})
else
gp.int_error(string.format("set color: unknown type (%s), lt (%i), value (%.3f)\n", ctype, lt, value))
end
return 1
end
-- Called when gnuplot is exited.
term.reset = function(p)
gfx.check_in_path()
gfx.check_variables()
if gfx.opt.full_doc then
pgf.write_doc_end()
end
return 1
end
--[[===============================================================================================
command line code
]]--===============================================================================================
term_help = function(helptext)
local w
for w in string.gmatch(helptext, "([^\n]*)\n") do
w = string.gsub(w, "\\", "\\\\")
w = string.gsub(w, "\"", "\\\"")
io.write('"'..w.."\",\n")
end
--[[
local out = string.gsub(helptext, "\n", "\",\n\"")
local out = string.gsub(helptext, "\n", "\",\n\"")
io.write(out)]]
end
if arg then -- called from the command line!
if #arg > 0 and arg[1] == 'style' then
-- write style file
pgf.create_style()
elseif arg[1] == 'termhelp' then
io.write([["2 lua tikz",
"?set terminal lua tikz",
"?set term lua tikz",
"?term lua tikz",
" The TikZ driver is one output mode of the generic Lua terminal.",
"",
" Syntax:",
" set terminal lua tikz",
"",
]])
pgf.print_help(term_help)
io.write("\"\"\n")
else
io.write([[
This script is intended to be called from GNUPLOT.
For generating the associated TeX/LaTeX/ConTeXt style files
just call this script with the additional option 'style':
# lua gnuplot.lua style
The TikZ driver provides the following additional terminal options:
]])
pgf.print_help(io.write)
end
end
| apache-2.0 |
UnluckyNinja/PathOfBuilding | Data/3_0/Bases/body.lua | 1 | 29096 | -- This file is automatically generated, do not edit!
-- Item data (c) Grinding Gear Games
local itemBases = ...
itemBases["Plate Vest"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 19, MovementPenalty = 3, },
req = { str = 12, },
}
itemBases["Chestplate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 68, MovementPenalty = 5, },
req = { level = 6, str = 25, },
}
itemBases["Copper Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 176, MovementPenalty = 5, },
req = { level = 17, str = 53, },
}
itemBases["War Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 216, MovementPenalty = 5, },
req = { level = 21, str = 63, },
}
itemBases["Full Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 284, MovementPenalty = 5, },
req = { level = 28, str = 81, },
}
itemBases["Arena Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 324, MovementPenalty = 5, },
req = { level = 32, str = 91, },
}
itemBases["Lordly Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 353, MovementPenalty = 5, },
req = { level = 35, str = 99, },
}
itemBases["Bronze Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 373, MovementPenalty = 5, },
req = { level = 37, str = 104, },
}
itemBases["Battle Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 412, MovementPenalty = 5, },
req = { level = 41, str = 114, },
}
itemBases["Sun Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 451, MovementPenalty = 5, },
req = { level = 45, str = 124, },
}
itemBases["Colosseum Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 491, MovementPenalty = 5, },
req = { level = 49, str = 134, },
}
itemBases["Majestic Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 530, MovementPenalty = 5, },
req = { level = 53, str = 144, },
}
itemBases["Golden Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 559, MovementPenalty = 5, },
req = { level = 56, str = 152, },
}
itemBases["Crusader Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 601, MovementPenalty = 5, },
req = { level = 59, str = 160, },
}
itemBases["Astral Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
implicit = "+(8-12)% to all Elemental Resistances",
armour = { ArmourBase = 711, MovementPenalty = 5, },
req = { level = 62, str = 180, },
}
itemBases["Gladiator Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 738, MovementPenalty = 5, },
req = { level = 65, str = 177, },
}
itemBases["Glorious Plate"] = {
type = "Body Armour",
subType = "Armour",
tags = { default = true, armour = true, body_armour = true, str_armour = true, },
armour = { ArmourBase = 776, },
req = { level = 68, str = 191, },
}
itemBases["Shabby Jerkin"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 29, MovementPenalty = 3, },
req = { dex = 14, },
}
itemBases["Strapped Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 98, MovementPenalty = 3, },
req = { level = 9, dex = 32, },
}
itemBases["Buckskin Tunic"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 176, MovementPenalty = 3, },
req = { level = 17, dex = 53, },
}
itemBases["Wild Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 255, MovementPenalty = 3, },
req = { level = 25, dex = 73, },
}
itemBases["Full Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 284, MovementPenalty = 3, },
req = { level = 28, dex = 81, },
}
itemBases["Sun Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 324, MovementPenalty = 3, },
req = { level = 32, dex = 91, },
}
itemBases["Thief's Garb"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 353, MovementPenalty = 3, },
req = { level = 35, dex = 99, },
}
itemBases["Eelskin Tunic"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 373, MovementPenalty = 3, },
req = { level = 37, dex = 104, },
}
itemBases["Frontier Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 412, MovementPenalty = 3, },
req = { level = 41, dex = 114, },
}
itemBases["Glorious Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 451, MovementPenalty = 3, },
req = { level = 45, dex = 124, },
}
itemBases["Coronal Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 491, MovementPenalty = 3, },
req = { level = 49, dex = 134, },
}
itemBases["Cutthroat's Garb"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 530, MovementPenalty = 3, },
req = { level = 53, dex = 144, },
}
itemBases["Sharkskin Tunic"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 559, MovementPenalty = 3, },
req = { level = 56, dex = 152, },
}
itemBases["Destiny Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 601, MovementPenalty = 3, },
req = { level = 59, dex = 160, },
}
itemBases["Exquisite Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 704, MovementPenalty = 3, },
req = { level = 62, dex = 170, },
}
itemBases["Zodiac Leather"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
armour = { EvasionBase = 854, MovementPenalty = 3, },
req = { level = 65, dex = 197, },
}
itemBases["Assassin's Garb"] = {
type = "Body Armour",
subType = "Evasion",
tags = { default = true, armour = true, body_armour = true, dex_armour = true, },
implicit = "3% increased Movement Speed",
armour = { EvasionBase = 737, },
req = { level = 68, dex = 183, },
}
itemBases["Simple Robe"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 12, MovementPenalty = 3, },
req = { int = 17, },
}
itemBases["Silken Vest"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 27, MovementPenalty = 3, },
req = { level = 11, int = 37, },
}
itemBases["Scholar's Robe"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 39, MovementPenalty = 3, },
req = { level = 18, int = 55, },
}
itemBases["Silken Garb"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 52, MovementPenalty = 3, },
req = { level = 25, int = 73, },
}
itemBases["Mage's Vestment"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 58, MovementPenalty = 3, },
req = { level = 28, int = 81, },
}
itemBases["Silk Robe"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 65, MovementPenalty = 3, },
req = { level = 32, int = 91, },
}
itemBases["Cabalist Regalia"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 71, MovementPenalty = 3, },
req = { level = 35, int = 99, },
}
itemBases["Sage's Robe"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 74, MovementPenalty = 3, },
req = { level = 37, int = 104, },
}
itemBases["Silken Wrap"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 82, MovementPenalty = 3, },
req = { level = 41, int = 114, },
}
itemBases["Conjurer's Vestment"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 89, MovementPenalty = 3, },
req = { level = 45, int = 124, },
}
itemBases["Spidersilk Robe"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 96, MovementPenalty = 3, },
req = { level = 49, int = 134, },
}
itemBases["Destroyer Regalia"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 104, MovementPenalty = 3, },
req = { level = 53, int = 144, },
}
itemBases["Savant's Robe"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 109, MovementPenalty = 3, },
req = { level = 56, int = 152, },
}
itemBases["Necromancer Silks"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 117, MovementPenalty = 3, },
req = { level = 59, int = 160, },
}
itemBases["Occultist's Vestment"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
implicit = "(3-10)% increased Spell Damage",
armour = { EnergyShieldBase = 130, MovementPenalty = 3, },
req = { level = 62, int = 180, },
}
itemBases["Widowsilk Robe"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 150, MovementPenalty = 3, },
req = { level = 65, int = 187, },
}
itemBases["Vaal Regalia"] = {
type = "Body Armour",
subType = "Energy Shield",
tags = { default = true, armour = true, body_armour = true, int_armour = true, },
armour = { EnergyShieldBase = 163, MovementPenalty = 3, },
req = { level = 68, int = 194, },
}
itemBases["Scale Vest"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 27, EvasionBase = 27, MovementPenalty = 3, },
req = { str = 10, dex = 10, },
}
itemBases["Light Brigandine"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 48, EvasionBase = 48, MovementPenalty = 3, },
req = { level = 8, str = 16, dex = 16, },
}
itemBases["Scale Doublet"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 97, EvasionBase = 97, MovementPenalty = 3, },
req = { level = 17, str = 28, dex = 28, },
}
itemBases["Infantry Brigandine"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 119, EvasionBase = 119, MovementPenalty = 3, },
req = { level = 21, str = 34, dex = 34, },
}
itemBases["Full Scale Armour"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 156, EvasionBase = 156, MovementPenalty = 3, },
req = { level = 28, str = 43, dex = 43, },
}
itemBases["Soldier's Brigandine"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 178, EvasionBase = 178, MovementPenalty = 3, },
req = { level = 32, str = 48, dex = 48, },
}
itemBases["Field Lamellar"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 194, EvasionBase = 194, MovementPenalty = 3, },
req = { level = 35, str = 53, dex = 53, },
}
itemBases["Wyrmscale Doublet"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 210, EvasionBase = 210, MovementPenalty = 3, },
req = { level = 38, str = 57, dex = 57, },
}
itemBases["Hussar Brigandine"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 232, EvasionBase = 232, MovementPenalty = 3, },
req = { level = 42, str = 62, dex = 62, },
}
itemBases["Full Wyrmscale"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 254, EvasionBase = 254, MovementPenalty = 3, },
req = { level = 46, str = 68, dex = 68, },
}
itemBases["Commander's Brigandine"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 275, EvasionBase = 275, MovementPenalty = 3, },
req = { level = 50, str = 73, dex = 73, },
}
itemBases["Battle Lamellar"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 297, EvasionBase = 297, MovementPenalty = 3, },
req = { level = 54, str = 79, dex = 79, },
}
itemBases["Dragonscale Doublet"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 313, EvasionBase = 313, MovementPenalty = 3, },
req = { level = 57, str = 83, dex = 83, },
}
itemBases["Desert Brigandine"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 376, EvasionBase = 376, MovementPenalty = 3, },
req = { level = 60, str = 96, dex = 96, },
}
itemBases["Full Dragonscale"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 470, EvasionBase = 373, MovementPenalty = 3, },
req = { level = 63, str = 115, dex = 94, },
}
itemBases["General's Brigandine"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 415, EvasionBase = 415, MovementPenalty = 3, },
req = { level = 66, str = 103, dex = 103, },
}
itemBases["Triumphant Lamellar"] = {
type = "Body Armour",
subType = "Armour/Evasion",
tags = { default = true, armour = true, body_armour = true, str_dex_armour = true, },
armour = { ArmourBase = 380, EvasionBase = 477, MovementPenalty = 3, },
req = { level = 69, str = 95, dex = 116, },
}
itemBases["Chainmail Vest"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 27, EnergyShieldBase = 8, MovementPenalty = 5, },
req = { str = 10, int = 10, },
}
itemBases["Chainmail Tunic"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 48, EnergyShieldBase = 12, MovementPenalty = 5, },
req = { level = 8, str = 16, int = 16, },
}
itemBases["Ringmail Coat"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 97, EnergyShieldBase = 21, MovementPenalty = 5, },
req = { level = 17, str = 28, int = 28, },
}
itemBases["Chainmail Doublet"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 119, EnergyShieldBase = 25, MovementPenalty = 5, },
req = { level = 21, str = 34, int = 34, },
}
itemBases["Full Ringmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 156, EnergyShieldBase = 32, MovementPenalty = 5, },
req = { level = 28, str = 43, int = 43, },
}
itemBases["Full Chainmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 178, EnergyShieldBase = 36, MovementPenalty = 5, },
req = { level = 32, str = 48, int = 48, },
}
itemBases["Holy Chainmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 194, EnergyShieldBase = 39, MovementPenalty = 5, },
req = { level = 35, str = 53, int = 53, },
}
itemBases["Latticed Ringmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 216, EnergyShieldBase = 43, MovementPenalty = 5, },
req = { level = 39, str = 59, int = 59, },
}
itemBases["Crusader Chainmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 237, EnergyShieldBase = 47, MovementPenalty = 5, },
req = { level = 43, str = 64, int = 64, },
}
itemBases["Ornate Ringmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 259, EnergyShieldBase = 51, MovementPenalty = 5, },
req = { level = 47, str = 69, int = 69, },
}
itemBases["Chain Hauberk"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 281, EnergyShieldBase = 55, MovementPenalty = 5, },
req = { level = 51, str = 75, int = 75, },
}
itemBases["Devout Chainmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 302, EnergyShieldBase = 59, MovementPenalty = 5, },
req = { level = 55, str = 80, int = 80, },
}
itemBases["Loricated Ringmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 325, EnergyShieldBase = 63, MovementPenalty = 5, },
req = { level = 58, str = 84, int = 84, },
}
itemBases["Conquest Chainmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 387, EnergyShieldBase = 75, MovementPenalty = 5, },
req = { level = 61, str = 96, int = 96, },
}
itemBases["Elegant Ringmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 377, EnergyShieldBase = 87, MovementPenalty = 5, },
req = { level = 64, str = 90, int = 105, },
}
itemBases["Saint's Hauberk"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 443, EnergyShieldBase = 73, MovementPenalty = 5, },
req = { level = 67, str = 109, int = 94, },
}
itemBases["Saintly Chainmail"] = {
type = "Body Armour",
subType = "Armour/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_int_armour = true, },
armour = { ArmourBase = 401, EnergyShieldBase = 91, MovementPenalty = 5, },
req = { level = 70, str = 99, int = 115, },
}
itemBases["Padded Vest"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 27, EnergyShieldBase = 8, MovementPenalty = 3, },
req = { dex = 10, int = 10, },
}
itemBases["Oiled Vest"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 54, EnergyShieldBase = 13, MovementPenalty = 3, },
req = { level = 9, dex = 17, int = 17, },
}
itemBases["Padded Jacket"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 102, EnergyShieldBase = 22, MovementPenalty = 3, },
req = { level = 18, dex = 30, int = 30, },
}
itemBases["Oiled Coat"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 124, EnergyShieldBase = 26, MovementPenalty = 3, },
req = { level = 22, dex = 35, int = 35, },
}
itemBases["Scarlet Raiment"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 156, EnergyShieldBase = 32, MovementPenalty = 3, },
req = { level = 28, dex = 43, int = 43, },
}
itemBases["Waxed Garb"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 178, EnergyShieldBase = 36, MovementPenalty = 3, },
req = { level = 32, dex = 48, int = 48, },
}
itemBases["Bone Armour"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 194, EnergyShieldBase = 39, MovementPenalty = 3, },
req = { level = 35, dex = 53, int = 53, },
}
itemBases["Quilted Jacket"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 221, EnergyShieldBase = 44, MovementPenalty = 3, },
req = { level = 40, dex = 60, int = 60, },
}
itemBases["Sleek Coat"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 243, EnergyShieldBase = 48, MovementPenalty = 3, },
req = { level = 44, dex = 65, int = 65, },
}
itemBases["Crimson Raiment"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 264, EnergyShieldBase = 52, MovementPenalty = 3, },
req = { level = 48, dex = 71, int = 71, },
}
itemBases["Lacquered Garb"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 286, EnergyShieldBase = 56, MovementPenalty = 3, },
req = { level = 52, dex = 76, int = 76, },
}
itemBases["Crypt Armour"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 308, EnergyShieldBase = 60, MovementPenalty = 3, },
req = { level = 56, dex = 82, int = 82, },
}
itemBases["Sentinel Jacket"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 330, EnergyShieldBase = 64, MovementPenalty = 3, },
req = { level = 59, dex = 86, int = 86, },
}
itemBases["Varnished Coat"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 387, EnergyShieldBase = 75, MovementPenalty = 3, },
req = { level = 62, dex = 96, int = 96, },
}
itemBases["Blood Raiment"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 436, EnergyShieldBase = 70, MovementPenalty = 3, },
req = { level = 65, dex = 107, int = 90, },
}
itemBases["Sadist Garb"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
armour = { EvasionBase = 427, EnergyShieldBase = 88, MovementPenalty = 3, },
req = { level = 68, dex = 103, int = 109, },
}
itemBases["Carnal Armour"] = {
type = "Body Armour",
subType = "Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, dex_int_armour = true, },
implicit = "+(20-25) to maximum Mana",
armour = { EvasionBase = 353, EnergyShieldBase = 98, MovementPenalty = 3, },
req = { level = 71, dex = 88, int = 122, },
}
itemBases["Sacrificial Garb"] = {
type = "Body Armour",
subType = "Armour/Evasion/Energy Shield",
tags = { default = true, armour = true, body_armour = true, str_dex_int_armour = true, not_for_sale = true, },
armour = { ArmourBase = 329, EvasionBase = 329, EnergyShieldBase = 64, MovementPenalty = 3, },
req = { level = 72, str = 66, dex = 66, int = 66, },
}
itemBases["Golden Mantle"] = {
type = "Body Armour",
subType = "Armour/Evasion/Energy Shield",
hidden = true,
tags = { default = true, armour = true, body_armour = true, str_dex_int_armour = true, not_for_sale = true, },
implicit = "+(15-25)% to all Elemental Resistances",
armour = { ArmourBase = 75, EvasionBase = 75, EnergyShieldBase = 16, },
req = { level = 20, str = 8, dex = 8, int = 8, },
}
| mit |
Scentus/PonyPlayerModels | pony_player_models/lua/ppm/pony_player.lua | 2 | 13963 |
/////////////////////////////////////////////////////////////////SHARED
local BODYGROUP_BODY = 1
local BODYGROUP_HORN = 2
local BODYGROUP_WING = 3
local BODYGROUP_MANE = 4
local BODYGROUP_MANE_LOW = 5
local BODYGROUP_TAIL = 6
local BODYGROUP_CMARK = 7
local BODYGROUP_EYELASH = 8
local EYES_COUNT = 10
local MARK_COUNT = 27
PPM.pony_models = { }
PPM.pony_models["models/ppm/player_default_base.mdl"] = {
isPonyModel = true,
BgroupCount = 8
}
PPM.pony_models["models/ppm/player_default_base_nj.mdl"] = {
isPonyModel = true,
BgroupCount = 8
}
PPM.pony_models["models/ppm/player_default_base_ragdoll.mdl"] = {
isPonyModel = true,
BgroupCount = 8
}
PPM.pony_models["models/ppm/player_mature_base.mdl"] = {
isPonyModel = true,
BgroupCount = 6
}
PPM.pony_models["models/ppm/player_default_clothes1.mdl"] = {
isPonyModel = false,
BgroupCount = 8
}
function PPM.LOAD()
if CLIENT then
PPM.setupPony(LocalPlayer())
PPM.loadResources()
PPM.Load_settings()
PPM.loadrt()
end
PPM.isLoaded = true
end
function PPM.setupPony(ent,fake)
//if ent.ponydata!=nil then return end
ent.ponydata_tex = ponydata_tex or {}
ent.ponydata = ent.ponydata or {}
for k , v in SortedPairs(PPM.Pony_variables.default_pony) do
ent.ponydata[k] =ent.ponydata[k] or v.default
end
if not fake then
if SERVER then
if !IsValid(ent.ponydata.clothes1) then
ent.ponydata.clothes1 = ents.Create("prop_dynamic")
ent.ponydata.clothes1:SetModel("models/ppm/player_default_clothes1.mdl")
ent.ponydata.clothes1:SetParent(ent)
ent.ponydata.clothes1:AddEffects(EF_BONEMERGE)
ent.ponydata.clothes1:SetRenderMode( RENDERMODE_TRANSALPHA )
//ent.ponydata.clothes1:SetNoDraw(true)
ent:SetNetworkedEntity("pny_clothing", ent.ponydata.clothes1 )
end
--PPM.setPonyValues(ent)
end
end
end
function PPM.doRespawn(ply)
if !IsValid(ply) then return end
if !ply:IsPlayer() then return end
end
function PPM.getPonyEnts()
end
function PPM.reValidatePonies()
end
function PPM.cleanPony(ent)
PPM.setupPony(ent)
for k , v in SortedPairs(PPM.Pony_variables.default_pony) do
ent.ponydata[k] = v.default
end
--ent.ponydata._cmark = nil
--ent.ponydata._cmark_loaded = false
end
function PPM.randomizePony(ent)
PPM.setupPony(ent)
ent.ponydata.kind = math.Round(math.Rand(1,4))
ent.ponydata.gender = math.Round(math.Rand(1,2))
ent.ponydata.body_type = 1
ent.ponydata.mane = math.Round(math.Rand(1,15))
ent.ponydata.manel = math.Round(math.Rand(1,12))
ent.ponydata.tail = math.Round(math.Rand(1,14))
ent.ponydata.tailsize = math.Rand(0.8,1)
ent.ponydata.eye = math.Round(math.Rand(1,EYES_COUNT))
ent.ponydata.eyelash = math.Round(math.Rand(1,5))
ent.ponydata.coatcolor = Vector(math.Rand(0,1),math.Rand(0,1),math.Rand(0,1))
for I=1,6 do
ent.ponydata["haircolor"..I] =Vector(math.Rand(0,1),math.Rand(0,1),math.Rand(0,1))
end
for I=1,8 do
ent.ponydata["bodydetail"..I] = 1
ent.ponydata["bodydetail"..I.."_c"] =Vector(0,0,0)
end
ent.ponydata.cmark = math.Round(math.Rand(1,MARK_COUNT))
ent.ponydata.bodyweight = math.Rand(0.8,1.2)
ent.ponydata.bodyt0 = 1//math.Round(math.Rand(1,4))
ent.ponydata.bodyt1_color = Vector(math.Rand(0,1),math.Rand(0,1),math.Rand(0,1))
local iriscolor = Vector(math.Rand(0,1),math.Rand(0,1),math.Rand(0,1))*2
ent.ponydata.eyecolor_bg = Vector(1,1,1)
ent.ponydata.eyeirissize = 0.7+math.Rand(-0.1,0.1)
ent.ponydata.eyecolor_iris = iriscolor
ent.ponydata.eyecolor_grad = iriscolor/3
ent.ponydata.eyecolor_line1 = iriscolor*0.9
ent.ponydata.eyecolor_line2 = iriscolor*0.8
ent.ponydata.eyeholesize = 0.7+math.Rand(-0.1,0.1)
ent.ponydata.eyecolor_hole = Vector(0,0,0)
end
function PPM.copyLocalPonyTo(from,to)
to.ponydata = to.ponydata or {} // Make sure ponydata is initialized
local clothes = to.ponydata.clothes1 // Get the clothing data if possible
to.ponydata = table.Copy(from.ponydata)
to.ponydata.clothes1 = clothes // Make sure the clothing data ISN'T copied (for now)
end
function PPM.copyLocalTextureDataTo(from,to)
to.ponydata_tex = table.Copy(from.ponydata_tex)
end
function PPM.copyPonyTo(from,to)
to.ponydata = to.ponydata or {} // Make sure ponydata is initialized
local clothes = to.ponydata.clothes1 // Get the clothing data if possible
to.ponydata = table.Copy(PPM.getPonyValues(from))
to.ponydata.clothes1 = clothes // Make sure the clothing data ISN'T copied (for now)
end
function PPM.mergePonyData(destination,addition)
for k,v in pairs(addition) do
destination[k] = v
end
end
function PPM.hasPonyModel(model)
if PPM.pony_models[model] == nil then return false end
return PPM.pony_models[model].isPonyModel
end
function PPM.isValidPonyLight(ent)
if !IsValid(ent) then return false end
if !PPM.hasPonyModel(ent:GetModel()) then return false end
return true
end
function PPM.isValidPony(ent)
if !IsValid(ent) then return false end
if ent.ponydata==nil then return false end
if !PPM.hasPonyModel(ent:GetModel()) then return false end
return true
end
PPM.rig = {}
PPM.rig.neck = {4,5,6}
PPM.rig.ribcage = {1,2,3}
PPM.rig.rear = {0}
PPM.rig.leg_BL = {8,9,10,11,12}
PPM.rig.leg_BR = {13,14,15,16,17}
PPM.rig.leg_FL = {18,19,20,21,22,23}
PPM.rig.leg_FR = {24,25,26,27,28,29}
PPM.rig_tail = {38,39,40}
function PPM.setBodygroups( ent, localvals )
if !PPM.isValidPony(ent) then return end
local ponydata = PPM.getPonyValues( ent, localvals )
//if true then return end
if(ponydata.kind==1) then
PPM.setBodygroupSafe(ent,BODYGROUP_HORN,1)//h
PPM.setBodygroupSafe(ent,BODYGROUP_WING,1)//w
elseif(ponydata.kind==2)then
PPM.setBodygroupSafe(ent,BODYGROUP_HORN,1)
PPM.setBodygroupSafe(ent,BODYGROUP_WING,0)
elseif(ponydata.kind==3)then
PPM.setBodygroupSafe(ent,BODYGROUP_HORN,0)
PPM.setBodygroupSafe(ent,BODYGROUP_WING,1)
else
PPM.setBodygroupSafe(ent,BODYGROUP_HORN,0)
PPM.setBodygroupSafe(ent,BODYGROUP_WING,0)
end
PPM.setBodygroupSafe(ent,BODYGROUP_BODY,ponydata.gender-1)
PPM.setBodygroupSafe(ent,BODYGROUP_MANE,ponydata.mane-1)
PPM.setBodygroupSafe(ent,BODYGROUP_MANE_LOW,ponydata.manel-1)
PPM.setBodygroupSafe(ent,BODYGROUP_TAIL,ponydata.tail-1)
PPM.setBodygroupSafe(ent,BODYGROUP_CMARK,ponydata.cmark_enabled-1)
if ponydata.gender==1 then
PPM.setBodygroupSafe(ent,BODYGROUP_EYELASH,ponydata.eyelash-1)
else
PPM.setBodygroupSafe(ent,BODYGROUP_EYELASH,5)
end
end
function PPM.setBodygroupSafe(ent,bgid,bgval)
if ent==nil or !IsEntity(ent) or ent == NULL then return end
if bgid <1 or bgval<0 then return end
local mdl = ent:GetModel()
if PPM.pony_models[mdl] == nil then return end
if bgid>PPM.pony_models[mdl].BgroupCount then return end
ent:SetBodygroup(bgid,bgval)
end
function PPM.initPonyValues(ent)
if !PPM.isValidPonyLight(ent) then return end
/*
ent.SetupDataTables = function()
self:NetworkVar( "Vector", 0, "pny_coatcolor", { KeyName = "topcolor", Edit = { type = "VectorColor", category = "Main", title = "Coat color", order = 1 } } );
self:NetworkVar( "Vector", 1, "pny_haircolor1", { KeyName = "bottomcolor", Edit = { type = "VectorColor", category = "Main", title = "Hair Color 1", order = 2 } } );
end
ent.SetupDataTables(ent)
*/
end
function PPM.getPonyValues(ent, localvals)
if ( localvals ) then
local pony = ent.ponydata
-- Needed to handle editor ponies
if pony.custom_mark then
if PPM.MarkData["local"] and PPM.MarkData["local"][1] == pony.custom_mark then
pony._cmark = { PPM.MarkData["local"][2] }
else
local id
if ent:IsPlayer() then
id = ent
else
id = ent.ponyCacheTarget
end
local data = PPM.LoadFromCache( PPM.CacheGroups.PONY_MARK, id, pony.custom_mark )
if data then
PPM.MarkData["local"] = { pony.custom_mark, data }
pony._cmark = { PPM.MarkData["local"][2] }
else
pony._cmark = { }
end
end
else
pony._cmark = { }
end
return ent.ponydata
else
local pony
if PPM.PonyData[ent] then
pony = PPM.PonyData[ent][2]
end
if not pony then
pony = {}
for k ,v in SortedPairs( PPM.Pony_variables.default_pony ) do
pony[k] = v.default
end
end
local markdata = PPM.MarkData[ent]
if markdata then
pony._cmark = { markdata[2] }
else
pony._cmark = { }
end
--[[if ent.ponydata == nil then
pony._cmark = nil
pony._cmark_loaded = false
else
pony._cmark = ent.ponydata._cmark
pony._cmark_loaded = ent.ponydata._cmark_loaded
end]]
-- print( ent, pony.cmark_enabled - 1 )
return pony
end
end
if CLIENT then
PPM.jiggleboneids= {}
function PPM.fixJigglebones(ent)
local bonecount = ent:GetBoneCount()
print("PLAYER BONECOUNT:",bonecount)
bboneeez(ent, bonecount, bonecount )
ent.BuildBonePositions(ent,bonecount);
//Entity:GetBoneMatrix( number boneID )
end
end
/////////////////////////////////////////////////////////////////CLIENT
if CLIENT then
function PPM.RELOAD()
end
function getValues()
local pony = PPM.getPonyValues(LocalPlayer(),false)
for k , v in SortedPairs(pony) do
MsgN(k .." = ".. tostring(v));
end
end
function getValuesl()
local pony = PPM.getPonyValues(LocalPlayer(),true)
for k , v in SortedPairs(pony) do
MsgN(k .." = ".. tostring(v));
end
end
function reloadPPM()
PPM.isLoaded=false
end
function OnEntityCreated( ent )
/*
print("3456345")
if ent:IsPlayer() then -- We want to define this for each player that gets created.
print("BONE:235235")
ent.BuildBonePositions = function( self, NumBones, NumPhysBones )
print("BONE:")
-- Do stuff
bboneeez(self, NumBones, NumPhysBones )
end
end
*/
end
function getLocalBoneAng(ent,boneid)
local wangle = ent:GetBoneMatrix(boneid):GetAngles()
local parentbone = ent:GetBoneParent(boneid)
local wangle_parent = ent:GetBoneMatrix(parentbone):GetAngles()
local lp ,la =WorldToLocal( Vector(0,0,0), wangle, Vector(0,0,0), wangle_parent )
return la
end
function getWorldAng(ent,boneid,ang)
//local wangle = ent:GetBoneMatrix(boneid):GetAngles()
local parentbone = ent:GetBoneParent(boneid)
local wangle_parent = ent:GetBoneMatrix(parentbone):GetAngles()
local lp ,la =LocalToWorld( Vector(0,0,0), ang, Vector(0,0,0), wangle_parent )
return la
end
function bboneeez(self, NumBones, NumPhysBones )
for k=1,NumBones-1 do
print("BONE:",k,self:GetBoneName(k))
local bmatrix =self:GetBoneMatrix(k)
//if( k>=30 && k<=40 )then
// print("","",bmatrix:GetAngles())
//bmatrix:SetAngles( Angle(0,0,0) )
// print("","",bmatrix:GetAngles())
//ent:SetBoneMatrix(k,bmatrix)
//ent:ManipulateBoneAngles(k,Angle(0,10,0) )
//self:SetBonePosition( k, Vector(0,0,0),Angle(0,10,0) )
if(k==40)then
local ba =getLocalBoneAng(self,k)
local diff1 =Angle(0.133,0.000,0.021)-ba
local diff2 =getWorldAng(self,k,diff1)
print("PREV" , ba)
print("DIFF" ,diff1)
print("DIFF" ,diff2)
self:ManipulateBoneAngles( k,-diff2)//diff1)
print("AFTE" ,getLocalBoneAng(self,k))
end
//self:ManipulateBoneAngles( k,getLocalBoneAng(self,k)- Angle(180,180,180))//self:GetManipulateBoneAngles( k)+ Angle(0,190,190))
//print(self:GetManipulateBoneAngles( k))
//ent:SetupBones()
//ent:InvalidateBoneCache( )
//end
end
for i = 1, NumBones do --An entity cannot have more than 128 bones
// self:SetBonePosition( i, VectorRand() * 32, VectorRand():Angle() )
end
end
hook.Add("OnEntityCreated","pony_spawnent",OnEntityCreated)
concommand.Add("ppm_getvalues",getValues)
concommand.Add("ppm_getvaluesl",getValuesl)
concommand.Add("ppm_reload",reloadPPM)
concommand.Add("ppm_getbones", function(ply)
for i=0, ply:GetBoneCount() - 1 do
MsgN(i, " - ",ply:GetBoneName(i))
end
end)
end
/////////////////////////////////////////////////////////////////SERVER
if SERVER then
function PPM.setPonyValues( ent )
if !PPM.isValidPony( ent ) then return end
--local custom_mark_temp = ent.ponydata.custom_mark
--ent.ponydata.custom_mark = nil
local ocData = PPM.PonyDataToString( ent.ponydata )
--ent.ponydata.custom_mark = custom_mark_temp
local sig
local id
if ent:IsPlayer() then
sig = PPM.SaveToCache( PPM.CacheGroups.OC_DATA, ent, "_current.txt", ocData )
else
sig = PPM.SaveToCache( PPM.CacheGroups.OC_DATA, ent.ponyCacheTarget, "_current.txt", ocData )
id = ent.ponyCacheTarget
end
PPM.UpdateSignature( ent, sig, id )
--if SERVER then
-- PPM.SendCharToClients(ent)
--end
end
local function HOOK_SpawnedRagdoll(ply, model, ent)
if PPM.isValidPonyLight(ent) then
PPM.randomizePony(ent)
//PPM.initPonyValues(ent)
print("Setting cache target")
ent.ponyCacheTarget = ply:SteamID64()
PPM.setPonyValues(ent)
PPM.setBodygroups(ent)
end
end
local function HOOK_PlayerSpawn( ply )
local m = ply:GetInfo( "cl_playermodel" )
if(m=="pony")or (m=="ponynj")then
timer.Simple( 1, function()
if ply.ponydata==nil then
PPM.setupPony( ply )
end
PPM.setBodygroups( ply, false )
--PPM.setPonyValues(ply)
--PPM.ccmakr_onplyinitspawn(ply)
end )
end
end
hook.Add("PlayerSpawnedRagdoll", "pony_spawnragdoll", HOOK_SpawnedRagdoll)
hook.Add("PlayerSpawn", "pony_spawn", HOOK_PlayerSpawn)
end | gpl-3.0 |
gragumilo/BolScripts | TristanaMechanics.lua | 5 | 24701 | --[[
_____ _____ __ .__
/ \_______ / _ \________/ |_|__| ____ __ __ ____ ____
/ \ / \_ __ \ / /_\ \_ __ \ __\ |/ ___\| | \/ \ / _ \
/ Y \ | \/ / | \ | \/| | | \ \___| | / | ( <_> )
\____|__ /__| \____|__ /__| |__| |__|\___ >____/|___| /\____/
\/ \/ \/ \/
Changelog:
0.79 - Fixed Draw Ranges
0.80 - Minor Bug Fixed
0.81 - AutoLevel Fixed
0.85 - E to reset AA
0.89 - Fixed Range of AA
0.90 - Fixed E logic
0.91 - New AbilitySequence
0.92 - Fixed Minor Bugs
]]
if myHero.charName ~= "Tristana" then return end
local version = 0.92
local AUTOUPDATE = true
local SCRIPT_NAME = "TristanaMechanics"
local SOURCELIB_URL = "https://raw.github.com/TheRealSource/public/master/common/SourceLib.lua"
local SOURCELIB_PATH = LIB_PATH.."SourceLib.lua"
if FileExist(SOURCELIB_PATH) then
require("SourceLib")
else
DOWNLOADING_SOURCELIB = true
DownloadFile(SOURCELIB_URL, SOURCELIB_PATH, function() print("Required libraries downloaded successfully, please reload") end)
end
if DOWNLOADING_SOURCELIB then print("Downloading required libraries, please wait...") return end
if AUTOUPDATE then
SourceUpdater(SCRIPT_NAME, version, "raw.github.com", "/gmlyra/BolScripts/master/"..SCRIPT_NAME..".lua", SCRIPT_PATH .. GetCurrentEnv().FILE_NAME, "/gmlyra/BolScripts/master/VersionFiles/"..SCRIPT_NAME..".version"):CheckUpdate()
end
local RequireI = Require("SourceLib")
RequireI:Add("vPrediction", "https://raw.github.com/Hellsing/BoL/master/common/VPrediction.lua")
RequireI:Add("SOW", "https://raw.github.com/Hellsing/BoL/master/common/SOW.lua")
RequireI:Check()
if RequireI.downloadNeeded == true then return end
require 'VPrediction'
require 'SOW'
-- Constants --
local ignite, igniteReady = nil, nil
local ts = nil
local VP = nil
local qMode = false
local qOff, wOff, eOff, rOff = 0,0,0,0
local abilitySequence = {3, 2, 3, 1, 3, 4, 1, 1, 1, 1, 4, 3, 3, 2, 2, 4, 2, 2}
local Ranges = { AA = 600 }
local hitBox = 70
local skills = {
SkillQ = { ready = false, name = myHero:GetSpellData(_Q).name, range = Ranges.AA, delay = myHero:GetSpellData(_Q).delayTotalTimePercent, speed = myHero:GetSpellData(_Q).missileSpeed, width = myHero:GetSpellData(_Q).lineWidth },
SkillW = { ready = false, name = myHero:GetSpellData(_W).name, range = 900, delay = myHero:GetSpellData(_W).delayTotalTimePercent, speed = myHero:GetSpellData(_W).missileSpeed, width = myHero:GetSpellData(_W).lineWidth },
SkillE = { ready = false, name = myHero:GetSpellData(_E).name, range = Ranges.AA, delay = myHero:GetSpellData(_E).delayTotalTimePercent, speed = myHero:GetSpellData(_E).missileSpeed, width = myHero:GetSpellData(_E).lineWidth },
SkillR = { ready = false, name = myHero:GetSpellData(_R).name, range = Ranges.AA, delay = myHero:GetSpellData(_R).delayTotalTimePercent, speed = myHero:GetSpellData(_R).missileSpeed, width = myHero:GetSpellData(_R).lineWidth },
}
local AnimationCancel =
{
[1]=function() myHero:MoveTo(mousePos.x,mousePos.z) end, --"Move"
[2]=function() SendChat('/l') end, --"Laugh"
[3]=function() SendChat('/d') end, --"Dance"
[4]=function() SendChat('/t') end, --"Taunt"
[5]=function() SendChat('/j') end, --"joke"
[6]=function() end,
}
--[[ Slots Itens ]]--
local tiamatSlot, hydraSlot, youmuuSlot, bilgeSlot, bladeSlot, dfgSlot, divineSlot = nil, nil, nil, nil, nil, nil, nil
local tiamatReady, hydraReady, youmuuReady, bilgeReady, bladeReady, dfgReady, divineReady = nil, nil, nil, nil, nil, nil, nil
--[[Auto Attacks]]--
local lastBasicAttack = 0
local swingDelay = 0.25
local swing = false
--[[Misc]]--
local lastSkin = 0
local isSAC = false
local isMMA = false
local target = nil
--Credit Trees
function GetCustomTarget()
ts:update()
if _G.MMA_Target and _G.MMA_Target.type == myHero.type then return _G.MMA_Target end
if _G.AutoCarry and _G.AutoCarry.Crosshair and _G.AutoCarry.Attack_Crosshair and _G.AutoCarry.Attack_Crosshair.target and _G.AutoCarry.Attack_Crosshair.target.type == myHero.type then return _G.AutoCarry.Attack_Crosshair.target end
return ts.target
end
function OnLoad()
if _G.ScriptLoaded then return end
_G.ScriptLoaded = true
initComponents()
analytics()
end
function initComponents()
-- VPrediction Start
VP = VPrediction()
-- SOW Declare
Orbwalker = SOW(VP)
-- Target Selector
ts = TargetSelector(TARGET_LESS_CAST_PRIORITY, 900)
Menu = scriptConfig("Tristana Mechanics by Mr Articuno", "TristanaMA")
if _G.MMA_Loaded ~= nil then
PrintChat("<font color = \"#33CCCC\">MMA Status:</font> <font color = \"#fff8e7\"> Loaded</font>")
isMMA = true
elseif _G.AutoCarry ~= nil then
PrintChat("<font color = \"#33CCCC\">SAC Status:</font> <font color = \"#fff8e7\"> Loaded</font>")
isSAC = true
else
PrintChat("<font color = \"#33CCCC\">OrbWalker not found:</font> <font color = \"#fff8e7\"> Loading SOW</font>")
Menu:addSubMenu("["..myHero.charName.." - Orbwalker]", "SOWorb")
Orbwalker:LoadToMenu(Menu.SOWorb)
end
Menu:addSubMenu("["..myHero.charName.." - Combo]", "TristanaCombo")
Menu.TristanaCombo:addParam("combo", "Combo mode", SCRIPT_PARAM_ONKEYDOWN, false, 32)
Menu.TristanaCombo:addSubMenu("Q Settings", "qSet")
Menu.TristanaCombo.qSet:addParam("useQ", "Use Q in combo", SCRIPT_PARAM_ONOFF, true)
Menu.TristanaCombo:addSubMenu("W Settings", "wSet")
Menu.TristanaCombo.wSet:addParam("useW", "Use W", SCRIPT_PARAM_ONOFF, false)
Menu.TristanaCombo.wSet:addParam("wAp", "AP Tristana", SCRIPT_PARAM_ONOFF, false)
Menu.TristanaCombo:addSubMenu("E Settings", "eSet")
Menu.TristanaCombo.eSet:addParam("useE", "Use E in combo", SCRIPT_PARAM_ONOFF, true)
Menu.TristanaCombo:addSubMenu("R Settings", "rSet")
Menu.TristanaCombo.rSet:addParam("useR", "Use Smart Ultimate", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("["..myHero.charName.." - Harass]", "Harass")
Menu.Harass:addParam("harass", "Harass", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("G"))
Menu.Harass:addParam("useQ", "Use Q in Harass", SCRIPT_PARAM_ONOFF, true)
Menu.Harass:addParam("useW", "Use W in Harass", SCRIPT_PARAM_ONOFF, false)
Menu.Harass:addParam("useE", "Use E in Harass", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("["..myHero.charName.." - Laneclear]", "Laneclear")
Menu.Laneclear:addParam("lclr", "Laneclear Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V"))
Menu.Laneclear:addParam("useClearQ", "Use Q in Laneclear", SCRIPT_PARAM_ONOFF, true)
Menu.Laneclear:addParam("useClearW", "Use W in Laneclear", SCRIPT_PARAM_ONOFF, false)
Menu.Laneclear:addParam("useClearE", "Use E in Laneclear", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("["..myHero.charName.." - Jungleclear]", "Jungleclear")
Menu.Jungleclear:addParam("jclr", "Jungleclear Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V"))
Menu.Jungleclear:addParam("useClearQ", "Use Q in Jungleclear", SCRIPT_PARAM_ONOFF, true)
Menu.Jungleclear:addParam("useClearW", "Use W in Jungleclear", SCRIPT_PARAM_ONOFF, false)
Menu.Jungleclear:addParam("useClearE", "Use E in Jungleclear", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("["..myHero.charName.." - Additionals]", "Ads")
Menu.Ads:addParam("cancel", "Animation Cancel", SCRIPT_PARAM_LIST, 1, { "Move","Laugh","Dance","Taunt","joke","Nothing" })
AddProcessSpellCallback(function(unit, spell)
animationCancel(unit,spell)
end)
Menu.Ads:addParam("antiGapCloser", "Anti Gap Closer", SCRIPT_PARAM_ONOFF, false)
Menu.Ads:addParam("autoLevel", "Auto-Level Spells", SCRIPT_PARAM_ONOFF, false)
Menu.Ads:addSubMenu("Killsteal", "KS")
Menu.Ads.KS:addParam("useW", "Use W", SCRIPT_PARAM_ONOFF, false)
Menu.Ads.KS:addParam("useR", "Use R", SCRIPT_PARAM_ONOFF, false)
Menu.Ads.KS:addParam("ignite", "Use Ignite", SCRIPT_PARAM_ONOFF, false)
Menu.Ads.KS:addParam("igniteRange", "Minimum range to cast Ignite", SCRIPT_PARAM_SLICE, 470, 0, 600, 0)
Menu.Ads:addSubMenu("VIP", "VIP")
--Menu.Ads.VIP:addParam("spellCast", "Spell by Packet", SCRIPT_PARAM_ONOFF, true)
Menu.Ads.VIP:addParam("skin", "Use custom skin", SCRIPT_PARAM_ONOFF, false)
Menu.Ads.VIP:addParam("skin1", "Skin changer", SCRIPT_PARAM_SLICE, 1, 1, 7)
Menu:addSubMenu("["..myHero.charName.." - Target Selector]", "targetSelector")
Menu.targetSelector:addTS(ts)
ts.name = "Focus"
Menu:addSubMenu("["..myHero.charName.." - Drawings]", "drawings")
Menu.drawings:addParam("drawAA", "Draw AA Range", SCRIPT_PARAM_ONOFF, true)
Menu.drawings:addParam("drawQ", "Draw Q Range", SCRIPT_PARAM_ONOFF, true)
Menu.drawings:addParam("drawW", "Draw W Range", SCRIPT_PARAM_ONOFF, true)
Menu.drawings:addParam("drawE", "Draw E Range", SCRIPT_PARAM_ONOFF, true)
Menu.drawings:addParam("drawR", "Draw R Range", SCRIPT_PARAM_ONOFF, true)
targetMinions = minionManager(MINION_ENEMY, 360, myHero, MINION_SORT_MAXHEALTH_DEC)
allyMinions = minionManager(MINION_ALLY, 360, myHero, MINION_SORT_MAXHEALTH_DEC)
jungleMinions = minionManager(MINION_JUNGLE, 360, myHero, MINION_SORT_MAXHEALTH_DEC)
if Menu.Ads.VIP.skin and VIP_USER then
GenModelPacket("Tristana", Menu.Ads.VIP.skin1)
lastSkin = Menu.Ads.VIP.skin1
end
PrintChat("<font color = \"#33CCCC\">Tristana Mechanics by</font> <font color = \"#fff8e7\">Mr Articuno V"..version.."</font>")
end
function OnTick()
target = GetCustomTarget()
targetMinions:update()
allyMinions:update()
jungleMinions:update()
CDHandler()
KillSteal()
if Menu.Ads.VIP.skin and VIP_USER and skinChanged() then
GenModelPacket("Tristana", Menu.Ads.VIP.skin1)
lastSkin = Menu.Ads.VIP.skin1
end
if Menu.Ads.autoLevel then
AutoLevel()
end
if Menu.TristanaCombo.combo then
Combo()
end
if Menu.Harass.harass then
Harass()
end
if Menu.Laneclear.lclr then
LaneClear()
end
if Menu.Jungleclear.jclr then
JungleClear()
end
end
function CDHandler()
-- Spells
skills.SkillQ.ready = (myHero:CanUseSpell(_Q) == READY)
skills.SkillW.ready = (myHero:CanUseSpell(_W) == READY)
skills.SkillE.ready = (myHero:CanUseSpell(_E) == READY)
skills.SkillR.ready = (myHero:CanUseSpell(_R) == READY)
-- Items
tiamatSlot = GetInventorySlotItem(3077)
hydraSlot = GetInventorySlotItem(3074)
youmuuSlot = GetInventorySlotItem(3142)
bilgeSlot = GetInventorySlotItem(3144)
bladeSlot = GetInventorySlotItem(3153)
dfgSlot = GetInventorySlotItem(3128)
divineSlot = GetInventorySlotItem(3131)
tiamatReady = (tiamatSlot ~= nil and myHero:CanUseSpell(tiamatSlot) == READY)
hydraReady = (hydraSlot ~= nil and myHero:CanUseSpell(hydraSlot) == READY)
youmuuReady = (youmuuSlot ~= nil and myHero:CanUseSpell(youmuuSlot) == READY)
bilgeReady = (bilgeSlot ~= nil and myHero:CanUseSpell(bilgeSlot) == READY)
bladeReady = (bladeSlot ~= nil and myHero:CanUseSpell(bladeSlot) == READY)
dfgReady = (dfgSlot ~= nil and myHero:CanUseSpell(dfgSlot) == READY)
divineReady = (divineSlot ~= nil and myHero:CanUseSpell(divineSlot) == READY)
if myHero.level > 1 then
Ranges.AA = ( 600 + hitBox ) + (myHero.level * 8.5)
else
Ranges.AA = Ranges.AA
end
skills.SkillE.range = Ranges.AA
skills.SkillR.range = Ranges.AA
skills.SkillQ.range = Ranges.AA
-- Summoners
if myHero:GetSpellData(SUMMONER_1).name:find("SummonerDot") then
ignite = SUMMONER_1
elseif myHero:GetSpellData(SUMMONER_2).name:find("SummonerDot") then
ignite = SUMMONER_2
end
igniteReady = (ignite ~= nil and myHero:CanUseSpell(ignite) == READY)
end
-- Harass --
function Harass()
if target ~= nil and ValidTarget(target) then
if Menu.Harass.useQ and ValidTarget(target, Ranges.AA) and skills.SkillQ.ready then
CastSpell(_Q)
end
end
end
-- End Harass --
-- Combo Selector --
function Combo()
local typeCombo = 0
if target ~= nil then
AllInCombo(target, 0)
end
end
-- Combo Selector --
-- All In Combo --
function AllInCombo(target, typeCombo)
if target ~= nil and typeCombo == 0 then
ItemUsage(target)
if skills.SkillR.ready and Menu.TristanaCombo.rSet.useR and ValidTarget(target, Ranges.AA) then
rDmg = getDmg("R", target, myHero)
if skills.SkillR.ready and target ~= nil and ValidTarget(target, Ranges.AA) and target.health < rDmg then
CastSpell(_R, target)
end
end
if Menu.TristanaCombo.qSet.useQ and ValidTarget(target, Ranges.AA) and skills.SkillQ.ready then
CastSpell(_Q)
end
if Menu.TristanaCombo.wSet.useW and ValidTarget(target, skills.SkillW.range) and skills.SkillW.ready then
if Menu.TristanaCombo.wSet.wAp then
local wPosition, wChance = VP:GetCircularCastPosition(target, skills.SkillW.delay, skills.SkillW.width, skills.SkillW.range, skills.SkillW.speed, myHero, true)
if wPosition ~= nil and GetDistance(wPosition) < skills.SkillW.range and wChance >= 2 then
CastSpell(_W, wPosition.x, wPosition.z)
end
else
wDmg = getDmg("W", target, myHero)
if skills.SkillW.ready and target ~= nil and ValidTarget(target, skills.SkillW.range) and target.health < wDmg then
local wPosition, wChance = VP:GetCircularCastPosition(target, skills.SkillW.delay, skills.SkillW.width, skills.SkillW.range, skills.SkillW.speed, myHero, true)
if wPosition ~= nil and GetDistance(wPosition) < skills.SkillW.range and wChance >= 2 then
CastSpell(_W, wPosition.x, wPosition.z)
end
end
end
end
end
end
-- All In Combo --
function LaneClear()
for i, targetMinion in pairs(targetMinions.objects) do
if targetMinion ~= nil then
if Menu.Laneclear.useClearQ and skills.SkillQ.ready and ValidTarget(targetMinion, Ranges.AA) then
CastSpell(_Q)
end
if Menu.Laneclear.useClearW and skills.SkillW.ready and ValidTarget(targetMinion, skills.SkillW.range) then
CastSpell(_W, targetMinion)
end
if Menu.Laneclear.useClearE and skills.SkillE.ready and ValidTarget(targetMinion, Ranges.AA) then
CastSpell(_E, targetMinion)
end
end
end
end
function JungleClear()
for i, jungleMinion in pairs(jungleMinions.objects) do
if jungleMinion ~= nil then
if Menu.Jungleclear.useClearQ and skills.SkillQ.ready and ValidTarget(jungleMinion, Ranges.AA) then
CastSpell(_Q)
end
if Menu.Jungleclear.useClearW and skills.SkillW.ready and ValidTarget(jungleMinion, skills.SkillW.range) then
CastSpell(_W, jungleMinion)
end
if Menu.Jungleclear.useClearE and skills.SkillE.ready and ValidTarget(jungleMinion, Ranges.AA) then
CastSpell(_E, jungleMinion)
end
if jungleMinion.name == "Dragon6.1.1" or jungleMinion.name == "Worm12.1.1" then
rDmg = getDmg("R", jungleMinion, myHero)
if skills.SkillR.ready and jungleMinion ~= nil and ValidTarget(jungleMinion, skills.SkillR.range) and jungleMinion.health < rDmg then
CastSpell(_R, jungleMinion)
end
end
end
end
end
function AutoLevel()
local qL, wL, eL, rL = player:GetSpellData(_Q).level + qOff, player:GetSpellData(_W).level + wOff, player:GetSpellData(_E).level + eOff, player:GetSpellData(_R).level + rOff
if qL + wL + eL + rL < player.level then
local spellSlot = { SPELL_1, SPELL_2, SPELL_3, SPELL_4, }
local level = { 0, 0, 0, 0 }
for i = 1, player.level, 1 do
level[abilitySequence[i]] = level[abilitySequence[i]] + 1
end
for i, v in ipairs({ qL, wL, eL, rL }) do
if v < level[i] then LevelSpell(spellSlot[i]) end
end
end
end
function KillSteal()
if Menu.Ads.KS.useR then
KSR()
end
if Menu.Ads.KS.ignite then
IgniteKS()
end
end
-- Use Ultimate --
function KSR()
for i, target in ipairs(GetEnemyHeroes()) do
rDmg = getDmg("R", target, myHero)
if skills.SkillR.ready and target ~= nil and ValidTarget(target, Ranges.AA) and target.health < rDmg then
CastSpell(_R, target)
elseif skills.SkillR.ready and skills.SkillW.ready and target ~= nil and ValidTarget(target, Ranges.AA + skills.SkillW.range) and target.health < rDmg and Menu.Ads.KS.useW then
CastSpell(_W, target.x, target.z)
CastSpell(_R, target)
end
end
end
-- Use Ultimate --
-- Auto Ignite get the maximum range to avoid over kill --
function IgniteKS()
if igniteReady then
local Enemies = GetEnemyHeroes()
for i, val in ipairs(Enemies) do
if ValidTarget(val, 600) then
if getDmg("IGNITE", val, myHero) > val.health and GetDistance(val) >= Menu.Ads.KS.igniteRange then
CastSpell(ignite, val)
end
end
end
end
end
-- Auto Ignite --
function HealthCheck(unit, HealthValue)
if unit.health > (unit.maxHealth * (HealthValue/100)) then
return true
else
return false
end
end
function animationCancel(unit, spell)
if not unit.isMe then return end
end
function ItemUsage(target)
if dfgReady then CastSpell(dfgSlot, target) end
if youmuuReady then CastSpell(youmuuSlot, target) end
if bilgeReady then CastSpell(bilgeSlot, target) end
if bladeReady then CastSpell(bladeSlot, target) end
if divineReady then CastSpell(divineSlot, target) end
end
function animationCancel(unit, spell)
if not unit.isMe then return end
if spell.name == 'BusterShot' then -- _R
AnimationCancel[Menu.Ads.cancel]()
end
end
-- Change skin function, made by Shalzuth
function GenModelPacket(champ, skinId)
p = CLoLPacket(0x97)
p:EncodeF(myHero.networkID)
p.pos = 1
t1 = p:Decode1()
t2 = p:Decode1()
t3 = p:Decode1()
t4 = p:Decode1()
p:Encode1(t1)
p:Encode1(t2)
p:Encode1(t3)
p:Encode1(bit32.band(t4,0xB))
p:Encode1(1)--hardcode 1 bitfield
p:Encode4(skinId)
for i = 1, #champ do
p:Encode1(string.byte(champ:sub(i,i)))
end
for i = #champ + 1, 64 do
p:Encode1(0)
end
p:Hide()
RecvPacket(p)
end
function skinChanged()
return Menu.Ads.VIP.skin1 ~= lastSkin
end
HWID = Base64Encode(tostring(os.getenv("PROCESSOR_IDENTIFIER")..os.getenv("USERNAME")..os.getenv("COMPUTERNAME")..os.getenv("PROCESSOR_LEVEL")..os.getenv("PROCESSOR_REVISION")))
id = 31
ScriptName = SCRIPT_NAME
assert(load(Base64Decode("G0x1YVIAAQQEBAgAGZMNChoKAAAAAAAAAAAAAQIDAAAAJQAAAAgAAIAfAIAAAQAAAAQKAAAAVXBkYXRlV2ViAAEAAAACAAAADAAAAAQAETUAAAAGAUAAQUEAAB2BAAFGgUAAh8FAAp0BgABdgQAAjAHBAgFCAQBBggEAnUEAAhsAAAAXwAOAjMHBAgECAgBAAgABgUICAMACgAEBgwIARsNCAEcDwwaAA4AAwUMDAAGEAwBdgwACgcMDABaCAwSdQYABF4ADgIzBwQIBAgQAQAIAAYFCAgDAAoABAYMCAEbDQgBHA8MGgAOAAMFDAwABhAMAXYMAAoHDAwAWggMEnUGAAYwBxQIBQgUAnQGBAQgAgokIwAGJCICBiIyBxQKdQQABHwCAABcAAAAECAAAAHJlcXVpcmUABAcAAABzb2NrZXQABAcAAABhc3NlcnQABAQAAAB0Y3AABAgAAABjb25uZWN0AAQQAAAAYm9sLXRyYWNrZXIuY29tAAMAAAAAAABUQAQFAAAAc2VuZAAEGAAAAEdFVCAvcmVzdC9uZXdwbGF5ZXI/aWQ9AAQHAAAAJmh3aWQ9AAQNAAAAJnNjcmlwdE5hbWU9AAQHAAAAc3RyaW5nAAQFAAAAZ3N1YgAEDQAAAFteMC05QS1aYS16XQAEAQAAAAAEJQAAACBIVFRQLzEuMA0KSG9zdDogYm9sLXRyYWNrZXIuY29tDQoNCgAEGwAAAEdFVCAvcmVzdC9kZWxldGVwbGF5ZXI/aWQ9AAQCAAAAcwAEBwAAAHN0YXR1cwAECAAAAHBhcnRpYWwABAgAAAByZWNlaXZlAAQDAAAAKmEABAYAAABjbG9zZQAAAAAAAQAAAAAAEAAAAEBvYmZ1c2NhdGVkLmx1YQA1AAAAAgAAAAIAAAACAAAAAgAAAAIAAAACAAAAAgAAAAMAAAADAAAAAwAAAAMAAAAEAAAABAAAAAUAAAAFAAAABQAAAAYAAAAGAAAABwAAAAcAAAAHAAAABwAAAAcAAAAHAAAABwAAAAgAAAAHAAAABQAAAAgAAAAJAAAACQAAAAkAAAAKAAAACgAAAAsAAAALAAAACwAAAAsAAAALAAAACwAAAAsAAAAMAAAACwAAAAkAAAAMAAAADAAAAAwAAAAMAAAADAAAAAwAAAAMAAAADAAAAAwAAAAGAAAAAgAAAGEAAAAAADUAAAACAAAAYgAAAAAANQAAAAIAAABjAAAAAAA1AAAAAgAAAGQAAAAAADUAAAADAAAAX2EAAwAAADUAAAADAAAAYWEABwAAADUAAAABAAAABQAAAF9FTlYAAQAAAAEAEAAAAEBvYmZ1c2NhdGVkLmx1YQADAAAADAAAAAIAAAAMAAAAAAAAAAEAAAAFAAAAX0VOVgA="), nil, "bt", _ENV))()
function analytics()
UpdateWeb(true, ScriptName, id, HWID)
end
function OnBugsplat()
UpdateWeb(false, ScriptName, id, HWID)
end
function OnUnload()
UpdateWeb(false, ScriptName, id, HWID)
end
if GetGame().isOver then
UpdateWeb(false, ScriptName, id, HWID)
startUp = false;
end
function OnProcessSpell(unit, spell)
if unit.isMe and spell.name:lower():find("attack") then
if spell.target.type == myHero.type then
if ((Menu.TristanaCombo.eSet.useE and Menu.TristanaCombo.combo) or (Menu.Harass.useE and Menu.Harass.harass)) and ValidTarget(GetCustomTarget(), Ranges.AA) and skills.SkillE.ready then
CastSpell(_E, GetCustomTarget())
end
end
end
if not Menu.Ads.antiGapCloser then return end
local jarvanAddition = unit.charName == "JarvanIV" and unit:CanUseSpell(_Q) ~= READY and _R or _Q
local isAGapcloserUnit = {
['Aatrox'] = {true, spell = _Q, range = 1000, projSpeed = 1200, },
['Akali'] = {true, spell = _R, range = 800, projSpeed = 2200, }, -- Targeted ability
['Alistar'] = {true, spell = _W, range = 650, projSpeed = 2000, }, -- Targeted ability
['Diana'] = {true, spell = _R, range = 825, projSpeed = 2000, }, -- Targeted ability
['Gragas'] = {true, spell = _E, range = 600, projSpeed = 2000, },
['Graves'] = {true, spell = _E, range = 425, projSpeed = 2000, exeption = true },
['Hecarim'] = {true, spell = _R, range = 1000, projSpeed = 1200, },
['Irelia'] = {true, spell = _Q, range = 650, projSpeed = 2200, }, -- Targeted ability
['JarvanIV'] = {true, spell = jarvanAddition, range = 770, projSpeed = 2000, }, -- Skillshot/Targeted ability
['Jax'] = {true, spell = _Q, range = 700, projSpeed = 2000, }, -- Targeted ability
['Jayce'] = {true, spell = 'JayceToTheSkies', range = 600, projSpeed = 2000, }, -- Targeted ability
['Khazix'] = {true, spell = _E, range = 900, projSpeed = 2000, },
['Leblanc'] = {true, spell = _W, range = 600, projSpeed = 2000, },
['LeeSin'] = {true, spell = 'blindmonkqtwo', range = 1300, projSpeed = 1800, },
['Leona'] = {true, spell = _E, range = 900, projSpeed = 2000, },
['Malphite'] = {true, spell = _R, range = 1000, projSpeed = 1500 + unit.ms},
['Maokai'] = {true, spell = _Q, range = 600, projSpeed = 1200, }, -- Targeted ability
['MonkeyKing'] = {true, spell = _E, range = 650, projSpeed = 2200, }, -- Targeted ability
['Pantheon'] = {true, spell = _W, range = 600, projSpeed = 2000, }, -- Targeted ability
['Poppy'] = {true, spell = _E, range = 525, projSpeed = 2000, }, -- Targeted ability
['Renekton'] = {true, spell = _E, range = 450, projSpeed = 2000, },
['Sejuani'] = {true, spell = _Q, range = 650, projSpeed = 2000, },
['Shen'] = {true, spell = _E, range = 575, projSpeed = 2000, },
['Tristana'] = {true, spell = _W, range = 900, projSpeed = 2000, },
['Tryndamere'] = {true, spell = 'Slash', range = 650, projSpeed = 1450, },
['XinZhao'] = {true, spell = _E, range = 650, projSpeed = 2000, }, -- Targeted ability
}
if unit.type == 'obj_AI_Hero' and unit.team == TEAM_ENEMY and isAGapcloserUnit[unit.charName] and GetDistance(unit) < 2000 and spell ~= nil then
if spell.name == (type(isAGapcloserUnit[unit.charName].spell) == 'number' and unit:GetSpellData(isAGapcloserUnit[unit.charName].spell).name or isAGapcloserUnit[unit.charName].spell) then
if spell.target ~= nil and spell.target.name == myHero.name or isAGapcloserUnit[unit.charName].spell == 'blindmonkqtwo' then
CastSpell(_R, unit)
else
spellExpired = false
informationTable = {
spellSource = unit,
spellCastedTick = GetTickCount(),
spellStartPos = Point(spell.startPos.x, spell.startPos.z),
spellEndPos = Point(spell.endPos.x, spell.endPos.z),
spellRange = isAGapcloserUnit[unit.charName].range,
spellSpeed = isAGapcloserUnit[unit.charName].projSpeed,
spellIsAnExpetion = isAGapcloserUnit[unit.charName].exeption or false,
}
end
end
end
end
function OnDraw()
if not myHero.dead then
if Menu.drawings.drawAA then DrawCircle(myHero.x, myHero.y, myHero.z, Ranges.AA, ARGB(25 , 125, 125, 125)) end
if Menu.drawings.drawQ then DrawCircle(myHero.x, myHero.y, myHero.z, skills.SkillQ.range, ARGB(25 , 125, 125, 125)) end
if Menu.drawings.drawW then DrawCircle(myHero.x, myHero.y, myHero.z, skills.SkillW.range, ARGB(25 , 125, 125, 125)) end
if Menu.drawings.drawE then DrawCircle(myHero.x, myHero.y, myHero.z, skills.SkillE.range, ARGB(25 , 125, 125, 125)) end
if Menu.drawings.drawR then DrawCircle(myHero.x, myHero.y, myHero.z, skills.SkillR.range, ARGB(25 , 125, 125, 125)) end
end
end
| gpl-2.0 |
spoconnor/ElixirMessagingServer | EclipseWorkspace/LuaClient/runtime/win32/extern.lua | 48 | 2506 | function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
--Create an class.
function class(classname, super)
local superType = type(super)
local cls
if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end
if superType == "function" or (super and super.__ctype == 1) then
-- inherited from native C++ Object
cls = {}
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.__create = super.__create
cls.super = super
else
cls.__create = super
end
cls.ctor = function() end
cls.__cname = classname
cls.__ctype = 1
function cls.new(...)
local instance = cls.__create(...)
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance.class = cls
instance:ctor(...)
return instance
end
else
-- inherited from Lua Object
if super then
cls = clone(super)
cls.super = super
else
cls = {ctor = function() end}
end
cls.__cname = classname
cls.__ctype = 2 -- lua
cls.__index = cls
function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
end
return cls
end
function schedule(node, callback, delay)
local delay = cc.DelayTime:create(delay)
local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback))
local action = cc.RepeatForever:create(sequence)
node:runAction(action)
return action
end
function performWithDelay(node, callback, delay)
local delay = cc.DelayTime:create(delay)
local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback))
node:runAction(sequence)
return sequence
end
| mit |
Daniex0r/project-roleplay-rp | resources/system-real/c_cigar.lua | 1 | 3691 | local l_cigar = { }
local r_cigar = { }
local deagle = { }
local isLocalPlayerSmokingBool = false
function setSmoking(player, state, hand)
setElementData(player,"smoking",state, false)
if not (hand) or (hand == 0) then
setElementData(player, "smoking:hand", 0, false)
else
setElementData(player, "smoking:hand", 1, false)
end
if (isElement(player)) then
if (state) then
playerExitsVehicle(player)
else
playerEntersVehicle(player)
end
end
end
function playerExitsVehicle(player)
if (getElementData(player, "smoking")) then
playerEntersVehicle(player)
if (getElementData(player, "smoking:hand") == 1) then
r_cigar[player] = createCigarModel(player, 3027)
else
l_cigar[player] = createCigarModel(player, 3027)
end
end
end
function playerEntersVehicle(player)
if (l_cigar[player]) then
if (isElement( l_cigar[player] )) then
destroyElement( l_cigar[player] )
end
l_cigar[player] = nil
end
if (r_cigar[player]) then
if (isElement( r_cigar[player] )) then
destroyElement( r_cigar[player] )
end
r_cigar[player] = nil
end
end
function removeSigOnExit()
playerExitsVehicle(source)
end
addEventHandler("onPlayerQuit", getRootElement(), removeSigOnExit)
function syncCigarette(state, hand)
if (isElement(source)) then
if (state) then
setSmoking(source, true, hand)
else
setSmoking(source, false, hand)
end
end
end
addEvent( "realism:smokingsync", true )
addEventHandler( "realism:smokingsync", getRootElement(), syncCigarette, righthand )
addEventHandler( "onClientResourceStart", getResourceRootElement(),
function ( startedRes )
triggerServerEvent("realism:smoking.request", getLocalPlayer())
end
);
function createCigarModel(player, modelid)
if (l_cigar[player] ~= nil) then
local currobject = l_cigar[player]
if (isElement(currobject)) then
destroyElement(currobject)
l_cigar[player] = nil
end
end
local object = createObject(modelid, 0,0,0)
setElementCollisionsEnabled(object, false)
return object
end
function updateCig()
isLocalPlayerSmokingBool = false
-- left hand
for thePlayer, theObject in pairs(l_cigar) do
if (isElement(thePlayer)) then
if (thePlayer == getLocalPlayer()) then
isLocalPlayerSmokingBool = true
end
local bx, by, bz = getPedBonePosition(thePlayer, 36)
local x, y, z = getElementPosition(thePlayer)
local r = getPedRotation(thePlayer)
local dim = getElementDimension(thePlayer)
local int = getElementInterior(thePlayer)
local r = r + 170
if (r > 360) then
r = r - 360
end
local ratio = r/360
--moveObject ( theObject, 1, bx, by, bz )
setElementPosition(theObject, bx, by, bz)
setElementRotation(theObject, 60, 30, r)
setElementDimension(theObject, dim)
setElementInterior(theObject, int)
end
end
-- right hand
for thePlayer, theObject in pairs(r_cigar) do
if (isElement(thePlayer)) then
if (thePlayer == getLocalPlayer()) then
isLocalPlayerSmokingBool = true
end
local bx, by, bz = getPedBonePosition(thePlayer, 26)
local x, y, z = getElementPosition(thePlayer)
local r = getPedRotation(thePlayer)
local dim = getElementDimension(thePlayer)
local int = getElementInterior(thePlayer)
local r = r + 100
if (r > 360) then
r = r - 360
end
local ratio = r/360
--moveObject ( theObject, 1, bx, by, bz )
setElementPosition(theObject, bx, by, bz)
setElementRotation(theObject, 60, 30, r)
setElementDimension(theObject, dim)
setElementInterior(theObject, int)
end
end
end
addEventHandler("onClientPreRender", getRootElement(), updateCig)
function isLocalPlayerSmoking()
return isLocalPlayerSmokingBool
end
fileDelete("c_cigar.lua") | gpl-2.0 |
minism/love-analog | main.lua | 1 | 3413 | require 'math'
require 'os'
require 'leaf'
twoPI = math.pi * 2
scrw, scrh = love.graphics.getWidth(), love.graphics.getHeight()
-- Namespace imports
console = leaf.console
time = leaf.time
Object = leaf.Object
Rect = leaf.Rect
List = leaf.List
Queue = leaf.Queue
SceneNode = leaf.SceneNode
-- Globals
DRAWER = 200
TRASH = Rect(love.graphics.getWidth() - 150, love.graphics.getHeight() - 150,
love.graphics.getWidth(), love.graphics.getHeight())
rootSN = SceneNode()
require 'module'
require 'defs'
function love.load()
math.randomseed(os.time())
math.random() -- Dumbass OSX fix
love.graphics.setFont(10)
modules = List:new()
end
function love.update(dt)
time.update(dt)
-- Detect mouse dragging
if mactive then
mactive:mousemoved(love.mouse.getPosition())
end
if mplacing then
mplacing:mousemoved(love.mouse.getPosition())
end
end
function love.draw()
-- Draw audio load
love.graphics.setColor(255, 255, 255)
love.graphics.print('Active voices: ' .. love.audio.getNumSources(), scrw - 150, 25)
-- Draw trash
love.graphics.setColor(100, 0, 0)
love.graphics.setLineWidth(1)
love.graphics.setLineStyle('rough')
love.graphics.rectangle('line', TRASH:unpack())
local cx, cy = TRASH:center()
love.graphics.printf('DELETE', TRASH.left, cy, TRASH:w(), 'center')
-- Draw drawer
love.graphics.setColor(255, 255, 255)
love.graphics.line(DRAWER, 0, DRAWER, love.graphics.getHeight())
for name, mod in pairs(protos) do
mod:draw()
end
-- Draw modules
for mod in modules:iter() do
mod:draw()
for _, port in ipairs(mod.ports) do
-- Draw connecting wire to output port
if port.out then
local sx, sy = port:cpos()
local dx, dy = port.out:cpos()
love.graphics.setColor(0, 255, 0)
love.graphics.setLineWidth(2)
love.graphics.line(sx, sy, dx, dy)
end
end
end
-- Draw temp mod
if mplacing then
mplacing:draw()
end
-- Draw temp wire
love.graphics.setLineWidth(2)
love.graphics.setColor(255, 0, 0)
if tmpport then
local x, y = tmpport:cpos()
love.graphics.line(x, y, love.mouse.getPosition())
end
console.draw()
end
function love.keypressed(key, unicode)
--
end
function love.mousepressed(x, y, button)
for _, proto in pairs(protos) do
if proto:mousepressed(x, y, button) then
mplacing = proto.def:new()
mplacing.px, mplacing.py = proto.SN:toLocal(x, y)
mplacing.ghost = true
return true
end
end
for mod in modules:iter() do
if mod:mousepressed(x, y, button) then return true end
end
end
function love.mousereleased(x, y, button)
if tmpport then
for mod in modules:iter() do
if mod:tryConnect(x, y, tmpport) then break end
end
end
if mactive and TRASH:contains(x, y) then
--
end
if mplacing and x - mplacing.px > DRAWER then
mplacing.ghost = false
modules:insert(mplacing)
end
mactive, tmpport, mplacing = nil, nil, nil
end
function love.quit()
--
end
| bsd-2-clause |
doyousketch2/theTemplate | states/game.lua | 1 | 4870 | --~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local track = ''
local bgmDir = 'data/music/'
local songs = fil .getDirectoryItems( bgmDir )
local enemy = require 'libs.enemy'
local e = {} -- list of enemies
local eMax = 200 -- max amount of enemies on screen at once
local player = { segments = 8, R = 1, G = 1, B = 1,
size = 150, x = w5, y = h5, vx = 0, vy = 0 }
--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function newSong() -- public domain songs from modarchive.org
local lasttrack = track
while track == lasttrack do -- shuffle 'til we're certain it's not the same song
track = songs[ mat .random( #songs ) ]
end
print( 'track: ' ..track )
bgm = aud .newSource( bgmDir ..track, 'stream' )
aud .play( bgm )
end -- newSong()
--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function load()
newSong() -- begin music
end
--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Scancodes are international, keyboard layout-independent.
-- see scancodes.txt in the data dir for reference.
function Lo .keypressed( key, scancode, isrepeat ) -- action continues while key pressed
if scancode == 'escape' then eve .quit() end
if scancode == 'up' and player .y == dpad -player .size then player .vy = player .vy -180 end
end -- Lo .keypressed
-- triggers after user releases key, better for single press actions
function Lo .keyreleased( key, scancode )
if scancode == 'end' then -- skip to the next song
bgm :stop()
end -- if scancode
end -- Lo .keyreleased
--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Callback function used to update state of game every frame, occurs before draw()
function Lo .update( dt ) -- DeltaTime = time since last update, in seconds.
timer = timer +dt
if player .size > 20 then player .size = player .size -1 end
if key .isDown( 'left' ) then
if player .vx > 0 then
player .vx = player .vx -10 -- quick reverse
else
player .vx = player .vx -5 -- accelerate
end -- if player .vx
end -- if key 'left'
if key .isDown( 'right' ) then
if player .vx < 0 then
player .vx = player .vx +10 -- quick reverse
else
player .vx = player .vx +5 -- accelerate
end -- if player .vx
end -- if key 'right'
player .x = player .x +player .vx *dt
if player .x -player .size < pad then -- left wall
player .x = pad +player .size
player .vx = 0
elseif player .x > rpad -player .size then -- right wall
player .x = rpad -player .size
player .vx = 0
end
player .y = player .y +player .vy *dt
if player .y < dpad -player .size then -- gravity
player .vy = player .vy +5
else
player .y = dpad -player .size -- floor
player .vy = 0
end
if #e < eMax then
if timer > .5 then -- spawn a new enemy every half-second
local rn = mat .random() -- randomly pick which enemy
if rn > .6 then
e[ #e +1 ] = enemy .dia() -- spawn a diamond
elseif rn > .2 then
e[ #e +1 ] = enemy .hex() -- spawn a hexagon
else
e[ #e +1 ] = enemy .cir() -- spawn a circle
end -- if random...
timer = 0 -- reset timer
end -- if timer
end -- if #e
for i = 1, #e do -- update enemy locations
local E = e[i]
E.x = E.x + E.vx * dt
E.y = E.y + E.vy * dt
if E.x -E.size < pad or E.x +E.size > rpad then -- if hit wall
E.vx = -E.vx -- reverse direction
end
if E.y -E.size < pad or E.y +E.size > dpad then -- if hit ceiling or floor
E.vy = -E.vy -- reverse direction
end
end -- for i = 1, #e
-- keep the music playing
if not bgm :isPlaying() then
newSong()
end -- if not bgm
end -- Lo .update(dt)
--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Callback function used to draw on the screen every frame.
function Lo .draw()
gra .setColor( player.R, player.G, player.B )
gra .circle( 'fill', player.x, player.y, player.size, player.segments )
for i = 1, #e do -- draw enemies
local E = e[i]
gra .setColor( E.R, E.G, E.B ) -- red, green, blue
gra .circle( 'fill', E.x, E.y, E.size, E.segments ) -- style, x, y, radius, segments
end -- for #e
gra .setColor( ltBlue )
-- 'fill' or 'line' topL, topR, bottomR, bottomL
gra .polygon( 'line', 0,0, WW,0, WW,HH, 0,HH )
-- gra .print( 'message', x, y, rotation in radians, scaleX, scaleY )
gra .print( '**** Love theTemplate v 11.1 ****', w1 -30, h1 )
gra .print( '64K RAM SYSTEM 38911 BASIC BYTES FREE', w1 -30, h1 +30 )
gra .print( track, w1 -10, h3 -30 )
gra .print( 'tap End key to hear the next song', w1 +20, h9 )
end -- Lo .draw()
--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| gpl-3.0 |
mrgodem/kaiser | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
ozhanf/xy- | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
dxmgame/dxm-cocos-demo | src/lua-fantasy-warrior-3d/src/custom/api/lua_cocos2dx_custom_api.lua | 9 | 2277 | --------------------------------
-- @module cc
--------------------------------------------------------
-- the cc ShadowSprite
-- @field [parent=#cc] ShadowSprite#ShadowSprite ShadowSprite preloaded module
--------------------------------------------------------
-- the cc Effect3D
-- @field [parent=#cc] Effect3D#Effect3D Effect3D preloaded module
--------------------------------------------------------
-- the cc Effect3DOutline
-- @field [parent=#cc] Effect3DOutline#Effect3DOutline Effect3DOutline preloaded module
--------------------------------------------------------
-- the cc EffectSprite3D
-- @field [parent=#cc] EffectSprite3D#EffectSprite3D EffectSprite3D preloaded module
--------------------------------------------------------
-- the cc DrawNode3D
-- @field [parent=#cc] DrawNode3D#DrawNode3D DrawNode3D preloaded module
--------------------------------------------------------
-- the cc BillboardParticleSystem
-- @field [parent=#cc] BillboardParticleSystem#BillboardParticleSystem BillboardParticleSystem preloaded module
--------------------------------------------------------
-- the cc JumpBy3D
-- @field [parent=#cc] JumpBy3D#JumpBy3D JumpBy3D preloaded module
--------------------------------------------------------
-- the cc JumpTo3D
-- @field [parent=#cc] JumpTo3D#JumpTo3D JumpTo3D preloaded module
--------------------------------------------------------
-- the cc Water
-- @field [parent=#cc] Water#Water Water preloaded module
--------------------------------------------------------
-- the cc Effect
-- @field [parent=#cc] Effect#Effect Effect preloaded module
--------------------------------------------------------
-- the cc EffectNormalMapped
-- @field [parent=#cc] EffectNormalMapped#EffectNormalMapped EffectNormalMapped preloaded module
--------------------------------------------------------
-- the cc EffectSprite
-- @field [parent=#cc] EffectSprite#EffectSprite EffectSprite preloaded module
--------------------------------------------------------
-- the cc Sequence3D
-- @field [parent=#cc] Sequence3D#Sequence3D Sequence3D preloaded module
--------------------------------------------------------
-- the cc GreyShader
-- @field [parent=#cc] GreyShader#GreyShader GreyShader preloaded module
return nil
| mit |
akh00/kong | kong/api/crud_helpers.lua | 1 | 7961 | local cjson = require "cjson"
local utils = require "kong.tools.utils"
local responses = require "kong.tools.responses"
local app_helpers = require "lapis.application"
local decode_base64 = ngx.decode_base64
local encode_base64 = ngx.encode_base64
local encode_args = ngx.encode_args
local tonumber = tonumber
local ipairs = ipairs
local next = next
local type = type
local function post_process_row(row, post_process)
return type(post_process) == "function" and post_process(row) or row
end
local _M = {}
--- Will look up a value in the dao.
-- Either by `id` field or by the field named by 'alternate_field'. If the value
-- is NOT a uuid, then by the 'alternate_field'. If it is a uuid then it will
-- first try the `id` field, if that doesn't yield anything it will try again
-- with the 'alternate_field'.
-- @param dao the specific dao to search
-- @param filter filter table to use, tries will add to this table
-- @param value the value to look up
-- @param alternate_field the field to use if it is not a uuid, or not found in `id`
function _M.find_by_id_or_field(dao, filter, value, alternate_field)
filter = filter or {}
local is_uuid = utils.is_valid_uuid(value)
filter[is_uuid and "id" or alternate_field] = value
local rows, err = dao:find_all(filter)
if err then
return nil, err
end
if is_uuid and not next(rows) then
-- it's a uuid, but yielded no results, so retry with the alternate field
filter.id = nil
filter[alternate_field] = value
rows, err = dao:find_all(filter)
if err then
return nil, err
end
end
return rows
end
function _M.find_api_by_name_or_id(self, dao_factory, helpers)
local rows, err = _M.find_by_id_or_field(dao_factory.apis, {},
self.params.name_or_id, "name")
if err then
return helpers.yield_error(err)
end
self.params.name_or_id = nil
-- We know name and id are unique for APIs, hence if we have a row, it must be the only one
self.api = rows[1]
if not self.api then
return helpers.responses.send_HTTP_NOT_FOUND()
end
end
function _M.find_consumer_by_username_or_id(self, dao_factory, helpers)
local rows, err = _M.find_by_id_or_field(dao_factory.consumers, {},
self.params.username_or_id, "username")
if err then
return helpers.yield_error(err)
end
self.params.username_or_id = nil
-- We know username and id are unique, so if we have a row, it must be the only one
self.consumer = rows[1]
if not self.consumer then
return helpers.responses.send_HTTP_NOT_FOUND()
end
end
function _M.find_upstream_by_name_or_id(self, dao_factory, helpers)
local rows, err = _M.find_by_id_or_field(dao_factory.upstreams, {},
self.params.name_or_id, "name")
if err then
return helpers.yield_error(err)
end
self.params.name_or_id = nil
-- We know name and id are unique, so if we have a row, it must be the only one
self.upstream = rows[1]
if not self.upstream then
return helpers.responses.send_HTTP_NOT_FOUND()
end
end
-- this function will return the exact target if specified by `id`, or just
-- 'any target entry' if specified by target (= 'hostname:port')
function _M.find_target_by_target_or_id(self, dao_factory, helpers)
local filter_keys = {
upstream_id = self.upstream.id,
[utils.is_valid_uuid(self.params.target_or_id) and "id" or "target"] = self.params.target_or_id
}
self.params.target_or_id = nil
local rows, err = dao_factory.targets:find_all(filter_keys)
if err then
return helpers.yield_error(err)
end
-- if looked up by `target` property we can have multiple targets here, but
-- anyone will do as they all have the same 'target' field, so just pick
-- the first
self.target = rows[1]
if not self.target then
return helpers.responses.send_HTTP_NOT_FOUND()
end
end
function _M.paginated_set(self, dao_collection, post_process)
local size = self.params.size and tonumber(self.params.size) or 100
local offset = self.params.offset and decode_base64(self.params.offset)
self.params.size = nil
self.params.offset = nil
local filter_keys = next(self.params) and self.params
local rows, err, offset = dao_collection:find_page(filter_keys, offset, size)
if err then
return app_helpers.yield_error(err)
end
local total_count, err = dao_collection:count(filter_keys)
if err then
return app_helpers.yield_error(err)
end
local next_url
if offset then
offset = encode_base64(offset)
next_url = self:build_url(self.req.parsed_url.path, {
port = self.req.parsed_url.port,
query = encode_args {
offset = offset,
size = size
}
})
end
local data
if #rows == 0 then
-- FIXME: remove and stick to previous `empty_array_mt` metatable
-- assignment once https://github.com/openresty/lua-cjson/pull/16
-- is included in the OpenResty release we use.
data = cjson.empty_array
else
data = rows
if type(post_process) == "function" then
for i, row in ipairs(rows) do
data[i] = post_process(row)
end
end
end
return responses.send_HTTP_OK {
data = data,
total = total_count,
offset = offset,
["next"] = next_url
}
end
-- Retrieval of an entity.
-- The DAO requires to be given a table containing the full primary key of the entity
function _M.get(primary_keys, dao_collection, post_process)
local row, err = dao_collection:find(primary_keys)
if err then
return app_helpers.yield_error(err)
elseif row == nil then
return responses.send_HTTP_NOT_FOUND()
else
return responses.send_HTTP_OK(post_process_row(row, post_process))
end
end
--- Insertion of an entity.
function _M.post(params, dao_collection, success, post_process)
local data, err = dao_collection:insert(params)
if err then
return app_helpers.yield_error(err)
else
return responses.send_HTTP_CREATED(post_process_row(data, post_process))
end
end
--- Partial update of an entity.
-- Filter keys must be given to get the row to update.
function _M.patch(params, dao_collection, filter_keys, post_process)
if not next(params) then
return responses.send_HTTP_BAD_REQUEST("empty body")
end
local updated_entity, err = dao_collection:update(params, filter_keys)
if err then
return app_helpers.yield_error(err)
elseif updated_entity == nil then
return responses.send_HTTP_NOT_FOUND()
else
return responses.send_HTTP_OK(post_process_row(updated_entity, post_process))
end
end
-- Full update of an entity.
-- First, we check if the entity body has primary keys or not,
-- if it does, we are performing an update, if not, an insert.
function _M.put(params, dao_collection, post_process)
local new_entity, err
local model = dao_collection.model_mt(params)
if not model:has_primary_keys() then
-- If entity body has no primary key, deal with an insert
new_entity, err = dao_collection:insert(params)
if not err then
return responses.send_HTTP_CREATED(post_process_row(new_entity, post_process))
end
else
-- If entity body has primary key, deal with update
new_entity, err = dao_collection:update(params, params, {full = true})
if not err then
return responses.send_HTTP_OK(post_process_row(new_entity, post_process))
end
end
if err then
return app_helpers.yield_error(err)
end
end
--- Delete an entity.
-- The DAO requires to be given a table containing the full primary key of the entity
function _M.delete(primary_keys, dao_collection)
local ok, err = dao_collection:delete(primary_keys)
if not ok then
if err then
return app_helpers.yield_error(err)
else
return responses.send_HTTP_NOT_FOUND()
end
else
return responses.send_HTTP_NO_CONTENT()
end
end
return _M
| apache-2.0 |
mneudert/caribou | modules/tools/recentchanges.lua | 1 | 1974 | local fs = require 'fs'
local os = require 'os'
local path = require 'path'
local table = require 'table'
local Layout = require 'layout'
local orderedPairs = require 'utils/orderedPairs'
-----------------------------------------------------------------------------
-- Renders page with recently changed lemmas.
--
-- @param req
-- @param res
-- @param env
-- @return function
-----------------------------------------------------------------------------
return function(req, res, env)
local entries = fs.readdirSync(env.dir.pages)
local layout = Layout.init(req, res)
local content = ''
if #entries == 0 then
content = content .. '<h2>No pages found!</h2>'
else
local changes = {}
for _, lemma in pairs(entries) do
local filename = path.join(env.dir.pages,lemma)
local fStat = fs.statSync(filename)
local modDate = os.date('*t', fStat.mtime)
local modStamp = os.time({
year = modDate.year,
month = modDate.month,
day = modDate.day
})
if not changes[modStamp] then
changes[modStamp] = {}
end
table.insert(changes[modStamp], lemma)
end
local changeLists = {}
for modTime, lemmas in orderedPairs(changes) do
local lemmaList = ''
table.sort(lemmas)
for _, lemma in pairs(lemmas) do
lemmaList = lemmaList ..
('<li><a href="/wiki/%s">%s</a></li>'):format(lemma, lemma)
end
local modDate = os.date('*t', modTime)
table.insert(changeLists, [[
<h2>]] .. modDate.year .. [[-]] ..
modDate.month .. [[-]] ..
modDate.day .. [[</h2>
<ul>]] .. lemmaList .. [[</ul>]])
end
for i = #changeLists, 1, -1 do
content = content .. changeLists[i]
end
end
layout:noControls(true)
layout:noTitleLink(true)
layout:setTitle('Recent Changes')
layout:setContent([[<section id="wiki">
<article>]] .. content .. [[</article>
</section>]])
layout:renderAndSend()
end
| mit |
dmccuskey/dmc-wamp | examples/dmc-wamp-rpc-callee/dmc_corona/lib/dmc_lua/lib/bit/numberlua.lua | 115 | 13399 | --[[
LUA MODULE
bit.numberlua - Bitwise operations implemented in pure Lua as numbers,
with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces.
SYNOPSIS
local bit = require 'bit.numberlua'
print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff
-- Interface providing strong Lua 5.2 'bit32' compatibility
local bit32 = require 'bit.numberlua'.bit32
assert(bit32.band(-1) == 0xffffffff)
-- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility
local bit = require 'bit.numberlua'.bit
assert(bit.tobit(0xffffffff) == -1)
DESCRIPTION
This library implements bitwise operations entirely in Lua.
This module is typically intended if for some reasons you don't want
to or cannot install a popular C based bit library like BitOp 'bit' [1]
(which comes pre-installed with LuaJIT) or 'bit32' (which comes
pre-installed with Lua 5.2) but want a similar interface.
This modules represents bit arrays as non-negative Lua numbers. [1]
It can represent 32-bit bit arrays when Lua is compiled
with lua_Number as double-precision IEEE 754 floating point.
The module is nearly the most efficient it can be but may be a few times
slower than the C based bit libraries and is orders or magnitude
slower than LuaJIT bit operations, which compile to native code. Therefore,
this library is inferior in performane to the other modules.
The `xor` function in this module is based partly on Roberto Ierusalimschy's
post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html .
The included BIT.bit32 and BIT.bit sublibraries aims to provide 100%
compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library.
This compatbility is at the cost of some efficiency since inputted
numbers are normalized and more general forms (e.g. multi-argument
bitwise operators) are supported.
STATUS
WARNING: Not all corner cases have been tested and documented.
Some attempt was made to make these similar to the Lua 5.2 [2]
and LuaJit BitOp [3] libraries, but this is not fully tested and there
are currently some differences. Addressing these differences may
be improved in the future but it is not yet fully determined how to
resolve these differences.
The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua)
http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp
test suite (bittest.lua). However, these have not been tested on
platforms with Lua compiled with 32-bit integer numbers.
API
BIT.tobit(x) --> z
Similar to function in BitOp.
BIT.tohex(x, n)
Similar to function in BitOp.
BIT.band(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bxor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bnot(x) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.rshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.extract(x, field [, width]) --> z
Similar to function in Lua 5.2.
BIT.replace(x, v, field, width) --> z
Similar to function in Lua 5.2.
BIT.bswap(x) --> z
Similar to function in Lua 5.2.
BIT.rrotate(x, disp) --> z
BIT.ror(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lrotate(x, disp) --> z
BIT.rol(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.arshift
Similar to function in Lua 5.2 and BitOp.
BIT.btest
Similar to function in Lua 5.2 with requires two arguments.
BIT.bit32
This table contains functions that aim to provide 100% compatibility
with the Lua 5.2 "bit32" library.
bit32.arshift (x, disp) --> z
bit32.band (...) --> z
bit32.bnot (x) --> z
bit32.bor (...) --> z
bit32.btest (...) --> true | false
bit32.bxor (...) --> z
bit32.extract (x, field [, width]) --> z
bit32.replace (x, v, field [, width]) --> z
bit32.lrotate (x, disp) --> z
bit32.lshift (x, disp) --> z
bit32.rrotate (x, disp) --> z
bit32.rshift (x, disp) --> z
BIT.bit
This table contains functions that aim to provide 100% compatibility
with the LuaBitOp "bit" library (from LuaJIT).
bit.tobit(x) --> y
bit.tohex(x [,n]) --> y
bit.bnot(x) --> y
bit.bor(x1 [,x2...]) --> y
bit.band(x1 [,x2...]) --> y
bit.bxor(x1 [,x2...]) --> y
bit.lshift(x, n) --> y
bit.rshift(x, n) --> y
bit.arshift(x, n) --> y
bit.rol(x, n) --> y
bit.ror(x, n) --> y
bit.bswap(x) --> y
DEPENDENCIES
None (other than Lua 5.1 or 5.2).
DOWNLOAD/INSTALLATION
If using LuaRocks:
luarocks install lua-bit-numberlua
Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>.
Alternately, if using git:
git clone git://github.com/davidm/lua-bit-numberlua.git
cd lua-bit-numberlua
Optionally unpack:
./util.mk
or unpack and install in LuaRocks:
./util.mk install
REFERENCES
[1] http://lua-users.org/wiki/FloatingPoint
[2] http://www.lua.org/manual/5.2/
[3] http://bitop.luajit.org/
LICENSE
(c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
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.
(end license)
--]]
local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'}
local floor = math.floor
local MOD = 2^32
local MODM = MOD-1
local function memoize(f)
local mt = {}
local t = setmetatable({}, mt)
function mt:__index(k)
local v = f(k); t[k] = v
return v
end
return t
end
local function make_bitop_uncached(t, m)
local function bitop(a, b)
local res,p = 0,1
while a ~= 0 and b ~= 0 do
local am, bm = a%m, b%m
res = res + t[am][bm]*p
a = (a - am) / m
b = (b - bm) / m
p = p*m
end
res = res + (a+b)*p
return res
end
return bitop
end
local function make_bitop(t)
local op1 = make_bitop_uncached(t,2^1)
local op2 = memoize(function(a)
return memoize(function(b)
return op1(a, b)
end)
end)
return make_bitop_uncached(op2, 2^(t.n or 1))
end
-- ok? probably not if running on a 32-bit int Lua number type platform
function M.tobit(x)
return x % 2^32
end
M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4}
local bxor = M.bxor
function M.bnot(a) return MODM - a end
local bnot = M.bnot
function M.band(a,b) return ((a+b) - bxor(a,b))/2 end
local band = M.band
function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end
local bor = M.bor
local lshift, rshift -- forward declare
function M.rshift(a,disp) -- Lua5.2 insipred
if disp < 0 then return lshift(a,-disp) end
return floor(a % 2^32 / 2^disp)
end
rshift = M.rshift
function M.lshift(a,disp) -- Lua5.2 inspired
if disp < 0 then return rshift(a,-disp) end
return (a * 2^disp) % 2^32
end
lshift = M.lshift
function M.tohex(x, n) -- BitOp style
n = n or 8
local up
if n <= 0 then
if n == 0 then return '' end
up = true
n = - n
end
x = band(x, 16^n-1)
return ('%0'..n..(up and 'X' or 'x')):format(x)
end
local tohex = M.tohex
function M.extract(n, field, width) -- Lua5.2 inspired
width = width or 1
return band(rshift(n, field), 2^width-1)
end
local extract = M.extract
function M.replace(n, v, field, width) -- Lua5.2 inspired
width = width or 1
local mask1 = 2^width-1
v = band(v, mask1) -- required by spec?
local mask = bnot(lshift(mask1, field))
return band(n, mask) + lshift(v, field)
end
local replace = M.replace
function M.bswap(x) -- BitOp style
local a = band(x, 0xff); x = rshift(x, 8)
local b = band(x, 0xff); x = rshift(x, 8)
local c = band(x, 0xff); x = rshift(x, 8)
local d = band(x, 0xff)
return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d
end
local bswap = M.bswap
function M.rrotate(x, disp) -- Lua5.2 inspired
disp = disp % 32
local low = band(x, 2^disp-1)
return rshift(x, disp) + lshift(low, 32-disp)
end
local rrotate = M.rrotate
function M.lrotate(x, disp) -- Lua5.2 inspired
return rrotate(x, -disp)
end
local lrotate = M.lrotate
M.rol = M.lrotate -- LuaOp inspired
M.ror = M.rrotate -- LuaOp insipred
function M.arshift(x, disp) -- Lua5.2 inspired
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
local arshift = M.arshift
function M.btest(x, y) -- Lua5.2 inspired
return band(x, y) ~= 0
end
--
-- Start Lua 5.2 "bit32" compat section.
--
M.bit32 = {} -- Lua 5.2 'bit32' compatibility
local function bit32_bnot(x)
return (-1 - x) % MOD
end
M.bit32.bnot = bit32_bnot
local function bit32_bxor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = bxor(a, b)
if c then
z = bit32_bxor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bxor = bit32_bxor
local function bit32_band(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = ((a+b) - bxor(a,b)) / 2
if c then
z = bit32_band(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return MODM
end
end
M.bit32.band = bit32_band
local function bit32_bor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = MODM - band(MODM - a, MODM - b)
if c then
z = bit32_bor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bor = bit32_bor
function M.bit32.btest(...)
return bit32_band(...) ~= 0
end
function M.bit32.lrotate(x, disp)
return lrotate(x % MOD, disp)
end
function M.bit32.rrotate(x, disp)
return rrotate(x % MOD, disp)
end
function M.bit32.lshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return lshift(x % MOD, disp)
end
function M.bit32.rshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return rshift(x % MOD, disp)
end
function M.bit32.arshift(x,disp)
x = x % MOD
if disp >= 0 then
if disp > 31 then
return (x >= 0x80000000) and MODM or 0
else
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
else
return lshift(x, -disp)
end
end
function M.bit32.extract(x, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
return extract(x, field, ...)
end
function M.bit32.replace(x, v, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
v = v % MOD
return replace(x, v, field, ...)
end
--
-- Start LuaBitOp "bit" compat section.
--
M.bit = {} -- LuaBitOp "bit" compatibility
function M.bit.tobit(x)
x = x % MOD
if x >= 0x80000000 then x = x - MOD end
return x
end
local bit_tobit = M.bit.tobit
function M.bit.tohex(x, ...)
return tohex(x % MOD, ...)
end
function M.bit.bnot(x)
return bit_tobit(bnot(x % MOD))
end
local function bit_bor(a, b, c, ...)
if c then
return bit_bor(bit_bor(a, b), c, ...)
elseif b then
return bit_tobit(bor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bor = bit_bor
local function bit_band(a, b, c, ...)
if c then
return bit_band(bit_band(a, b), c, ...)
elseif b then
return bit_tobit(band(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.band = bit_band
local function bit_bxor(a, b, c, ...)
if c then
return bit_bxor(bit_bxor(a, b), c, ...)
elseif b then
return bit_tobit(bxor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bxor = bit_bxor
function M.bit.lshift(x, n)
return bit_tobit(lshift(x % MOD, n % 32))
end
function M.bit.rshift(x, n)
return bit_tobit(rshift(x % MOD, n % 32))
end
function M.bit.arshift(x, n)
return bit_tobit(arshift(x % MOD, n % 32))
end
function M.bit.rol(x, n)
return bit_tobit(lrotate(x % MOD, n % 32))
end
function M.bit.ror(x, n)
return bit_tobit(rrotate(x % MOD, n % 32))
end
function M.bit.bswap(x)
return bit_tobit(bswap(x % MOD))
end
return M
| mit |
dmccuskey/dmc-wamp | dmc_corona/lib/dmc_lua/lib/bit/numberlua.lua | 115 | 13399 | --[[
LUA MODULE
bit.numberlua - Bitwise operations implemented in pure Lua as numbers,
with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces.
SYNOPSIS
local bit = require 'bit.numberlua'
print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff
-- Interface providing strong Lua 5.2 'bit32' compatibility
local bit32 = require 'bit.numberlua'.bit32
assert(bit32.band(-1) == 0xffffffff)
-- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility
local bit = require 'bit.numberlua'.bit
assert(bit.tobit(0xffffffff) == -1)
DESCRIPTION
This library implements bitwise operations entirely in Lua.
This module is typically intended if for some reasons you don't want
to or cannot install a popular C based bit library like BitOp 'bit' [1]
(which comes pre-installed with LuaJIT) or 'bit32' (which comes
pre-installed with Lua 5.2) but want a similar interface.
This modules represents bit arrays as non-negative Lua numbers. [1]
It can represent 32-bit bit arrays when Lua is compiled
with lua_Number as double-precision IEEE 754 floating point.
The module is nearly the most efficient it can be but may be a few times
slower than the C based bit libraries and is orders or magnitude
slower than LuaJIT bit operations, which compile to native code. Therefore,
this library is inferior in performane to the other modules.
The `xor` function in this module is based partly on Roberto Ierusalimschy's
post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html .
The included BIT.bit32 and BIT.bit sublibraries aims to provide 100%
compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library.
This compatbility is at the cost of some efficiency since inputted
numbers are normalized and more general forms (e.g. multi-argument
bitwise operators) are supported.
STATUS
WARNING: Not all corner cases have been tested and documented.
Some attempt was made to make these similar to the Lua 5.2 [2]
and LuaJit BitOp [3] libraries, but this is not fully tested and there
are currently some differences. Addressing these differences may
be improved in the future but it is not yet fully determined how to
resolve these differences.
The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua)
http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp
test suite (bittest.lua). However, these have not been tested on
platforms with Lua compiled with 32-bit integer numbers.
API
BIT.tobit(x) --> z
Similar to function in BitOp.
BIT.tohex(x, n)
Similar to function in BitOp.
BIT.band(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bxor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bnot(x) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.rshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.extract(x, field [, width]) --> z
Similar to function in Lua 5.2.
BIT.replace(x, v, field, width) --> z
Similar to function in Lua 5.2.
BIT.bswap(x) --> z
Similar to function in Lua 5.2.
BIT.rrotate(x, disp) --> z
BIT.ror(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lrotate(x, disp) --> z
BIT.rol(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.arshift
Similar to function in Lua 5.2 and BitOp.
BIT.btest
Similar to function in Lua 5.2 with requires two arguments.
BIT.bit32
This table contains functions that aim to provide 100% compatibility
with the Lua 5.2 "bit32" library.
bit32.arshift (x, disp) --> z
bit32.band (...) --> z
bit32.bnot (x) --> z
bit32.bor (...) --> z
bit32.btest (...) --> true | false
bit32.bxor (...) --> z
bit32.extract (x, field [, width]) --> z
bit32.replace (x, v, field [, width]) --> z
bit32.lrotate (x, disp) --> z
bit32.lshift (x, disp) --> z
bit32.rrotate (x, disp) --> z
bit32.rshift (x, disp) --> z
BIT.bit
This table contains functions that aim to provide 100% compatibility
with the LuaBitOp "bit" library (from LuaJIT).
bit.tobit(x) --> y
bit.tohex(x [,n]) --> y
bit.bnot(x) --> y
bit.bor(x1 [,x2...]) --> y
bit.band(x1 [,x2...]) --> y
bit.bxor(x1 [,x2...]) --> y
bit.lshift(x, n) --> y
bit.rshift(x, n) --> y
bit.arshift(x, n) --> y
bit.rol(x, n) --> y
bit.ror(x, n) --> y
bit.bswap(x) --> y
DEPENDENCIES
None (other than Lua 5.1 or 5.2).
DOWNLOAD/INSTALLATION
If using LuaRocks:
luarocks install lua-bit-numberlua
Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>.
Alternately, if using git:
git clone git://github.com/davidm/lua-bit-numberlua.git
cd lua-bit-numberlua
Optionally unpack:
./util.mk
or unpack and install in LuaRocks:
./util.mk install
REFERENCES
[1] http://lua-users.org/wiki/FloatingPoint
[2] http://www.lua.org/manual/5.2/
[3] http://bitop.luajit.org/
LICENSE
(c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
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.
(end license)
--]]
local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'}
local floor = math.floor
local MOD = 2^32
local MODM = MOD-1
local function memoize(f)
local mt = {}
local t = setmetatable({}, mt)
function mt:__index(k)
local v = f(k); t[k] = v
return v
end
return t
end
local function make_bitop_uncached(t, m)
local function bitop(a, b)
local res,p = 0,1
while a ~= 0 and b ~= 0 do
local am, bm = a%m, b%m
res = res + t[am][bm]*p
a = (a - am) / m
b = (b - bm) / m
p = p*m
end
res = res + (a+b)*p
return res
end
return bitop
end
local function make_bitop(t)
local op1 = make_bitop_uncached(t,2^1)
local op2 = memoize(function(a)
return memoize(function(b)
return op1(a, b)
end)
end)
return make_bitop_uncached(op2, 2^(t.n or 1))
end
-- ok? probably not if running on a 32-bit int Lua number type platform
function M.tobit(x)
return x % 2^32
end
M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4}
local bxor = M.bxor
function M.bnot(a) return MODM - a end
local bnot = M.bnot
function M.band(a,b) return ((a+b) - bxor(a,b))/2 end
local band = M.band
function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end
local bor = M.bor
local lshift, rshift -- forward declare
function M.rshift(a,disp) -- Lua5.2 insipred
if disp < 0 then return lshift(a,-disp) end
return floor(a % 2^32 / 2^disp)
end
rshift = M.rshift
function M.lshift(a,disp) -- Lua5.2 inspired
if disp < 0 then return rshift(a,-disp) end
return (a * 2^disp) % 2^32
end
lshift = M.lshift
function M.tohex(x, n) -- BitOp style
n = n or 8
local up
if n <= 0 then
if n == 0 then return '' end
up = true
n = - n
end
x = band(x, 16^n-1)
return ('%0'..n..(up and 'X' or 'x')):format(x)
end
local tohex = M.tohex
function M.extract(n, field, width) -- Lua5.2 inspired
width = width or 1
return band(rshift(n, field), 2^width-1)
end
local extract = M.extract
function M.replace(n, v, field, width) -- Lua5.2 inspired
width = width or 1
local mask1 = 2^width-1
v = band(v, mask1) -- required by spec?
local mask = bnot(lshift(mask1, field))
return band(n, mask) + lshift(v, field)
end
local replace = M.replace
function M.bswap(x) -- BitOp style
local a = band(x, 0xff); x = rshift(x, 8)
local b = band(x, 0xff); x = rshift(x, 8)
local c = band(x, 0xff); x = rshift(x, 8)
local d = band(x, 0xff)
return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d
end
local bswap = M.bswap
function M.rrotate(x, disp) -- Lua5.2 inspired
disp = disp % 32
local low = band(x, 2^disp-1)
return rshift(x, disp) + lshift(low, 32-disp)
end
local rrotate = M.rrotate
function M.lrotate(x, disp) -- Lua5.2 inspired
return rrotate(x, -disp)
end
local lrotate = M.lrotate
M.rol = M.lrotate -- LuaOp inspired
M.ror = M.rrotate -- LuaOp insipred
function M.arshift(x, disp) -- Lua5.2 inspired
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
local arshift = M.arshift
function M.btest(x, y) -- Lua5.2 inspired
return band(x, y) ~= 0
end
--
-- Start Lua 5.2 "bit32" compat section.
--
M.bit32 = {} -- Lua 5.2 'bit32' compatibility
local function bit32_bnot(x)
return (-1 - x) % MOD
end
M.bit32.bnot = bit32_bnot
local function bit32_bxor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = bxor(a, b)
if c then
z = bit32_bxor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bxor = bit32_bxor
local function bit32_band(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = ((a+b) - bxor(a,b)) / 2
if c then
z = bit32_band(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return MODM
end
end
M.bit32.band = bit32_band
local function bit32_bor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = MODM - band(MODM - a, MODM - b)
if c then
z = bit32_bor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bor = bit32_bor
function M.bit32.btest(...)
return bit32_band(...) ~= 0
end
function M.bit32.lrotate(x, disp)
return lrotate(x % MOD, disp)
end
function M.bit32.rrotate(x, disp)
return rrotate(x % MOD, disp)
end
function M.bit32.lshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return lshift(x % MOD, disp)
end
function M.bit32.rshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return rshift(x % MOD, disp)
end
function M.bit32.arshift(x,disp)
x = x % MOD
if disp >= 0 then
if disp > 31 then
return (x >= 0x80000000) and MODM or 0
else
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
else
return lshift(x, -disp)
end
end
function M.bit32.extract(x, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
return extract(x, field, ...)
end
function M.bit32.replace(x, v, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
v = v % MOD
return replace(x, v, field, ...)
end
--
-- Start LuaBitOp "bit" compat section.
--
M.bit = {} -- LuaBitOp "bit" compatibility
function M.bit.tobit(x)
x = x % MOD
if x >= 0x80000000 then x = x - MOD end
return x
end
local bit_tobit = M.bit.tobit
function M.bit.tohex(x, ...)
return tohex(x % MOD, ...)
end
function M.bit.bnot(x)
return bit_tobit(bnot(x % MOD))
end
local function bit_bor(a, b, c, ...)
if c then
return bit_bor(bit_bor(a, b), c, ...)
elseif b then
return bit_tobit(bor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bor = bit_bor
local function bit_band(a, b, c, ...)
if c then
return bit_band(bit_band(a, b), c, ...)
elseif b then
return bit_tobit(band(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.band = bit_band
local function bit_bxor(a, b, c, ...)
if c then
return bit_bxor(bit_bxor(a, b), c, ...)
elseif b then
return bit_tobit(bxor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bxor = bit_bxor
function M.bit.lshift(x, n)
return bit_tobit(lshift(x % MOD, n % 32))
end
function M.bit.rshift(x, n)
return bit_tobit(rshift(x % MOD, n % 32))
end
function M.bit.arshift(x, n)
return bit_tobit(arshift(x % MOD, n % 32))
end
function M.bit.rol(x, n)
return bit_tobit(lrotate(x % MOD, n % 32))
end
function M.bit.ror(x, n)
return bit_tobit(rrotate(x % MOD, n % 32))
end
function M.bit.bswap(x)
return bit_tobit(bswap(x % MOD))
end
return M
| mit |
Sponk/NeoEditor | SDK/LuaApi/ThemedButton.lua | 1 | 1349 | dofile("Button.lua")
--- The ThemedButton class
-- The ThemedButton class contains primitives to display and configure
-- UI based buttons. You can specify a callback that will be called when the button is pressed.
-- This version of a button is themable, i.e. it loads sprites and displays them
-- instead of using plain colors.
--
-- See also: <a href="Widget.lua.html">Widget</a>
-- See also: <a href="Button.lua.html">Button</a>
--
-- Example:
-- /code
-- -- The button callback
-- function button_callback()
-- print("Button pressed!")
-- end
--
-- -- Create a button
-- button = ThemedButton(10, 10, 100, 20, "This is a button!", "button_callback")
--
-- -- Add it to the main canvas
-- mainCanvas:addWidget(button)
-- /endcode
--- ThemedButton(x,y,w,h,text,callback)
-- Creates a new button.
-- @param x The x position on the canvas
-- @param y The y position on the canvas
-- @param w The width of the widget
-- @param h The height of the widget
-- @param text The label of the widget
-- @param callback (optional) The callback of the button
ThemedButton = class(
Button,
function(object, x, y, w, h, text, callback)
if text == nil then text = "" end
object.widget = createThemedButton(x,y,w,h,text,callback)
object.position = {x,y}
object.width = w
object.height = h
object.rotation = 0
object.visible = true
end)
| gpl-2.0 |
nimaghorbani/telenima2 | plugins/linkpv.lua | 1 | 31162 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
if success == -1 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' then
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'rem' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local receiver = 'user#id'..msg.action.user.id
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return false
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id)
send_large_msg(receiver, rules)
end
if matches[1] == 'chat_del_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and matches[2] then
if not is_owner(msg) then
return "Only owner can promote"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'newlink' then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'linkpv' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
send_large_msg('user#id'..msg.from.id, "Group link:\n"..group_link)
end
if matches[1] == 'setowner' then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'help' then
if not is_momod(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
end
return {
patterns = {
"^([Ll]inkpv)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
--Iwas Lazy So I Just Removed Patterns And Didn't Del Junk Items
--https://github.com/ThisIsArman
--Telegram.me/ThisIsArman
| gpl-2.0 |
helkarakse/TickProfilerDisplay | src/startup/marketStartup.lua | 2 | 1478 | --[[
MacroStartup Version 1.1 Beta
Do not modify, copy or distribute without permission of author
Helkarakse, 20130614
Changelog:
- 1.1 - Changed the startup code to pull latest copy from github instead of private server, 20131202
]]--
-- File array of github links
local fileArray = {
{link = "https://raw.github.com/helkarakse/LuaLibs/master/src/common/functions.lua", file = "functions"},
{link = "https://raw.github.com/helkarakse/LuaLibs/master/src/libs/libJson.lua", file = "json"},
{link = "https://raw.github.com/helkarakse/LuaLibs/master/src/parser/tickParser.lua", file = "parser"},
{link = "https://raw.github.com/helkarakse/TickProfilerDisplay/master/src/board/market.lua", file = "market"}
}
-- This filename is the file that will be executed
local indexFile = "market"
-- Set to true to overwrite files
local overwrite = true
-- Helper function to pull latest file from server
local function getProgram(link, filename)
print("Downloading '" .. filename .. "' file from server.")
-- remove the file if override is true
if (overwrite == true) then
shell.run("rm " .. filename)
end
-- get the latest copy
local data = http.get(link)
if data then
print("File '" .. filename .. "' download complete.")
local file = fs.open(filename,"w")
file.write(data.readAll())
file.close()
end
end
-- download and start program
for i = 1, #fileArray do
getProgram(fileArray[i].link, fileArray[i].file)
end
shell.run(indexFile) | gpl-2.0 |
RicoP/vlcfork | share/lua/sd/jamendo.lua | 58 | 6732 | --[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 at videolan dot org>
Rémi Duraffort <ivoire at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function descriptor()
return { title="Jamendo Selections" }
end
function main()
add_top_tracks( "ratingweek_desc", "rock", 100 )
add_top_tracks( "ratingweek_desc", "pop", 100 )
add_top_tracks( "ratingweek_desc", "jazz", 100 )
add_top_tracks( "ratingweek_desc", "dance", 100 )
add_top_tracks( "ratingweek_desc", "hipop+rap", 100 )
add_top_tracks( "ratingweek_desc", "world+reggae", 100 )
add_top_tracks( "ratingweek_desc", "lounge+ambient", 100 )
add_top_tracks( "ratingweek_desc", nil, 100 )
add_top_albums( "ratingweek_desc", nil, 20 )
add_radio_from_id( "9", 20 )
add_radio_from_id( "8", 20 )
add_radio_from_id( "6", 20 )
add_radio_from_id( "5", 20 )
add_radio_from_id( "7", 20 )
add_radio_from_id( "4", 20 )
end
function add_top_albums( album_order, tag, max_results )
local url = "http://api.jamendo.com/get2/id+name+artist_name+album_image/album/xml/?imagesize=500&order=" .. album_order .. "&n=" .. max_results
if tag ~= nil then
url = url .. "&tag_idstr=" .. tag
end
local tree = simplexml.parse_url( url )
local node_name = "Top " .. max_results
if album_order == "rating_desc" then node_name = node_name .. " most popular albums"
elseif album_order == "ratingmonth_desc" then node_name = node_name .. " most popular albums this month"
elseif album_order == "ratingweek_desc" then node_name = node_name .. " most popular albums this week"
elseif album_order == "releasedate_desc" then node_name = node_name .. " latest released albums"
elseif album_order == "downloaded_desc" then node_name = node_name .. " most downloaded albums"
elseif album_order == "listened_desc" then node_name = node_name .. " most listened to albums"
elseif album_order == "starred_desc" then node_name = node_name .. " most starred albums"
elseif album_order == "playlisted_desc" then node_name = node_name .. " most playlisted albums"
elseif album_order == "needreviews_desc" then node_name = node_name .. " albums requiring review"
end
if tag ~= nil then
node_name = tag .. " - " .. node_name
end
local node = vlc.sd.add_node( {title=node_name} )
for _, album in ipairs( tree.children ) do
simplexml.add_name_maps( album )
local album_node = node:add_subitem(
{ path = 'http://api.jamendo.com/get2/id+name+duration+artist_name+album_name+album_genre+album_dates+album_image/track/xml/track_album+album_artist/?album_id=' .. album.children_map["id"][1].children[1],
title = album.children_map["artist_name"][1].children[1] .. ' - ' .. album.children_map["name"][1].children[1],
arturl = album.children_map["album_image"][1].children[1] })
end
end
function add_top_tracks( track_order, tag, max_results )
local url = "http://api.jamendo.com/get2/id+name+duration+artist_name+album_name+genre+album_image+album_dates/track/xml/track_album+album_artist/?imagesize=500&order=" .. track_order .. "&n=" .. max_results
if tag ~= nil then
url = url .. "&tag_minweight=0.35&tag_idstr=" .. tag
end
local tree = simplexml.parse_url( url )
local node_name = "Top " .. max_results
if track_order == "rating_desc" then node_name = node_name .. " most popular tracks"
elseif track_order == "ratingmonth_desc" then node_name = node_name .. " most popular tracks this month"
elseif track_order == "ratingweek_desc" then node_name = node_name .. " most popular tracks this week"
elseif track_order == "releasedate_desc" then node_name = node_name .. " latest released tracks"
elseif track_order == "downloaded_desc" then node_name = node_name .. " most downloaded tracks"
elseif track_order == "listened_desc" then node_name = node_name .. " most listened to tracks"
elseif track_order == "starred_desc" then node_name = node_name .. " most starred tracks"
elseif track_order == "playlisted_desc" then node_name = node_name .. " most playlisted tracks"
elseif track_order == "needreviews_desc" then node_name = node_name .. " tracks requiring review"
end
if tag ~= nil then
node_name = string.upper(tag) .. " - " .. node_name
end
local node = vlc.sd.add_node( {title=node_name} )
for _, track in ipairs( tree.children ) do
simplexml.add_name_maps( track )
node:add_subitem( {path="http://api.jamendo.com/get2/stream/track/redirect/?id=" .. track.children_map["id"][1].children[1],
title=track.children_map["artist_name"][1].children[1].." - "..track.children_map["name"][1].children[1],
artist=track.children_map["artist_name"][1].children[1],
album=track.children_map["album_name"][1].children[1],
genre=track.children_map["genre"][1].children[1],
date=track.children_map["album_dates"][1].children_map["year"][1].children[1],
arturl=track.children_map["album_image"][1].children[1],
duration=track.children_map["duration"][1].children[1]} )
end
end
function add_radio_from_id( id, max_results )
local radio_name
if id == "9" then radio_name="Rock"
elseif id == "8" then radio_name="Pop / Songwriting"
elseif id == "6" then radio_name="Jazz"
elseif id == "5" then radio_name="Hip-Hop"
elseif id == "7" then radio_name="Lounge"
elseif id == "4" then radio_name="Dance / Electro"
end
vlc.sd.add_item( {path="http://api.jamendo.com/get2/id+name+artist_name+album_name+duration+album_genre+album_image+album_dates/track/xml/radio_track_inradioplaylist+track_album+album_artist/?imagesize=500&order=random_desc&radio_id=" .. id .. "&n=" .. max_results,
title=radio_name} )
end
| gpl-2.0 |
gitTerebi/OpenRA | mods/cnc/maps/gdi05a/gdi05a.lua | 19 | 6681 | RepairThreshold = { Easy = 0.3, Normal = 0.6, Hard = 0.9 }
ActorRemovals =
{
Easy = { Actor167, Actor168, Actor190, Actor191, Actor193, Actor194, Actor196, Actor198, Actor200 },
Normal = { Actor167, Actor194, Actor196, Actor197 },
Hard = { },
}
GdiTanks = { "mtnk", "mtnk" }
GdiApc = { "apc" }
GdiInfantry = { "e1", "e1", "e1", "e1", "e1", "e2", "e2", "e2", "e2", "e2" }
GdiBase = { GdiNuke1, GdiNuke2, GdiProc, GdiSilo1, GdiSilo2, GdiPyle, GdiWeap, GdiHarv }
NodSams = { Sam1, Sam2, Sam3, Sam4 }
CoreNodBase = { NodConYard, NodRefinery, HandOfNod, Airfield }
Grd1UnitTypes = { "bggy" }
Grd1Path = { waypoint4.Location, waypoint5.Location, waypoint10.Location }
Grd1Delay = { Easy = DateTime.Minutes(2), Normal = DateTime.Minutes(1), Hard = DateTime.Seconds(30) }
Grd2UnitTypes = { "bggy" }
Grd2Path = { waypoint0.Location, waypoint1.Location, waypoint2.Location }
Grd3Units = { GuardTank1, GuardTank2 }
Grd3Path = { waypoint4.Location, waypoint5.Location, waypoint9.Location }
AttackDelayMin = { Easy = DateTime.Minutes(1), Normal = DateTime.Seconds(45), Hard = DateTime.Seconds(30) }
AttackDelayMax = { Easy = DateTime.Minutes(2), Normal = DateTime.Seconds(90), Hard = DateTime.Minutes(1) }
AttackUnitTypes =
{
Easy =
{
{ HandOfNod, { "e1", "e1" } },
{ HandOfNod, { "e1", "e3" } },
{ HandOfNod, { "e1", "e1", "e3" } },
{ HandOfNod, { "e1", "e3", "e3" } },
},
Normal =
{
{ HandOfNod, { "e1", "e1", "e3" } },
{ HandOfNod, { "e1", "e3", "e3" } },
{ HandOfNod, { "e1", "e1", "e3", "e3" } },
{ Airfield, { "bggy" } },
},
Hard =
{
{ HandOfNod, { "e1", "e1", "e3", "e3" } },
{ HandOfNod, { "e1", "e1", "e1", "e3", "e3" } },
{ HandOfNod, { "e1", "e1", "e3", "e3", "e3" } },
{ Airfield, { "bggy" } },
{ Airfield, { "ltnk" } },
}
}
AttackPaths =
{
{ waypoint0.Location, waypoint1.Location, waypoint2.Location, waypoint3.Location },
{ waypoint4.Location, waypoint9.Location, waypoint7.Location, waypoint8.Location },
}
Build = function(factory, units, action)
if factory.IsDead or factory.Owner ~= nod then
return
end
if not factory.Build(units, action) then
Trigger.AfterDelay(DateTime.Seconds(5), function()
Build(factory, units, action)
end)
end
end
Attack = function()
local types = Utils.Random(AttackUnitTypes[Map.Difficulty])
local path = Utils.Random(AttackPaths)
Build(types[1], types[2], function(units)
Utils.Do(units, function(unit)
if unit.Owner ~= nod then return end
unit.Patrol(path, false)
Trigger.OnIdle(unit, unit.Hunt)
end)
end)
Trigger.AfterDelay(Utils.RandomInteger(AttackDelayMin[Map.Difficulty], AttackDelayMax[Map.Difficulty]), Attack)
end
Grd1Action = function()
Build(Airfield, Grd1UnitTypes, function(units)
Utils.Do(units, function(unit)
if unit.Owner ~= nod then return end
Trigger.OnKilled(unit, function()
Trigger.AfterDelay(Grd1Delay[Map.Difficulty], Grd1Action)
end)
unit.Patrol(Grd1Path, true, DateTime.Seconds(7))
end)
end)
end
Grd2Action = function()
Build(Airfield, Grd2UnitTypes, function(units)
Utils.Do(units, function(unit)
if unit.Owner ~= nod then return end
unit.Patrol(Grd2Path, true, DateTime.Seconds(5))
end)
end)
end
Grd3Action = function()
local unit
for i, u in ipairs(Grd3Units) do
if not u.IsDead then
unit = u
break
end
end
if unit ~= nil then
Trigger.OnKilled(unit, function()
Grd3Action()
end)
unit.Patrol(Grd3Path, true, DateTime.Seconds(11))
end
end
DiscoverGdiBase = function(actor, discoverer)
if baseDiscovered or not discoverer == gdi then
return
end
Utils.Do(GdiBase, function(actor)
actor.Owner = gdi
end)
GdiHarv.FindResources()
baseDiscovered = true
gdiObjective3 = gdi.AddPrimaryObjective("Eliminate all Nod forces in the area.")
gdi.MarkCompletedObjective(gdiObjective1)
Attack()
end
SetupWorld = function()
Utils.Do(ActorRemovals[Map.Difficulty], function(unit)
unit.Destroy()
end)
Media.PlaySpeechNotification(gdi, "Reinforce")
Reinforcements.Reinforce(gdi, GdiTanks, { GdiTankEntry.Location, GdiTankRallyPoint.Location }, DateTime.Seconds(1), function(actor) actor.Stance = "Defend" end)
Reinforcements.Reinforce(gdi, GdiApc, { GdiApcEntry.Location, GdiApcRallyPoint.Location }, DateTime.Seconds(1), function(actor) actor.Stance = "Defend" end)
Reinforcements.Reinforce(gdi, GdiInfantry, { GdiInfantryEntry.Location, GdiInfantryRallyPoint.Location }, 15, function(actor) actor.Stance = "Defend" end)
Trigger.OnPlayerDiscovered(gdiBase, DiscoverGdiBase)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == nod and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == nod and building.Health < RepairThreshold[Map.Difficulty] * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
Trigger.OnAllKilled(NodSams, function()
gdi.MarkCompletedObjective(gdiObjective2)
Actor.Create("airstrike.proxy", true, { Owner = gdi })
end)
GdiHarv.Stop()
NodHarv.FindResources()
if Map.Difficulty ~= "Easy" then
Trigger.OnDamaged(NodHarv, function()
Utils.Do(nod.GetGroundAttackers(), function(unit)
unit.AttackMove(NodHarv.Location)
if Map.Difficulty == "Hard" then
unit.Hunt()
end
end)
end)
end
Trigger.AfterDelay(DateTime.Seconds(45), Grd1Action)
Trigger.AfterDelay(DateTime.Minutes(3), Grd2Action)
Grd3Action()
end
WorldLoaded = function()
gdiBase = Player.GetPlayer("AbandonedBase")
gdi = Player.GetPlayer("GDI")
nod = Player.GetPlayer("Nod")
Trigger.OnObjectiveAdded(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(gdi, function()
Media.PlaySpeechNotification(player, "Lose")
end)
Trigger.OnPlayerWon(gdi, function()
Media.PlaySpeechNotification(player, "Win")
end)
nodObjective = nod.AddPrimaryObjective("Destroy all GDI troops.")
gdiObjective1 = gdi.AddPrimaryObjective("Find the GDI base.")
gdiObjective2 = gdi.AddSecondaryObjective("Destroy all SAM sites to receive air support.")
SetupWorld()
Camera.Position = GdiTankRallyPoint.CenterPosition
end
Tick = function()
if gdi.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
nod.MarkCompletedObjective(nodObjective)
end
end
if baseDiscovered and nod.HasNoRequiredUnits() then
gdi.MarkCompletedObjective(gdiObjective3)
end
end | gpl-3.0 |
pins-ocs/OCP-tests | test-gtocX_2burn_pars/data/gtocX_2burn_pars_Data.lua | 1 | 4709 | --[[
/*-----------------------------------------------------------------------*\
| file: gtocX_2burn_pars_Data.lua |
| |
| version: 1.0 date 28/3/2020 |
| |
| Copyright (C) 2020 |
| |
| Enrico Bertolazzi, Francesco Biral and Paolo Bosetti |
| Dipartimento di Ingegneria Industriale |
| Universita` degli Studi di Trento |
| Via Sommarive 9, I-38123, Trento, Italy |
| email: enrico.bertolazzi@unitn.it |
| francesco.biral@unitn.it |
| paolo.bosetti@unitn.it |
\*-----------------------------------------------------------------------*/
--]]
-- Auxiliary values
ray_epsi = 0.001
ray_tol = 0.001
content = {
-- Level of message
InfoLevel = 4,
-- maximum number of threads used for linear algebra and various solvers
N_threads = 4,
U_threaded = true,
F_threaded = true,
JF_threaded = true,
LU_threaded = true,
-- Enable doctor
Doctor = false,
-- Enable check jacobian
JacobianCheck = false,
JacobianCheckFull = false,
JacobianCheck_epsilon = 1e-4,
FiniteDifferenceJacobian = false,
-- Redirect output to GenericContainer["stream_output"]
RedirectStreamToString = false,
-- Dump Function and Jacobian if uncommented
-- DumpFile = "gtocX_2burn_pars_dump",
-- spline output (all values as function of "s")
-- OutputSplines = [0],
-- Redirect output to GenericContainer["stream_output"]
RedirectStreamToString = false,
ControlSolver = {
-- "LU", "LUPQ", "QR", "QRP", "SVD", "LSS", "LSY", "MINIMIZATION"
factorization = "LU",
MaxIter = 50,
Tolerance = 1e-9,
Iterative = false,
InfoLevel = -1 -- suppress all messages
},
-- setup solver
Solver = {
-- Linear algebra factorization selection:
-- "LU", "QR", "QRP", "SUPERLU"
factorization = "LU",
-- Last Block selection:
-- "LU", "LUPQ", "QR", "QRP", "SVD", "LSS", "LSY"
last_factorization = "LU",
-- choose solves: Hyness, NewtonDumped
solver = "Hyness",
-- solver parameters
max_iter = 300,
max_step_iter = 40,
max_accumulated_iter = 800,
tolerance = 9.999999999999999e-10,
-- continuation parameters
ns_continuation_begin = 0,
ns_continuation_end = 2,
continuation = {
initial_step = 0.2, -- initial step for continuation
min_step = 0.001, -- minimum accepted step for continuation
reduce_factor = 0.5, -- if continuation step fails, reduce step by this factor
augment_factor = 1.5, -- if step successful in less than few_iteration augment step by this factor
few_iterations = 8
}
},
-- Boundary Conditions (SET/FREE)
BoundaryConditions = {
initial_x = SET,
initial_y = SET,
initial_z = SET,
final_x = SET,
final_y = SET,
final_z = SET,
},
-- Guess
Guess = {
-- possible value: zero, default, none, warm
initialize = "zero",
-- possible value: default, none, warm, spline, table
guess_type = "default"
},
Parameters = {
-- Model Parameters
muS = 0.575874,
time_f = 27,
time_i = 0,
w_guess = 0,
w_nonlin = 0,
-- Guess Parameters
-- Boundary Conditions
retrograde = -1,
-- Post Processing Parameters
-- User Function Parameters
epsi_norm = 0.01,
-- Continuation Parameters
-- Constraints Parameters
},
-- functions mapped objects
MappedObjects = {
},
-- Controls: No penalties or barriers constraint defined
Constraints = {
-- Constraint1D
-- Penalty subtype: "PENALTY_REGULAR", "PENALTY_SMOOTH", "PENALTY_PIECEWISE"
-- Barrier subtype: "BARRIER_LOG", "BARRIER_LOG_EXP", "BARRIER_LOG0"
-- PenaltyBarrier1DGreaterThan
ray_positivesubType = "BARRIER_LOG",
ray_positiveepsilon = ray_epsi,
ray_positivetolerance = ray_tol,
ray_positiveactive = true
-- Constraint2D: none defined
},
-- User defined classes initialization
-- User defined classes: M E S H
Mesh =
{
s0 = 0,
segments = {
{
n = 50,
length = 1,
},
},
},
}
-- EOF
| gpl-2.0 |
wiox/archive | gmod-defibrillator-master/lua/weapons/weapon_ttt_defib.lua | 2 | 6252 | if SERVER then
resource.AddFile("materials/vgui/ttt/icon_rg_defibrillator.png")
end
local STATE_NONE, STATE_PROGRESS, STATE_ERROR = 0, 1, 2
local color_red = Color(255, 0, 0)
SWEP.Base = "weapon_tttbase"
SWEP.HoldType = "slam"
SWEP.ViewModel = Model("models/weapons/v_c4.mdl")
SWEP.WorldModel = Model("models/weapons/w_c4.mdl")
--- TTT Vars
SWEP.Kind = WEAPON_EQUIP2
SWEP.AutoSpawnable = false
SWEP.CanBuy = {ROLE_TRAITOR}
SWEP.LimitedStock = true
if CLIENT then
SWEP.PrintName = "Defibrillator"
SWEP.Slot = 7
SWEP.Icon = "vgui/ttt/icon_rg_defibrillator.png"
SWEP.EquipMenuData = {
type = "item_weapon",
name = "Defribrillator",
desc = "Resurrect dead mates with this one!"
}
surface.CreateFont("DefibText", {
font = "Tahoma",
size = 13,
weight = 700,
shadow = true
})
function SWEP:DrawHUD()
local state = self:GetDefibState()
local scrW, scrH = ScrW(), ScrH()
local progress = 1
local outlineCol, progressCol, progressText = color_white, color_white, ""
if state == STATE_PROGRESS then
local startTime, endTime = self:GetDefibStartTime(), self:GetDefibStartTime() + 5
progress = math.TimeFraction(startTime, endTime, CurTime())
if progress <= 0 then
return
end
outlineCol = Color(0, 100, 0)
progressCol = Color(0, 255, 0, (math.abs(math.sin(RealTime() * 3)) * 100) + 20)
progressText = self:GetStateText() or "DEFIBRILLATING"
elseif state == STATE_ERROR then
outlineCol = color_red
progressCol = Color(255, 0, 0, math.abs(math.sin(RealTime() * 15)) * 255)
progressText = self:GetStateText() or ""
else
return
end
progress = math.Clamp(progress, 0, 1)
surface.SetDrawColor(outlineCol)
surface.DrawOutlinedRect(scrW / 2 - (200 / 2) - 1, scrH / 2 + 10 - 1, 202, 16)
surface.SetDrawColor(progressCol)
surface.DrawRect(scrW / 2 - (200 / 2), scrH / 2 + 10, 200 * progress, 14)
surface.SetFont("DefibText")
local textW, textH = surface.GetTextSize(progressText)
surface.SetTextPos(scrW / 2 - 100 + 2, scrH / 2 - 20 + textH)
surface.SetTextColor(color_white)
surface.DrawText(progressText)
end
end
function SWEP:SetupDataTables()
self:NetworkVar("Int", 0, "DefibState")
self:NetworkVar("Float", 1, "DefibStartTime")
self:NetworkVar("String", 0, "StateText")
end
function SWEP:Initialize()
self:SetDefibState(STATE_NONE)
self:SetDefibStartTime(0)
end
function SWEP:Deploy()
self:SetDefibState(STATE_NONE)
self:SetDefibStartTime(0)
return true
end
function SWEP:Holster()
self:SetDefibState(STATE_NONE)
self:SetDefibStartTime(0)
return true
end
function SWEP:PrimaryAttack()
if CLIENT then return end
local tr = util.TraceLine({
start = self.Owner:EyePos(),
endpos = self.Owner:EyePos() + self.Owner:GetAimVector() * 80,
filter = self.Owner
})
if IsValid(tr.Entity) and tr.Entity:GetClass() == "prop_ragdoll" then
if not tr.Entity.uqid then
self:FireError("FAILURE - SUBJECT BRAINDEAD")
return
end
local ply = player.GetByUniqueID(tr.Entity.uqid)
if IsValid(ply) then
self:BeginDefib(ply, tr.Entity)
else
self:FireError("FAILURE - SUBJECT BRAINDEAD")
return
end
else
self:FireError("FAILURE - INVALID TARGET")
end
end
function SWEP:BeginDefib(ply, ragdoll)
local spawnPos = self:FindPosition(self.Owner)
if not spawnPos then
self:FireError("FAILURE - INSUFFICIENT ROOM")
return
end
self:SetStateText("DEFIBRILLATING - "..string.upper(ply:Name()))
self:SetDefibState(STATE_PROGRESS)
self:SetDefibStartTime(CurTime())
self.TargetPly = ply
self.TargetRagdoll = ragdoll
self:SetNextPrimaryFire(CurTime() + 6)
end
function SWEP:FireError(err)
if err then
self:SetStateText(err)
else
self:SetStateText("")
end
self:SetDefibState(STATE_ERROR)
timer.Simple(1, function()
if IsValid(self) then
self:SetDefibState(STATE_NONE)
self:SetStateText("")
end
end)
self:SetNextPrimaryFire(CurTime() + 1.2)
end
function SWEP:FireSuccess()
self:SetDefibState(STATE_NONE)
self:SetNextPrimaryFire(CurTime() + 1)
hook.Call("UsedDefib", GAMEMODE, self.Owner)
self:Remove()
end
function SWEP:Think()
if CLIENT then return end
if self:GetDefibState() == STATE_PROGRESS then
if not IsValid(self.Owner) then
self:FireError()
return
end
if not (IsValid(self.TargetPly) and IsValid(self.TargetRagdoll)) then
self:FireError("ERROR - SUBJECT BRAINDEAD")
return
end
local tr = util.TraceLine({
start = self.Owner:EyePos(),
endpos = self.Owner:EyePos() + self.Owner:GetAimVector() * 80,
filter = self.Owner
})
if tr.Entity ~= self.TargetRagdoll then
self:FireError("ERROR - TARGET LOST")
return
end
if CurTime() >= self:GetDefibStartTime() + 5 then
if self:HandleRespawn() then
self:FireSuccess()
else
self:FireError("ERROR - INSUFFICIENT ROOM")
return
end
end
self:NextThink(CurTime())
return true
end
end
function SWEP:HandleRespawn()
local ply, ragdoll = self.TargetPly, self.TargetRagdoll
local spawnPos = self:FindPosition(self.Owner)
if not spawnPos then
return false
end
local credits = CORPSE.GetCredits(ragdoll, 0)
ply:SpawnForRound(true)
ply:SetCredits(credits)
ply:SetPos(spawnPos)
ply:SetEyeAngles(Angle(0, ragdoll:GetAngles().y, 0))
ragdoll:Remove()
return true
end
local Positions = {}
for i=0,360,22.5 do table.insert( Positions, Vector(math.cos(i),math.sin(i),0) ) end -- Populate Around Player
table.insert(Positions, Vector(0, 0, 1)) -- Populate Above Player
function SWEP:FindPosition(ply)
local size = Vector(32, 32, 72)
local StartPos = ply:GetPos() + Vector(0, 0, size.z/2)
local len = #Positions
for i = 1, len do
local v = Positions[i]
local Pos = StartPos + v * size * 1.5
local tr = {}
tr.start = Pos
tr.endpos = Pos
tr.mins = size / 2 * -1
tr.maxs = size / 2
local trace = util.TraceHull(tr)
if(not trace.Hit) then
return Pos - Vector(0, 0, size.z/2)
end
end
return false
end
| unlicense |
pchote/OpenRA | mods/d2k/maps/atreides-02b/atreides02b.lua | 2 | 2641 | --[[
Copyright 2007-2021 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you 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. For more
information, see COPYING.
]]
HarkonnenBase = { HConyard, HOutpost, HBarracks }
HarkonnenReinforcements =
{
easy =
{
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" }
},
normal =
{
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" }
},
hard =
{
{ "trike", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf" },
{ "trike", "trike" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
{ "trike", "trike" }
}
}
HarkonnenAttackPaths =
{
{ HarkonnenEntry1.Location, HarkonnenRally1.Location },
{ HarkonnenEntry1.Location, HarkonnenRally3.Location },
{ HarkonnenEntry2.Location, HarkonnenRally2.Location },
{ HarkonnenEntry2.Location, HarkonnenRally4.Location }
}
HarkonnenAttackDelay =
{
easy = DateTime.Minutes(5),
normal = DateTime.Minutes(2) + DateTime.Seconds(40),
hard = DateTime.Minutes(1) + DateTime.Seconds(20)
}
HarkonnenAttackWaves =
{
easy = 3,
normal = 6,
hard = 9
}
Tick = function()
if player.HasNoRequiredUnits() then
harkonnen.MarkCompletedObjective(KillAtreides)
end
if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then
Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat")
player.MarkCompletedObjective(KillHarkonnen)
end
end
WorldLoaded = function()
harkonnen = Player.GetPlayer("Harkonnen")
player = Player.GetPlayer("Atreides")
InitObjectives(player)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.")
KillHarkonnen = player.AddPrimaryObjective("Destroy all Harkonnen forces.")
Camera.Position = AConyard.CenterPosition
Trigger.OnAllKilled(HarkonnenBase, function()
Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt)
end)
local path = function() return Utils.Random(HarkonnenAttackPaths) end
SendCarryallReinforcements(harkonnen, 0, HarkonnenAttackWaves[Difficulty], HarkonnenAttackDelay[Difficulty], path, HarkonnenReinforcements[Difficulty])
Trigger.AfterDelay(0, ActivateAI)
end
| gpl-3.0 |
pchote/OpenRA | mods/d2k/maps/ordos-03a/ordos03a-AI.lua | 4 | 1862 | --[[
Copyright 2007-2021 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you 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. For more
information, see COPYING.
]]
AttackGroupSize =
{
easy = 6,
normal = 8,
hard = 10
}
AttackDelays =
{
easy = { DateTime.Seconds(4), DateTime.Seconds(9) },
normal = { DateTime.Seconds(2), DateTime.Seconds(7) },
hard = { DateTime.Seconds(1), DateTime.Seconds(5) }
}
HarkonnenInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper" }
HarkonnenVehicleTypes = { "trike", "trike", "quad" }
InitAIUnits = function()
IdlingUnits[harkonnen] = Reinforcements.Reinforce(harkonnen, HarkonnenInitialReinforcements, HarkonnenInitialPath)
DefendAndRepairBase(harkonnen, HarkonnenBase, 0.75, AttackGroupSize[Difficulty])
end
ActivateAI = function()
LastHarvesterEaten[harkonnen] = true
Trigger.AfterDelay(0, InitAIUnits)
HConyard.Produce(OrdosUpgrades[1])
HConyard.Produce(OrdosUpgrades[2])
local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end
local infantryToBuild = function() return { Utils.Random(HarkonnenInfantryTypes) } end
local vehilcesToBuild = function() return { Utils.Random(HarkonnenVehicleTypes) } end
local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5
-- Finish the upgrades first before trying to build something
Trigger.AfterDelay(DateTime.Seconds(14), function()
ProduceUnits(harkonnen, HBarracks, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
ProduceUnits(harkonnen, HLightFactory, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
end)
end
| gpl-3.0 |
ahmedcharles/Mudlet | src/mudlet-lua/lua/geyser/GeyserTests.lua | 22 | 5965 | --------------------------------------
-- --
-- The Geyser Layout Manager by guy --
-- --
--------------------------------------
-- TESTS FOR GEYSER --
--- Test labels. Creates 101 Labels of varying hue and transparency.
function Geyser.testLabels()
labelTestContainer = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="labelTestContainer"})
for i=0,90,10 do
for j=0,90,10 do
local myName = "TestLabel_" .. i .. "_" .. j
local l = Geyser.Label:new({
name = myName,
x = i .. "%", y = j .. "%",
width = "8%", height = "8%",
message = myName,
fgColor = "white"},
labelTestContainer)
l:setColor(i,j,100, i*j/8100 * 128 + 127)
end
end
Geyser.Label:new({
name = "Clickable",
fontSize = 22,
message = [[<p style="font-size:22pt"><center>Click me</center></p>]],
x = "53%", y = "53%",
width = "-40px", height = "-3c",
backgroundAlpha = 240,
callback = "echo",
args = "You Clicked Me!!\n"},
labelTestContainer)
end
--- Test gauges. Creates 100 gauges of varying fullness.
function Geyser.testGauges()
gaugeTestContainer = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="gaugeTestContainer"})
for i=0,90,10 do
for j=0,90,10 do
local myName = "TestGauge_" .. i .. "_" .. j
local g = Geyser.Gauge:new({name = myName, x = i .. "%", y = j .. "%", width = "9%", height = "9%",
message = myName, fgColor = "red",},
gaugeTestContainer)
g:setValue(1.0 * i)
--g:setText(myName)
end
end
end
--- Used by Geyser.demo1(). Sorry about the namespace polution,
-- but callbacks can't use functions contained in a table. Anyway,
-- it just echoes some status info to the two miniconsoles.
function demoCallback1 (value)
local g1 = geyserDemoContainer.windowList.myGauge
local g2 = geyserDemoContainer.windowList.myGoofyGauge
local c1 = geyserDemoContainer.windowList["console 1"]
local c2 = geyserDemoContainer.windowList["console 2"]
g1:setValue((g1.value - value) % 100)
g2:setValue((g2.value - 2*value) % 100)
local v1 = tostring(g1.value)
local v2 = tostring(g2.value)
c1:decho(string.format("<90,90,%d> You are at %d \n", v1, v1))
c2:decho(string.format("<90,%d,%d> You are at %d \n", 255-v2, v2, v2))
end
local myDemoState = 0
--- Used by Geyser.demo1(). It moves the location of the
-- container window. Look how easy it is to shift around all those
-- gui elements!
function demoCallback2 ()
if myDemoState == 0 then
geyserDemoContainer:resize(nil, "50%")
geyserDemoContainer:move("-90c")
myDemoState = 1
else
geyserDemoContainer:resize(nil, "100%")
geyserDemoContainer:move("-42c")
myDemoState = 0
end
end
--- This demonstrates some of the neat features in Geyser.
function Geyser.demo1()
----------------------------------------
-- 1. Create a container on the left side of the screen wide
-- enough for 40 characters
geyserDemoContainer = Geyser.Container:new(
{ x = "-42c", y = "0px",
width = "40c", height = "100%",
name = "myContainer"})
----------------------------------------
-- 2. Add a miniconsole to the top of the container,
-- full width, with 20 lines of text
local console1 = Geyser.MiniConsole:new(
{ x = "0px", y = "0px",
width = "100%", height = "20c",
name = "console 1"},
geyserDemoContainer) -- add console1 to container directly
console1:setColor(80,40,20,255)
console1:echo("Go ahead - resize the Mudlet window\n")
----------------------------------------
-- 3. Add two gauges and a clickable label just below the
-- miniconsole
local g1 = Geyser.Gauge:new(
{ x = "0px", y = console1.height,
width = "60%", height = "4c",
orientation = "batty", color = "violet",
name = "myGauge"})
g1:setValue(77)
geyserDemoContainer:add(g1) -- add gauge after creation
local g2 = Geyser.Gauge:new(
{ x = "10%", y = console1.height,
width = "50%", height = "4c",
orientation = "goofy",
name = "myGoofyGauge"}, geyserDemoContainer) -- add gauge directly
g2:setValue(55)
g2:setColor("cyan")
local label1 = Geyser.Label:new(
{ x = g1.width, y = console1.height,
width = "40%", height = "4c",
name = "label with callback",
callback = "demoCallback1",
args=5, fontSize = 8, fgColor = "white",
message = "Click me"})
geyserDemoContainer:add(label1) -- you know the drill
----------------------------------------
-- 4. Add another miniconsole below the gauge that extends
-- to the bottom of the screen and wraps at 40 characters and
-- another clickable label.
echo("adfa\n")
local console2 = Geyser.MiniConsole:new({
x = "0px", y = "24c",
width = "100%", height = "-0px",
name = "console 2",
wrapAt = 40,
color = "<10,20,40>",},
geyserDemoContainer) -- add console2 to geyserDemoContainer directly
console2:echo("Vampire Gauges!\n")
local label2 = Geyser.Label:new(
{ x = g1.width, y = "60%",
width = "40%", height = "4c",
name = "label with another callback and a long name!",
callback = "demoCallback2",
message = [[<center>and me</center>]]})
geyserDemoContainer:add(label2) -- same here
----------------------------------------
-- 5. hide all windows just created
geyserDemoContainer:hide()
----------------------------------------
-- 6. now show them again
geyserDemoContainer:show()
end
| gpl-2.0 |
artynet/luci | applications/luci-app-mwan3/luasrc/model/cbi/mwan/notify.lua | 7 | 1813 | -- Copyright 2014 Aedan Renner <chipdankly@gmail.com>
-- Copyright 2018 Florian Eckert <fe@dev.tdt.de>
-- Licensed to the public under the GNU General Public License v2.
local fs = require "nixio.fs"
local ut = require "luci.util"
local script = "/etc/mwan3.user"
local m, f, t
m = SimpleForm("luci", translate("MWAN - Notification"))
f = m:section(SimpleSection, nil,
translate("This section allows you to modify the content of \"/etc/mwan3.user\".<br />" ..
"The file is also preserved during sysupgrade.<br />" ..
"<br />" ..
"Notes:<br />" ..
"This file is interpreted as a shell script.<br />" ..
"The first line of the script must be "#!/bin/sh" without quotes.<br />" ..
"Lines beginning with # are comments and are not executed.<br />" ..
"Put your custom mwan3 action here, they will<br />" ..
"be executed with each netifd hotplug interface event<br />" ..
"on interfaces for which mwan3 is enabled.<br />" ..
"<br />" ..
"There are three main environment variables that are passed to this script.<br />" ..
"<br />" ..
"$ACTION <br />" ..
"* \"ifup\" Is called by netifd and mwan3track <br />" ..
"* \"ifdown\" Is called by netifd and mwan3track <br />" ..
"* \"connected\" Is only called by mwan3track if tracking was successful <br />" ..
"* \"disconnected\" Is only called by mwan3track if tracking has failed <br />" ..
"$INTERFACE Name of the interface which went up or down (e.g. \"wan\" or \"wwan\")<br />" ..
"$DEVICE Physical device name which interface went up or down (e.g. \"eth0\" or \"wwan0\")<br />" ..
"<br />"))
t = f:option(TextValue, "lines")
t.rmempty = true
t.rows = 20
function t.cfgvalue()
return fs.readfile(script)
end
function t.write(self, section, data)
return fs.writefile(script, ut.trim(data:gsub("\r\n", "\n")) .. "\n")
end
return m
| apache-2.0 |
timbeaudet/build_automation | build/make_project.lua | 1 | 4560 | --
-- Premake5 script for creating a Visual Studio, XCode or CodeLite workspace for the TEMPLATE_PROJECT_NAME project.
-- Requires Premake5 from: http://industriousone.com/
--
-- Available on github: https://www.github.com/timbeaudet/build_automation/ under the unliscense agreement.
-----------------------------------------------------------------------------------------------------------------------
newoption {
trigger = "web",
description = "Chosen build system to override for web.",
value = "",
}
--Documented at: http://industriousone.com/osget
local WINDOWS_SYSTEM_NAME = "windows"
local LINUX_SYSTEM_NAME = "linux"
local MACOSX_SYSTEM_NAME = "macosx"
local WEB_SYSTEM_NAME = "web"
--local MACIOS_SYSTEM_NAME = "macios"
--local ANDROID_SYSTEM_NAME = "android"
local PROJECT_NAME = "TEMPLATE_PROJECT_FILE"
local SYSTEM_NAME = os.target()
if _OPTIONS["web"] then
SYSTEM_NAME = WEB_SYSTEM_NAME
end
if _ACTION == "clean" then
os.rmdir("../build/" .. WINDOWS_SYSTEM_NAME)
os.rmdir("../build/" .. LINUX_SYSTEM_NAME)
os.rmdir("../build/" .. MACOSX_SYSTEM_NAME)
os.rmdir("../build/" .. WEB_SYSTEM_NAME)
end
local SCRIPT_EXTENSION = ".sh"
if (SYSTEM_NAME == WINDOWS_SYSTEM_NAME) then
SCRIPT_EXTENSION = ".bat"
end
solution(PROJECT_NAME)
location ("../build/" .. SYSTEM_NAME)
configurations { "debug", "release" }
project (PROJECT_NAME)
location ("../build/" .. SYSTEM_NAME)
language ("C++")
kind ("WindowedApp")
warnings ("Extra")
files { "../source/**.h", "../source/**.cpp", "../source/**.mm", "../source/**.c" }
excludes { "../**/doxygen/**" }
defines { "tb_without_networking", "tb_without_input_devices" }
includedirs {
"../build/tb_external_libraries/includes/"
}
----------------------------------------------------------------------- Windows Platform Specifics
if (WINDOWS_SYSTEM_NAME == SYSTEM_NAME) then
libdirs {
"../build/tb_external_libraries/libraries/msvc/x32",
"C:/Program Files (x86)/Windows Kits/10/Lib/10.0.14393.0/um/x86/" --for dxguid
}
--TODO: TIM: Cleanup: tb_windows define should be removed and placed in tb_configuration.h
defines { "_WINDOWS", "WIN32", "tb_windows" }
links { "OpenGL32", "OpenAL32", "glew32" }
flags { "StaticRuntime" }
toolset "v140_xp"
characterset ("MBCS")
kind ("ConsoleApp")
end
----------------------------------------------------------------------- Mac OS X Platform Specifics
if (MACOSX_SYSTEM_NAME == SYSTEM_NAME) then
libdirs {
"../build/tb_external_libraries/libraries/macosx/"
}
buildoptions "-mmacosx-version-min=10.7"
--linkoptions ""
-- buildoptions "-std=c++11 -stdlib=libc++ -mmacosx-version-min=10.7"
-- linkoptions "-stdlib=libc++"
--TODO: TIM: Cleanup: tb_macosx define should be removed and placed in tb_configuration.h
defines { "tb_macosx" }
links { "AppKit.framework", "IOKit.framework", "OpenGL.framework", "OpenAL.framework", "glew" }
end
----------------------------------------------------------------------- Linux Platform Specifics
if (LINUX_SYSTEM_NAME == SYSTEM_NAME) then
libdirs {
"../build/tb_external_libraries/libraries/linux/",
"/opt/lib/"
}
includedirs {
"/usr/includes/GL/"
}
buildoptions "-std=c++11"
--TODO: TIM: Cleanup: tb_linux define should be removed and placed in tb_configuration.h
defines { "tb_linux" }
links { "GL", "GLEW", "openal", "X11" }
excludes { "../**/**.mm" }
end
----------------------------------------------------------------------- Web (Emscripten) Platform Specifics
if (WEB_SYSTEM_NAME == SYSTEM_NAME) then
buildoptions "-std=c++11"
linkoptions "-stdlib=libc++"
defines { "tb_web" }
end
--------------------------------------------------------------------- Build Configuration Specifics/Overrides
configuration "debug*"
targetdir ("../build/" .. SYSTEM_NAME .. "/debug")
objdir ("../build/" .. SYSTEM_NAME .. "/debug/objects" )
defines { "_DEBUG", "DEBUG" }
symbols "On"
debugdir "../run"
--debugargs { "--nosplash", "--other" }
postbuildcommands { "../automated/post_build_debug" .. SCRIPT_EXTENSION }
configuration "release*"
targetdir ("../build/" .. SYSTEM_NAME .. "/release")
objdir ("../build/" .. SYSTEM_NAME .. "/release/objects" )
defines { "NDEBUG" }
symbols "On"
optimize "On"
debugdir "../run"
--debugargs { "--nosplash", "--other" }
postbuildcommands { "../automated/post_build_release" .. SCRIPT_EXTENSION }
| unlicense |
stephank/luci | applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua | 80 | 1397 | --[[
Luci configuration model for statistics - collectd ping plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("luci_statistics",
translate("Ping Plugin Configuration"),
translate(
"The ping plugin will send icmp echo replies to selected " ..
"hosts and measure the roundtrip time for each host."
))
-- collectd_ping config section
s = m:section( NamedSection, "collectd_ping", "luci_statistics" )
-- collectd_ping.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_ping.hosts (Host)
hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space."))
hosts.default = "127.0.0.1"
hosts:depends( "enable", 1 )
-- collectd_ping.ttl (TTL)
ttl = s:option( Value, "TTL", translate("TTL for ping packets") )
ttl.isinteger = true
ttl.default = 128
ttl:depends( "enable", 1 )
-- collectd_ping.interval (Interval)
interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") )
interval.isinteger = true
interval.default = 30
interval:depends( "enable", 1 )
return m
| apache-2.0 |
delram/crii | plugins/banhammer.lua | 106 | 11894 |
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)$",
"^([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 |
djkamran021/BY | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-3.0 |
artynet/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/cpu.lua | 3 | 1336 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("CPU Plugin Configuration"),
translate("The cpu plugin collects basic statistics about the processor usage."))
-- collectd_cpu config section
s = m:section( NamedSection, "collectd_cpu", "luci_statistics" )
-- collectd_cpu.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_cpu.reportbycpu (ReportByCpu)
reportbycpu = s:option( Flag, "ReportByCpu",
translate("Report by CPU"),
translate("By setting this, CPU is not aggregate of all processors on the system"))
reportbycpu.default = 1
reportbycpu:depends( "enable", 1 )
-- collectd_cpu.reportbystate (ReportByState)
reportbystate = s:option( Flag, "ReportByState",
translate("Report by state"),
translate("When set to true, reports per-state metric (system, user, idle)"))
reportbystate.default = 1
reportbystate:depends( "enable", 1 )
-- collectd_cpu.valuespercentage (ValuesPercentage)
valuespercentage = s:option( Flag, "ValuesPercentage",
translate("Report in percent"),
translate("When set to true, we request percentage values"))
valuespercentage.default = 0
valuespercentage:depends({ enable = 1, ReportByCpu = 1, ReportByState = 1 })
return m
| apache-2.0 |
aqasaeed/mamad | 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 |
SatoshiNXSimudrone/sl4a-damon-clone | lua/luasocket/etc/forward.lua | 61 | 2077 | -- load our favourite library
local dispatch = require("dispatch")
local handler = dispatch.newhandler()
-- make sure the user knows how to invoke us
if table.getn(arg) < 1 then
print("Usage")
print(" lua forward.lua <iport:ohost:oport> ...")
os.exit(1)
end
-- function to move data from one socket to the other
local function move(foo, bar)
local live
while 1 do
local data, error, partial = foo:receive(2048)
live = data or error == "timeout"
data = data or partial
local result, error = bar:send(data)
if not live or not result then
foo:close()
bar:close()
break
end
end
end
-- for each tunnel, start a new server
for i, v in ipairs(arg) do
-- capture forwarding parameters
local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)")
assert(iport, "invalid arguments")
-- create our server socket
local server = assert(handler.tcp())
assert(server:setoption("reuseaddr", true))
assert(server:bind("*", iport))
assert(server:listen(32))
-- handler for the server object loops accepting new connections
handler:start(function()
while 1 do
local client = assert(server:accept())
assert(client:settimeout(0))
-- for each new connection, start a new client handler
handler:start(function()
-- handler tries to connect to peer
local peer = assert(handler.tcp())
assert(peer:settimeout(0))
assert(peer:connect(ohost, oport))
-- if sucessful, starts a new handler to send data from
-- client to peer
handler:start(function()
move(client, peer)
end)
-- afte starting new handler, enter in loop sending data from
-- peer to client
move(peer, client)
end)
end
end)
end
-- simply loop stepping the server
while 1 do
handler:step()
end
| apache-2.0 |
stephank/luci | protocols/ppp/luasrc/model/cbi/admin_network/proto_ppp.lua | 7 | 3622 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local device, username, password
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand
device = section:taboption("general", Value, "device", translate("Modem device"))
device.rmempty = false
local device_suggestions = nixio.fs.glob("/dev/tty*S*")
or nixio.fs.glob("/dev/tts/*")
if device_suggestions then
local node
for node in device_suggestions do
device:value(node)
end
end
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
function keepalive_failure.write() end
function keepalive_failure.remove() end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
| apache-2.0 |
Daniex0r/project-roleplay-rp | resources/system-aut/s_pasy.lua | 1 | 1433 | function toggleWindowa(source)
local thePlayer = source
local theVehicle = getPedOccupiedVehicle(thePlayer)
if theVehicle then
if hasVehicleWindows(theVehicle) then
if (getVehicleOccupant(theVehicle) == thePlayer) or (getVehicleOccupant(theVehicle, 1) == thePlayer) then
if not (isVehicleWindowUp(theVehicle)) then
exports['antyczit']:changeProtectedElementDataEx(theVehicle, "vehicle:pasy", 0, true)
exports.global:sendLocalMeAction(source, "Odpina pasy.")
triggerClientEvent("removeWindow", getRootElement())
for i = 0, getVehicleMaxPassengers(theVehicle) do
local player = getVehicleOccupant(theVehicle, i)
if (player) then
triggerEvent("setTintNamea", player)
end
end
else
exports['antyczit']:changeProtectedElementDataEx(theVehicle, "vehicle:pasy", 1, true)
exports.global:sendLocalMeAction(source, "Zapina pasy.")
triggerClientEvent("addWindow", getRootElement())
for i = 0, getVehicleMaxPassengers(theVehicle) do
local player = getVehicleOccupant(theVehicle, i)
if (player) then
triggerEvent("resetTintNamea", theVehicle, player)
end
end
end
end
end
end
end
addCommandHandler("pasy", toggleWindowa)
function addIcona()
if (getElementData(source, "vehicle:pasy") == 0) then
triggerClientEvent("addWindow", getRootElement())
end
end
addEventHandler("onVehicleEnter", getRootElement(), addIcona) | gpl-2.0 |
dmccuskey/dmc-wamp | examples/dmc-wamp-publish/main.lua | 1 | 2429 | --====================================================================--
-- WAMP Basic Publish
--
-- Basic Publish test for the WAMP library
--
-- Sample code is MIT licensed, the same license which covers Lua itself
-- http://en.wikipedia.org/wiki/MIT_License
-- Copyright (C) 2014-2015 David McCuskey. All Rights Reserved.
--====================================================================--
print( '\n\n##############################################\n\n' )
--====================================================================--
--== Imports
-- read in app deployment configuration, global
_G.gINFO = require 'app_config'
local Wamp = require 'dmc_corona.dmc_wamp'
--====================================================================--
--== Setup, Constants
-- WAMP server info in file 'app_config.lua'
--
local HOST = gINFO.server.host
local PORT = gINFO.server.port
local REALM = gINFO.server.realm
local WAMP_PUBSUB_TOPIC = gINFO.server.pubsub_topic
local wamp -- ref to WAMP object
local doWampPublish -- forward delare function
-- config for message count
local num_msgs = 5
local count = 0
--====================================================================--
--== Support Functions
doWampPublish = function()
print( ">> Wamp Publish event")
local topic = WAMP_PUBSUB_TOPIC
local publish_handler = function( publication )
print( ">> WAMP publish acknowledgment" )
print( string.format( "publish id: %d", publication.id ) )
if count == num_msgs then
-- wamp:close()
else
timer.performWithDelay( 500, function() doWampPublish() end )
end
end
count = count + 1
local params = {
args={ "message-" .. tostring(i), },
-- kwargs={},
callback=publish_handler
}
wamp:publish( topic, params )
end
--====================================================================--
--== Main
--====================================================================--
local wampEvent_handler = function( event )
print( ">> wampEvent_handler", event.type )
if event.type == wamp.ONJOIN then
print( ">> We have WAMP Join" )
doWampPublish()
elseif event.type == wamp.ONDISCONNECT then
print( ">> We have WAMP Disconnect" )
print( ">> ", event.reason, event.message )
end
end
print( "WAMP: Starting WAMP Communication" )
wamp = Wamp:new{
uri=HOST,
port=PORT,
protocols={ 'wamp.2.json' },
realm=REALM
}
wamp:addEventListener( wamp.EVENT, wampEvent_handler )
| mit |
dani-sj/danibot | plugins/google.lua | 336 | 1323 | do
local function googlethat(query)
local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&'
local parameters = 'q='..(URL.escape(query) or '')
-- Do the request
local res, code = https.request(url..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=''
i = 0
for key,val in ipairs(results) do
i = i+1
stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n'
end
return stringresults
end
local function run(msg, matches)
-- comment this line if you want this plugin works in private message.
if not is_chat_msg(msg) then return nil end
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = 'Returns five results from Google. Safe search is enabled by default.',
usage = ' !google [terms]: Searches Google and send results',
patterns = {
'^!google (.*)$',
'^%.[g|G]oogle (.*)$'
},
run = run
}
end
| gpl-2.0 |
ondravondra/vlc | share/lua/sd/icecast.lua | 82 | 2757 | --[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
lazily_loaded = false
function lazy_load()
if lazily_loaded then return nil end
require "simplexml"
lazily_loaded = true
end
function descriptor()
return { title="Icecast Radio Directory" }
end
function dropnil(s)
if s == nil then return "" else return s end
end
function main()
lazy_load()
local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml")
for _, station in ipairs( tree.children ) do
simplexml.add_name_maps( station )
local station_name = station.children_map["server_name"][1].children[1]
if station_name == "Unspecified name" or station_name == "" or station_name == nil
then
station_name = station.children_map["listen_url"][1].children[1]
if string.find( station_name, "radionomy.com" )
then
station_name = string.match( station_name, "([^/]+)$")
station_name = string.gsub( station_name, "-", " " )
end
end
vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1],
title=station_name,
genre=dropnil(station.children_map["genre"][1].children[1]),
nowplaying=dropnil(station.children_map["current_song"][1].children[1]),
uiddata=station.children_map["listen_url"][1].children[1]
.. dropnil(station.children_map["server_name"][1].children[1]),
meta={
["Listing Source"]="dir.xiph.org",
["Listing Type"]="radio",
["Icecast Bitrate"]=dropnil(station.children_map["bitrate"][1].children[1]),
["Icecast Server Type"]=dropnil(station.children_map["server_type"][1].children[1])
}} )
end
end
| gpl-2.0 |
akh00/kong | spec/03-plugins/27-request-termination/02-access_spec.lua | 2 | 5144 | local helpers = require "spec.helpers"
local cjson = require "cjson"
describe("Plugin: request-termination (access)", function()
local client, admin_client
setup(function()
local api1 = assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "api1.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api1.id,
config = {
}
})
local api2 = assert(helpers.dao.apis:insert {
name = "api-2",
hosts = { "api2.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api2.id,
config = {
status_code=404
}
})
local api3 = assert(helpers.dao.apis:insert {
name = "api-3",
hosts = { "api3.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api3.id,
config = {
status_code=406,
message="Invalid"
}
})
local api4 = assert(helpers.dao.apis:insert {
name = "api-4",
hosts = { "api4.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api4.id,
config = {
body="<html><body><h1>Service is down for maintenance</h1></body></html>"
}
})
local api5 = assert(helpers.dao.apis:insert {
name = "api-5",
hosts = { "api5.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api5.id,
config = {
status_code=451,
content_type="text/html",
body="<html><body><h1>Service is down due to content infringement</h1></body></html>"
}
})
local api6 = assert(helpers.dao.apis:insert {
name = "api-6",
hosts = { "api6.request-termination.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "request-termination",
api_id = api6.id,
config = {
status_code=503,
body='{"code": 1, "message": "Service unavailable"}'
}
})
assert(helpers.start_kong())
client = helpers.proxy_client()
admin_client = helpers.admin_client()
end)
teardown(function()
if client and admin_client then
client:close()
admin_client:close()
end
helpers.stop_kong()
end)
describe("status code and message", function()
it("default status code and message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api1.request-termination.com"
}
})
local body = assert.res_status(503, res)
local json = cjson.decode(body)
assert.same({ message = "Service unavailable" }, json)
end)
it("status code with default message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api2.request-termination.com"
}
})
local body = assert.res_status(404, res)
local json = cjson.decode(body)
assert.same({ message = "Not found" }, json)
end)
it("status code with custom message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api3.request-termination.com"
}
})
local body = assert.res_status(406, res)
local json = cjson.decode(body)
assert.same({ message = "Invalid" }, json)
end)
end)
describe("status code and body", function()
it("default status code and body", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api4.request-termination.com"
}
})
local body = assert.res_status(503, res)
assert.equal([[<html><body><h1>Service is down for maintenance</h1></body></html>]], body)
end)
it("status code with default message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api5.request-termination.com"
}
})
local body = assert.res_status(451, res)
assert.equal([[<html><body><h1>Service is down due to content infringement</h1></body></html>]], body)
end)
it("status code with custom message", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "api6.request-termination.com"
}
})
local body = assert.res_status(503, res)
local json = cjson.decode(body)
assert.same({ code = 1, message = "Service unavailable" }, json)
end)
end)
end)
| apache-2.0 |
artynet/luci | libs/luci-lib-px5g/lua/px5g/util.lua | 170 | 1148 | --[[
* px5g - Embedded x509 key and certificate generator based on PolarSSL
*
* Copyright (C) 2009 Steven Barth <steven@midlink.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License, version 2.1 as published by the Free Software Foundation.
]]--
local nixio = require "nixio"
local table = require "table"
module "px5g.util"
local preamble = {
key = "-----BEGIN RSA PRIVATE KEY-----",
cert = "-----BEGIN CERTIFICATE-----",
request = "-----BEGIN CERTIFICATE REQUEST-----"
}
local postamble = {
key = "-----END RSA PRIVATE KEY-----",
cert = "-----END CERTIFICATE-----",
request = "-----END CERTIFICATE REQUEST-----"
}
function der2pem(data, type)
local b64 = nixio.bin.b64encode(data)
local outdata = {preamble[type]}
for i = 1, #b64, 64 do
outdata[#outdata + 1] = b64:sub(i, i + 63)
end
outdata[#outdata + 1] = postamble[type]
outdata[#outdata + 1] = ""
return table.concat(outdata, "\n")
end
function pem2der(data)
local b64 = data:gsub({["\n"] = "", ["%-%-%-%-%-.-%-%-%-%-%-"] = ""})
return nixio.bin.b64decode(b64)
end | apache-2.0 |
akh00/kong | spec/03-plugins/26-oauth2/03-access_spec.lua | 1 | 85246 | local cjson = require "cjson"
local helpers = require "spec.helpers"
local utils = require "kong.tools.utils"
local function provision_code(host, extra_headers, client_id)
local request_client = helpers.proxy_ssl_client()
local res = assert(request_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
client_id = client_id or "clientid123",
scope = "email",
response_type = "code",
state = "hello",
authenticated_userid = "userid123"
},
headers = utils.table_merge({
["Host"] = host or "oauth2.com",
["Content-Type"] = "application/json"
}, extra_headers)
})
assert.response(res).has.status(200)
local body = assert.response(res).has.jsonbody()
request_client:close()
if body.redirect_uri then
local iterator, err = ngx.re.gmatch(body.redirect_uri, "^http://google\\.com/kong\\?code=([\\w]{32,32})&state=hello$")
assert.is_nil(err)
local m, err = iterator()
assert.is_nil(err)
return m[1]
end
end
local function provision_token(host, extra_headers, client_id, client_secret)
local code = provision_code(host, extra_headers, client_id)
local request_client = helpers.proxy_ssl_client()
local res = assert(request_client:send {
method = "POST",
path = "/oauth2/token",
body = { code = code,
client_id = client_id or "clientid123",
client_secret = client_secret or "secret123",
grant_type = "authorization_code" },
headers = utils.table_merge({
["Host"] = host or "oauth2.com",
["Content-Type"] = "application/json"
}, extra_headers)
})
assert.response(res).has.status(200)
local token = assert.response(res).has.jsonbody()
assert.is_table(token)
request_client:close()
return token
end
describe("Plugin: oauth2 (access)", function()
local proxy_ssl_client, proxy_client
local client1
setup(function()
local consumer = assert(helpers.dao.consumers:insert {
username = "bob"
})
local anonymous_user = assert(helpers.dao.consumers:insert {
username = "no-body"
})
client1 = assert(helpers.dao.oauth2_credentials:insert {
client_id = "clientid123",
client_secret = "secret123",
redirect_uri = "http://google.com/kong",
name = "testapp",
consumer_id = consumer.id
})
assert(helpers.dao.oauth2_credentials:insert {
client_id = "clientid789",
client_secret = "secret789",
redirect_uri = "http://google.com/kong?foo=bar&code=123",
name = "testapp2",
consumer_id = consumer.id
})
assert(helpers.dao.oauth2_credentials:insert {
client_id = "clientid333",
client_secret = "secret333",
redirect_uri = "http://google.com/kong",
name = "testapp3",
consumer_id = consumer.id
})
assert(helpers.dao.oauth2_credentials:insert {
client_id = "clientid456",
client_secret = "secret456",
redirect_uri = {"http://one.com/one/", "http://two.com/two"},
name = "testapp3",
consumer_id = consumer.id
})
local api1 = assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "oauth2.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api1.id,
config = {
scopes = { "email", "profile", "user.email" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true
}
})
local api2 = assert(helpers.dao.apis:insert {
name = "api-2",
hosts = { "mockbin-path.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api2.id,
config = {
scopes = { "email", "profile" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true
}
})
local api2bis = assert(helpers.dao.apis:insert {
name = "api-2-bis",
uris = { "/somepath" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api2bis.id,
config = {
scopes = { "email", "profile" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true
}
})
local api3 = assert(helpers.dao.apis:insert {
name = "api-3",
hosts = { "oauth2_3.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api3.id,
config = {
scopes = { "email", "profile" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
hide_credentials = true
}
})
local api4 = assert(helpers.dao.apis:insert {
name = "api-4",
hosts = { "oauth2_4.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api4.id,
config = {
scopes = { "email", "profile" },
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_client_credentials = true,
enable_authorization_code = false
}
})
local api5 = assert(helpers.dao.apis:insert {
name = "api-5",
hosts = { "oauth2_5.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api5.id,
config = {
scopes = { "email", "profile" },
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_password_grant = true,
enable_authorization_code = false
}
})
local api6 = assert(helpers.dao.apis:insert {
name = "api-6",
hosts = { "oauth2_6.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api6.id,
config = {
scopes = { "email", "profile", "user.email" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
accept_http_if_already_terminated = true
}
})
local api7 = assert(helpers.dao.apis:insert {
name = "api-7",
hosts = { "oauth2_7.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api7.id,
config = {
scopes = { "email", "profile", "user.email" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
anonymous = anonymous_user.id,
global_credentials = false
}
})
local api8 = assert(helpers.dao.apis:insert {
name = "oauth2_8.com",
hosts = { "oauth2_8.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api8.id,
config = {
scopes = { "email", "profile", "user.email" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
global_credentials = true
}
})
local api9 = assert(helpers.dao.apis:insert {
name = "oauth2_9.com",
hosts = { "oauth2_9.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api9.id,
config = {
scopes = { "email", "profile", "user.email" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
global_credentials = true
}
})
local api10 = assert(helpers.dao.apis:insert {
name = "oauth2_10.com",
hosts = { "oauth2_10.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api10.id,
config = {
scopes = { "email", "profile", "user.email" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
global_credentials = true,
anonymous = utils.uuid(), -- a non existing consumer
}
})
assert(helpers.start_kong())
proxy_client = helpers.proxy_client()
proxy_ssl_client = helpers.proxy_ssl_client()
end)
teardown(function()
if proxy_client and proxy_ssl_client then
proxy_client:close()
proxy_ssl_client:close()
end
helpers.stop_kong()
end)
describe("OAuth2 Authorization", function()
describe("Code Grant", function()
it("returns an error when no provision_key is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
headers = {
["Host"] = "oauth2.com"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid provision_key", error = "invalid_provision_key" }, json)
assert.are.equal("no-store", res.headers["cache-control"])
assert.are.equal("no-cache", res.headers["pragma"])
end)
it("returns an error when no parameter is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Missing authenticated_userid parameter", error = "invalid_authenticated_userid" }, json)
end)
it("returns an error when only provision_key and authenticated_userid are sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
assert.are.equal("no-store", res.headers["cache-control"])
assert.are.equal("no-cache", res.headers["pragma"])
end)
it("returns an error when only the client_id is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ redirect_uri = "http://google.com/kong?error=invalid_scope&error_description=You%20must%20specify%20a%20scope" }, json)
end)
it("returns an error when an invalid scope is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "wot"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ redirect_uri = "http://google.com/kong?error=invalid_scope&error_description=%22wot%22%20is%20an%20invalid%20scope" }, json)
end)
it("returns an error when no response_type is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ redirect_uri = "http://google.com/kong?error=unsupported_response_type&error_description=Invalid%20response_type" }, json)
end)
it("returns an error with a state when no response_type is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
state = "somestate"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ redirect_uri = "http://google.com/kong?error=unsupported_response_type&error_description=Invalid%20response_type&state=somestate" }, json)
end)
it("returns error when the redirect_uri does not match", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code",
redirect_uri = "http://hello.com/"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ redirect_uri = "http://google.com/kong?error=invalid_request&error_description=Invalid%20redirect_uri%20that%20does%20not%20match%20with%20any%20redirect_uri%20created%20with%20the%20application" }, json)
end)
it("works even if redirect_uri contains a query string", function()
local res = assert(proxy_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid789",
scope = "email",
response_type = "code"
},
headers = {
["Host"] = "oauth2_6.com",
["Content-Type"] = "application/json",
["X-Forwarded-Proto"] = "https"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\?code=[\\w]{32,32}&foo=bar$"))
end)
it("works with multiple redirect_uri in the application", function()
local res = assert(proxy_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid456",
scope = "email",
response_type = "code"
},
headers = {
["Host"] = "oauth2_6.com",
["Content-Type"] = "application/json",
["X-Forwarded-Proto"] = "https"
}
})
assert.response(res).has.status(200)
local json = assert.response(res).has.jsonbody()
assert.truthy(ngx.re.match(json.redirect_uri, "^http://one\\.com/one/\\?code=[\\w]{32,32}$"))
end)
it("fails when not under HTTPS", function()
local res = assert(proxy_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
assert.response(res).has.status(400)
local json = assert.response(res).has.jsonbody(res)
assert.equal("You must use HTTPS", json.error_description)
assert.equal("access_denied", json.error)
end)
it("works when not under HTTPS but accept_http_if_already_terminated is true", function()
local res = assert(proxy_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code"
},
headers = {
["Host"] = "oauth2_6.com",
["Content-Type"] = "application/json",
["X-Forwarded-Proto"] = "https"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\?code=[\\w]{32,32}$"))
end)
it("fails when not under HTTPS and accept_http_if_already_terminated is false", function()
local res = assert(proxy_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json",
["X-Forwarded-Proto"] = "https"
}
})
assert.response(res).has.status(400)
local json = assert.response(res).has.jsonbody(res)
assert.equal("You must use HTTPS", json.error_description)
assert.equal("access_denied", json.error)
end)
it("returns success", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\?code=[\\w]{32,32}$"))
end)
it("fails with a path when using the DNS", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123a",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code"
},
headers = {
["Host"] = "mockbin-path.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid provision_key", error = "invalid_provision_key" }, json)
end)
it("returns success with a path", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/somepath/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code"
},
headers = {
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\?code=[\\w]{32,32}$"))
end)
it("returns success when requesting the url with final slash", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize/",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\?code=[\\w]{32,32}$"))
end)
it("returns success with a state", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "code",
state = "hello"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\?code=[\\w]{32,32}&state=hello$"))
-- Checking headers
assert.are.equal("no-store", res.headers["cache-control"])
assert.are.equal("no-cache", res.headers["pragma"])
end)
it("returns success and store authenticated user properties", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
client_id = "clientid123",
scope = "email",
response_type = "code",
state = "hello",
authenticated_userid = "userid123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\?code=[\\w]{32,32}&state=hello$"))
local iterator, err = ngx.re.gmatch(body.redirect_uri, "^http://google\\.com/kong\\?code=([\\w]{32,32})&state=hello$")
assert.is_nil(err)
local m, err = iterator()
assert.is_nil(err)
local data = helpers.dao.oauth2_authorization_codes:find_all {code = m[1]}
assert.are.equal(1, #data)
assert.are.equal(m[1], data[1].code)
assert.are.equal("userid123", data[1].authenticated_userid)
assert.are.equal("email", data[1].scope)
assert.are.equal(client1.id, data[1].credential_id)
end)
it("returns success with a dotted scope and store authenticated user properties", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
client_id = "clientid123",
scope = "user.email",
response_type = "code",
state = "hello",
authenticated_userid = "userid123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\?code=[\\w]{32,32}&state=hello$"))
local iterator, err = ngx.re.gmatch(body.redirect_uri, "^http://google\\.com/kong\\?code=([\\w]{32,32})&state=hello$")
assert.is_nil(err)
local m, err = iterator()
assert.is_nil(err)
local data = helpers.dao.oauth2_authorization_codes:find_all {code = m[1]}
assert.are.equal(1, #data)
assert.are.equal(m[1], data[1].code)
assert.are.equal("userid123", data[1].authenticated_userid)
assert.are.equal("user.email", data[1].scope)
end)
end)
describe("Implicit Grant", function()
it("returns success", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "token"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\#access_token=[\\w]{32,32}&expires_in=[\\d]+&token_type=bearer$"))
assert.are.equal("no-store", res.headers["cache-control"])
assert.are.equal("no-cache", res.headers["pragma"])
end)
it("returns success and the state", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "token",
state = "wot"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\#access_token=[\\w]{32,32}&expires_in=[\\d]+&state=wot&token_type=bearer$"))
end)
it("returns success and the token should have the right expiration", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
scope = "email",
response_type = "token"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\#access_token=[\\w]{32,32}&expires_in=[\\d]+&token_type=bearer$"))
local iterator, err = ngx.re.gmatch(body.redirect_uri, "^http://google\\.com/kong\\#access_token=([\\w]{32,32})&expires_in=[\\d]+&token_type=bearer$")
assert.is_nil(err)
local m, err = iterator()
assert.is_nil(err)
local data = helpers.dao.oauth2_tokens:find_all {access_token = m[1]}
assert.are.equal(1, #data)
assert.are.equal(m[1], data[1].access_token)
assert.are.equal(5, data[1].expires_in)
assert.falsy(data[1].refresh_token)
end)
it("returns success and store authenticated user properties", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
client_id = "clientid123",
scope = "email profile",
response_type = "token",
authenticated_userid = "userid123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_table(ngx.re.match(body.redirect_uri, "^http://google\\.com/kong\\#access_token=[\\w]{32,32}&expires_in=[\\d]+&token_type=bearer$"))
local iterator, err = ngx.re.gmatch(body.redirect_uri, "^http://google\\.com/kong\\#access_token=([\\w]{32,32})&expires_in=[\\d]+&token_type=bearer$")
assert.is_nil(err)
local m, err = iterator()
assert.is_nil(err)
local data = helpers.dao.oauth2_tokens:find_all {access_token = m[1]}
assert.are.equal(1, #data)
assert.are.equal(m[1], data[1].access_token)
assert.are.equal("userid123", data[1].authenticated_userid)
assert.are.equal("email profile", data[1].scope)
-- Checking that there is no refresh token since it's an implicit grant
assert.are.equal(5, data[1].expires_in)
assert.falsy(data[1].refresh_token)
end)
it("returns set the right upstream headers", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/authorize",
body = {
provision_key = "provision123",
client_id = "clientid123",
scope = "email profile",
response_type = "token",
authenticated_userid = "userid123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
local iterator, err = ngx.re.gmatch(body.redirect_uri, "^http://google\\.com/kong\\#access_token=([\\w]{32,32})&expires_in=[\\d]+&token_type=bearer$")
assert.is_nil(err)
local m, err = iterator()
assert.is_nil(err)
local access_token = m[1]
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request?access_token=" .. access_token,
headers = {
["Host"] = "oauth2.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.truthy(body.headers["x-consumer-id"])
assert.are.equal("bob", body.headers["x-consumer-username"])
assert.are.equal("email profile", body.headers["x-authenticated-scope"])
assert.are.equal("userid123", body.headers["x-authenticated-userid"])
end)
end)
describe("Client Credentials", function()
it("returns an error when client_secret is not sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
scope = "email",
response_type = "token"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
end)
it("returns an error when client_secret is not sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
response_type = "token"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "unsupported_grant_type", error_description = "Invalid grant_type" }, json)
end)
it("fails when not under HTTPS", function()
local res = assert(proxy_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "client_credentials"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
assert.response(res).has.status(400)
local json = assert.response(res).has.jsonbody(res)
assert.equal("You must use HTTPS", json.error_description)
assert.equal("access_denied", json.error)
end)
it("fails when setting authenticated_userid and no provision_key", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "client_credentials",
authenticated_userid = "user123"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid provision_key", error = "invalid_provision_key" }, json)
end)
it("fails when setting authenticated_userid and invalid provision_key", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "client_credentials",
authenticated_userid = "user123",
provision_key = "hello"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid provision_key", error = "invalid_provision_key" }, json)
end)
it("returns success", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "client_credentials"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("returns success with an application that has multiple redirect_uri", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid456",
client_secret="secret456",
scope = "email",
grant_type = "client_credentials"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("returns success with an application that has multiple redirect_uri, and by passing a valid redirect_uri", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid456",
client_secret="secret456",
scope = "email",
grant_type = "client_credentials",
redirect_uri = "http://two.com/two"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("fails with an application that has multiple redirect_uri, and by passing an invalid redirect_uri", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid456",
client_secret="secret456",
scope = "email",
grant_type = "client_credentials",
redirect_uri = "http://two.com/two/hello"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "invalid_request", error_description = "Invalid redirect_uri that does not match with any redirect_uri created with the application" }, json)
end)
it("returns success with authenticated_userid and valid provision_key", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "client_credentials",
authenticated_userid = "hello",
provision_key = "provision123"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("returns success with authorization header", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
scope = "email",
grant_type = "client_credentials"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json",
Authorization = "Basic Y2xpZW50aWQxMjM6c2VjcmV0MTIz"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("returns success with authorization header and client_id body param", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
scope = "email",
grant_type = "client_credentials"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json",
Authorization = "Basic Y2xpZW50aWQxMjM6c2VjcmV0MTIz"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("returns an error with a wrong authorization header", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
scope = "email",
grant_type = "client_credentials"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json",
Authorization = "Basic Y2xpZW50aWQxMjM6c2VjcmV0MTI0"
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
assert.are.equal("Basic realm=\"OAuth2.0\"", res.headers["www-authenticate"])
end)
it("sets the right upstream headers", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "client_credentials",
authenticated_userid = "hello",
provision_key = "provision123"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request?access_token=" .. body.access_token,
headers = {
["Host"] = "oauth2_4.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.truthy(body.headers["x-consumer-id"])
assert.are.equal("bob", body.headers["x-consumer-username"])
assert.are.equal("email", body.headers["x-authenticated-scope"])
assert.are.equal("hello", body.headers["x-authenticated-userid"])
end)
it("works in a multipart request", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "client_credentials",
authenticated_userid = "hello",
provision_key = "provision123"
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "multipart/form-data"
}
})
local body = cjson.decode(assert.res_status(200, res))
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
body = {
access_token = body.access_token
},
headers = {
["Host"] = "oauth2_4.com",
["Content-Type"] = "multipart/form-data"
}
})
assert.res_status(200, res)
end)
end)
describe("Password Grant", function()
it("blocks unauthorized requests", function()
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "oauth2_5.com"
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "The access token is missing", error = "invalid_request" }, json)
end)
it("returns an error when client_secret is not sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
scope = "email",
response_type = "token"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
end)
it("returns an error when grant_type is not sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
response_type = "token"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "unsupported_grant_type", error_description = "Invalid grant_type" }, json)
end)
it("fails when no provision key is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
response_type = "token",
grant_type = "password"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid provision_key", error = "invalid_provision_key" }, json)
end)
it("fails when no provision key is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "password"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid provision_key", error = "invalid_provision_key" }, json)
end)
it("fails when no authenticated user id is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
provision_key = "provision123",
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "password"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Missing authenticated_userid parameter", error = "invalid_authenticated_userid" }, json)
end)
it("returns success", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
client_id = "clientid123",
client_secret="secret123",
scope = "email",
grant_type = "password"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"refresh_token":"[\w]{32,32}","token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("returns success with authorization header", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
scope = "email",
grant_type = "password"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json",
Authorization = "Basic Y2xpZW50aWQxMjM6c2VjcmV0MTIz"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"refresh_token":"[\w]{32,32}","token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("returns an error with a wrong authorization header", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
scope = "email",
grant_type = "password"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json",
Authorization = "Basic Y2xpZW50aWQxMjM6c2VjcmV0MTI0"
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
assert.are.equal("Basic realm=\"OAuth2.0\"", res.headers["www-authenticate"])
end)
it("sets the right upstream headers", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
provision_key = "provision123",
authenticated_userid = "id123",
scope = "email",
grant_type = "password"
},
headers = {
["Host"] = "oauth2_5.com",
["Content-Type"] = "application/json",
Authorization = "Basic Y2xpZW50aWQxMjM6c2VjcmV0MTIz"
}
})
local body = cjson.decode(assert.res_status(200, res))
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request?access_token=" .. body.access_token,
headers = {
["Host"] = "oauth2_5.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.truthy(body.headers["x-consumer-id"])
assert.are.equal("bob", body.headers["x-consumer-username"])
assert.are.equal("email", body.headers["x-authenticated-scope"])
assert.are.equal("id123", body.headers["x-authenticated-userid"])
end)
end)
end)
describe("OAuth2 Access Token", function()
it("returns an error when nothing is being sent", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
headers = {
["Host"] = "oauth2.com"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
-- Checking headers
assert.are.equal("no-store", res.headers["cache-control"])
assert.are.equal("no-cache", res.headers["pragma"])
end)
it("returns an error when only the code is being sent", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
-- Checking headers
assert.are.equal("no-store", res.headers["cache-control"])
assert.are.equal("no-cache", res.headers["pragma"])
end)
it("returns an error when only the code and client_secret are being sent", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_secret = "secret123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
-- Checking headers
assert.are.equal("no-store", res.headers["cache-control"])
assert.are.equal("no-cache", res.headers["pragma"])
end)
it("returns an error when grant_type is not being sent", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid123",
client_secret = "secret123"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "unsupported_grant_type", error_description = "Invalid grant_type" }, json)
end)
it("returns an error with a wrong code", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code .. "hello",
client_id = "clientid123",
client_secret = "secret123",
grant_type = "authorization_code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "invalid_request", error_description = "Invalid code" }, json)
end)
it("returns success without state", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "authorization_code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"refresh_token":"[\w]{32,32}","token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("returns success with state", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "authorization_code",
state = "wot"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"refresh_token":"[\w]{32,32}","token_type":"bearer","state":"wot","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("fails when the client used for the code is not the same client used for the token", function()
local code = provision_code(nil, nil, "clientid333")
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "authorization_code",
state = "wot"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
assert.same({ error = "invalid_request", error_description = "Invalid code", state = "wot" }, cjson.decode(body))
end)
it("sets the right upstream headers", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "authorization_code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = cjson.decode(assert.res_status(200, res))
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request?access_token=" .. body.access_token,
headers = {
["Host"] = "oauth2.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.truthy(body.headers["x-consumer-id"])
assert.are.equal("bob", body.headers["x-consumer-username"])
assert.are.equal("email", body.headers["x-authenticated-scope"])
assert.are.equal("userid123", body.headers["x-authenticated-userid"])
end)
it("fails when an authorization code is used more than once", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "authorization_code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"refresh_token":"[\w]{32,32}","token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "authorization_code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "invalid_request", error_description = "Invalid code" }, json)
end)
it("fails when an authorization code is used by another application", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid789",
client_secret = "secret789",
grant_type = "authorization_code"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "invalid_request", error_description = "Invalid code" }, json)
end)
it("fails when an authorization code is used for another API", function()
local code = provision_code()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
code = code,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "authorization_code"
},
headers = {
["Host"] = "oauth2_3.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "invalid_request", error_description = "Invalid code" }, json)
end)
end)
describe("Making a request", function()
it("fails when no access_token is being sent in an application/json body", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "The access token is missing", error = "invalid_request" }, json)
end)
it("works when a correct access_token is being sent in the querystring", function()
local token = provision_token()
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request?access_token=" .. token.access_token,
headers = {
["Host"] = "oauth2.com"
}
})
assert.res_status(200, res)
end)
it("does not work when requesting a different API", function()
local token = provision_token()
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request?access_token=" .. token.access_token,
headers = {
["Host"] = "oauth2_3.com"
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "The access token is invalid or has expired", error = "invalid_token" }, json)
end)
it("works when a correct access_token is being sent in a form body", function()
local token = provision_token()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
body = {
access_token = token.access_token
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
assert.res_status(200, res)
end)
it("works when a correct access_token is being sent in an authorization header (bearer)", function()
local token = provision_token()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
Authorization = "bearer " .. token.access_token
}
})
assert.res_status(200, res)
end)
it("works when a correct access_token is being sent in an authorization header (token)", function()
local token = provision_token()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
Authorization = "bearer " .. token.access_token
}
})
local body = cjson.decode(assert.res_status(200, res))
local consumer = helpers.dao.consumers:find_all({username = "bob"})[1]
assert.are.equal(consumer.id, body.headers["x-consumer-id"])
assert.are.equal(consumer.username, body.headers["x-consumer-username"])
assert.are.equal("userid123", body.headers["x-authenticated-userid"])
assert.are.equal("email", body.headers["x-authenticated-scope"])
assert.is_nil(body.headers["x-anonymous-consumer"])
end)
it("works with right credentials and anonymous", function()
local token = provision_token("oauth2_7.com")
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2_7.com",
Authorization = "bearer " .. token.access_token
}
})
local body = cjson.decode(assert.res_status(200, res))
local consumer = helpers.dao.consumers:find_all({username = "bob"})[1]
assert.are.equal(consumer.id, body.headers["x-consumer-id"])
assert.are.equal(consumer.username, body.headers["x-consumer-username"])
assert.are.equal("userid123", body.headers["x-authenticated-userid"])
assert.are.equal("email", body.headers["x-authenticated-scope"])
assert.is_nil(body.headers["x-anonymous-consumer"])
end)
it("works with wrong credentials and anonymous", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2_7.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.are.equal("true", body.headers["x-anonymous-consumer"])
assert.equal('no-body', body.headers["x-consumer-username"])
end)
it("errors when anonymous user doesn't exist", function()
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "oauth2_10.com"
}
})
assert.response(res).has.status(500)
end)
describe("Global Credentials", function()
it("does not access two different APIs that are not sharing global credentials", function()
local token = provision_token("oauth2_8.com")
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2_8.com",
Authorization = "bearer " .. token.access_token
}
})
assert.res_status(200, res)
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
Authorization = "bearer " .. token.access_token
}
})
assert.res_status(401, res)
end)
it("does not access two different APIs that are not sharing global credentials 2", function()
local token = provision_token("oauth2.com")
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2_8.com",
Authorization = "bearer " .. token.access_token
}
})
assert.res_status(401, res)
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
Authorization = "bearer " .. token.access_token
}
})
assert.res_status(200, res)
end)
it("access two different APIs that are sharing global credentials", function()
local token = provision_token("oauth2_8.com")
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2_8.com",
Authorization = "bearer " .. token.access_token
}
})
assert.res_status(200, res)
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2_9.com",
Authorization = "bearer " .. token.access_token
}
})
assert.res_status(200, res)
end)
end)
end)
describe("Authentication challenge", function()
it("returns 401 Unauthorized without error if it lacks any authentication information", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com"
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "The access token is missing", error = "invalid_request" }, json)
assert.are.equal('Bearer realm="service"', res.headers['www-authenticate'])
end)
it("returns 401 Unauthorized when an invalid access token is being sent via url parameter", function()
local res = assert(proxy_ssl_client:send {
method = "GET",
path = "/request?access_token=invalid",
headers = {
["Host"] = "oauth2.com"
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "The access token is invalid or has expired", error = "invalid_token" }, json)
assert.are.equal('Bearer realm="service" error="invalid_token" error_description="The access token is invalid or has expired"', res.headers['www-authenticate'])
end)
it("returns 401 Unauthorized when an invalid access token is being sent via the Authorization header", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
Authorization = "bearer invalid"
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "The access token is invalid or has expired", error = "invalid_token" }, json)
assert.are.equal('Bearer realm="service" error="invalid_token" error_description="The access token is invalid or has expired"', res.headers['www-authenticate'])
end)
it("returns 401 Unauthorized when token has expired", function()
local token = provision_token()
-- Token expires in (5 seconds)
ngx.sleep(7)
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
Authorization = "bearer " .. token.access_token
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "The access token is invalid or has expired", error = "invalid_token" }, json)
assert.are.equal('Bearer realm="service" error="invalid_token" error_description="The access token is invalid or has expired"', res.headers['www-authenticate'])
end)
end)
describe("Refresh Token", function()
it("does not refresh an invalid access token", function()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
refresh_token = "hello",
client_id = "clientid123",
client_secret = "secret123",
grant_type = "refresh_token"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error = "invalid_request", error_description = "Invalid refresh_token" }, json)
end)
it("refreshes an valid access token", function()
local token = provision_token()
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
refresh_token = token.refresh_token,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "refresh_token"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"refresh_token":"[\w]{32,32}","token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
end)
it("refreshes an valid access token and checks that it belongs to the application", function()
local token = provision_token(nil, nil, "clientid333", "secret333")
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
refresh_token = token.refresh_token,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "refresh_token"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json"
}
})
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ error_description = "Invalid client authentication", error = "invalid_client" }, json)
assert.are.equal("no-store", res.headers["cache-control"])
assert.are.equal("no-cache", res.headers["pragma"])
end)
it("expires after 5 seconds", function()
local token = provision_token()
local res = assert(proxy_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
authorization = "bearer " .. token.access_token
}
})
assert.res_status(200, res)
local id = helpers.dao.oauth2_tokens:find_all({access_token = token.access_token })[1].id
assert.truthy(helpers.dao.oauth2_tokens:find({id=id}))
-- But waiting after the cache expiration (5 seconds) should block the request
ngx.sleep(7)
local res = assert(proxy_client:send {
method = "POST",
path = "/request",
headers = {
["Host"] = "oauth2.com",
authorization = "bearer " .. token.access_token
}
})
local body = assert.res_status(401, res)
local json = cjson.decode(body)
assert.same({ error_description = "The access token is invalid or has expired", error = "invalid_token" }, json)
-- Refreshing the token
local res = assert(proxy_ssl_client:send {
method = "POST",
path = "/oauth2/token",
body = {
refresh_token = token.refresh_token,
client_id = "clientid123",
client_secret = "secret123",
grant_type = "refresh_token"
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/json",
authorization = "bearer " .. token.access_token
}
})
local body = assert.res_status(200, res)
assert.is_table(ngx.re.match(body, [[^\{"refresh_token":"[\w]{32,32}","token_type":"bearer","access_token":"[\w]{32,32}","expires_in":5\}$]]))
assert.falsy(token.access_token == cjson.decode(body).access_token)
assert.falsy(token.refresh_token == cjson.decode(body).refresh_token)
assert.falsy(helpers.dao.oauth2_tokens:find({id=id}))
end)
end)
describe("Hide Credentials", function()
it("does not hide credentials in the body", function()
local token = provision_token()
local res = assert(proxy_client:send {
method = "POST",
path = "/request",
body = {
access_token = token.access_token
},
headers = {
["Host"] = "oauth2.com",
["Content-Type"] = "application/x-www-form-urlencoded"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.equal(token.access_token, body.postData.params.access_token)
end)
it("hides credentials in the body", function()
local token = provision_token("oauth2_3.com")
local res = assert(proxy_client:send {
method = "POST",
path = "/request",
body = {
access_token = token.access_token
},
headers = {
["Host"] = "oauth2_3.com",
["Content-Type"] = "application/x-www-form-urlencoded"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_nil(body.postData.params.access_token)
end)
it("does not hide credentials in the querystring", function()
local token = provision_token()
local res = assert(proxy_client:send {
method = "GET",
path = "/request?access_token=" .. token.access_token,
headers = {
["Host"] = "oauth2.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.equal(token.access_token, body.queryString.access_token)
end)
it("hides credentials in the querystring", function()
local token = provision_token("oauth2_3.com")
local res = assert(proxy_client:send {
method = "GET",
path = "/request?access_token=" .. token.access_token,
headers = {
["Host"] = "oauth2_3.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_nil(body.queryString.access_token)
end)
it("does not hide credentials in the header", function()
local token = provision_token()
local res = assert(proxy_client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "oauth2.com",
authorization = "bearer " .. token.access_token
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.equal("bearer " .. token.access_token, body.headers.authorization)
end)
it("hides credentials in the header", function()
local token = provision_token("oauth2_3.com")
local res = assert(proxy_client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "oauth2_3.com",
authorization = "bearer " .. token.access_token
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.is_nil(body.headers.authorization)
end)
it("does not abort when the request body is a multipart form upload", function()
local token = provision_token("oauth2_3.com")
local res = assert(proxy_client:send {
method = "POST",
path = "/request?access_token=" .. token.access_token,
body = {
foo = "bar"
},
headers = {
["Host"] = "oauth2_3.com",
["Content-Type"] = "multipart/form-data"
}
})
assert.res_status(200, res)
end)
end)
end)
describe("Plugin: oauth2 (access)", function()
local client, user1, user2, anonymous
setup(function()
local api1 = assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "logical-and.com" },
upstream_url = "http://mockbin.org/request"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api1.id,
config = {
scopes = { "email", "profile", "user.email" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
global_credentials = false,
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api1.id
})
anonymous = assert(helpers.dao.consumers:insert {
username = "Anonymous"
})
user1 = assert(helpers.dao.consumers:insert {
username = "Mickey"
})
user2 = assert(helpers.dao.consumers:insert {
username = "Aladdin"
})
local api2 = assert(helpers.dao.apis:insert {
name = "api-2",
hosts = { "logical-or.com" },
upstream_url = "http://mockbin.org/request"
})
assert(helpers.dao.plugins:insert {
name = "oauth2",
api_id = api2.id,
config = {
scopes = { "email", "profile", "user.email" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
global_credentials = false,
anonymous = anonymous.id,
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api2.id,
config = {
anonymous = anonymous.id
}
})
assert(helpers.dao.keyauth_credentials:insert {
key = "Mouse",
consumer_id = user1.id
})
assert(helpers.dao.oauth2_credentials:insert {
client_id = "clientid123",
client_secret = "secret123",
redirect_uri = "http://google.com/kong",
name = "testapp",
consumer_id = user2.id
})
assert(helpers.start_kong())
client = helpers.proxy_client()
end)
teardown(function()
if client then client:close() end
helpers.stop_kong()
end)
describe("multiple auth without anonymous, logical AND", function()
it("passes with all credentials provided", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "logical-and.com",
["apikey"] = "Mouse",
-- we must provide the apikey again in the extra_headers, for the
-- token endpoint, because that endpoint is also protected by the
-- key-auth plugin. Otherwise getting the token simply fails.
["Authorization"] = "bearer " .. provision_token("logical-and.com",
{["apikey"] = "Mouse"}).access_token,
}
})
assert.response(res).has.status(200)
assert.request(res).has.no.header("x-anonymous-consumer")
local id = assert.request(res).has.header("x-consumer-id")
assert.not_equal(id, anonymous.id)
assert(id == user1.id or id == user2.id)
end)
it("fails 401, with only the first credential provided", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "logical-and.com",
["apikey"] = "Mouse",
}
})
assert.response(res).has.status(401)
end)
it("fails 401, with only the second credential provided", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "logical-and.com",
-- we must provide the apikey again in the extra_headers, for the
-- token endpoint, because that endpoint is also protected by the
-- key-auth plugin. Otherwise getting the token simply fails.
["Authorization"] = "bearer " .. provision_token("logical-and.com",
{["apikey"] = "Mouse"}).access_token,
}
})
assert.response(res).has.status(401)
end)
it("fails 401, with no credential provided", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "logical-and.com",
}
})
assert.response(res).has.status(401)
end)
end)
describe("multiple auth with anonymous, logical OR", function()
it("passes with all credentials provided", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "logical-or.com",
["apikey"] = "Mouse",
["Authorization"] = "bearer " .. provision_token("logical-or.com").access_token,
}
})
assert.response(res).has.status(200)
assert.request(res).has.no.header("x-anonymous-consumer")
local id = assert.request(res).has.header("x-consumer-id")
assert.not_equal(id, anonymous.id)
assert(id == user1.id or id == user2.id)
end)
it("passes with only the first credential provided", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "logical-or.com",
["apikey"] = "Mouse",
}
})
assert.response(res).has.status(200)
assert.request(res).has.no.header("x-anonymous-consumer")
local id = assert.request(res).has.header("x-consumer-id")
assert.not_equal(id, anonymous.id)
assert.equal(user1.id, id)
end)
it("passes with only the second credential provided", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "logical-or.com",
["Authorization"] = "bearer " .. provision_token("logical-or.com").access_token,
}
})
assert.response(res).has.status(200)
assert.request(res).has.no.header("x-anonymous-consumer")
local id = assert.request(res).has.header("x-consumer-id")
assert.not_equal(id, anonymous.id)
assert.equal(user2.id, id)
end)
it("passes with no credential provided", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "logical-or.com",
}
})
assert.response(res).has.status(200)
assert.request(res).has.header("x-anonymous-consumer")
local id = assert.request(res).has.header("x-consumer-id")
assert.equal(id, anonymous.id)
end)
end)
end)
| apache-2.0 |
Daniex0r/project-roleplay-rp | resources/system-policji/c_sirens.lua | 1 | 2853 | local sounds = { }
-- Bind Keys required
function bindKeys(res)
bindKey("n", "down", toggleSirens)
for key, value in ipairs(getElementsByType("vehicle")) do
if isElementStreamedIn(value) then
if getElementData(value, "lspd:siren") then
sounds[value] = playSound3D("siren.wav", 0, 0, 0, true)
attachElements( sounds[value], value )
setSoundVolume(sounds[value], 0.6)
setSoundMaxDistance(sounds[value], 45)
setElementDimension(sounds[value], getElementDimension(value))
setElementInterior(sounds[value], getElementInterior(value))
end
end
end
end
addEventHandler("onClientResourceStart", getResourceRootElement(), bindKeys)
function toggleSirens()
local theVehicle = getPedOccupiedVehicle(getLocalPlayer())
if (theVehicle) then
if getElementData(theVehicle, "lspd:siren") then
triggerServerEvent("lspd:setSirenState", theVehicle, false)
elseif (exports.global:hasItem(theVehicle, 85)) then
triggerServerEvent("lspd:setSirenState", theVehicle, true)
end
end
end
addCommandHandler("togglecarsirens", toggleSirens, false)
function streamIn()
if getElementType( source ) == "vehicle" and getElementData( source, "lspd:siren" ) and not sounds[ source ] then
sounds[source] = playSound3D("siren.wav", 0, 0, 0, true)
attachElements( sounds[source], source )
setSoundVolume(sounds[source], 0.6)
setSoundMaxDistance(sounds[source], 45)
setElementDimension(sounds[source], getElementDimension(source))
setElementInterior(sounds[source], getElementInterior(source))
end
end
addEventHandler("onClientElementStreamIn", getRootElement(), streamIn)
function streamOut()
if getElementType( source ) == "vehicle" and sounds[source] then
destroyElement( sounds[ source ] )
sounds[ source ] = nil
end
end
addEventHandler("onClientElementStreamOut", getRootElement(), streamOut)
function updateSirens( name )
if name == "lspd:siren" and isElementStreamedIn( source ) and getElementType( source ) == "vehicle" then
local attached = getAttachedElements( source )
if attached then
for key, value in ipairs( attached ) do
if getElementType( value ) == "sound" and value ~= sounds[ source ] then
destroyElement( value )
end
end
end
if not getElementData( source, name ) then
if sounds[ source ] then
destroyElement( sounds[ source ] )
sounds[ source ] = nil
end
else
if not sounds[ source ] then
sounds[source] = playSound3D("siren.wav", 0, 0, 0, true)
attachElements( sounds[source], source )
setSoundVolume(sounds[source], 0.6)
setSoundMaxDistance(sounds[source], 45)
setElementDimension(sounds[source], getElementDimension(source))
setElementInterior(sounds[source], getElementInterior(source))
end
end
end
end
addEventHandler("onClientElementDataChange", getRootElement(), updateSirens)
fileDelete("c_sirens.lua") | gpl-2.0 |
UnluckyNinja/PathOfBuilding | Data/3_0/EnchantmentBoots.lua | 3 | 3230 | -- Item data (c) Grinding Gear Games
return {
["CRUEL"] = {
"Adds 16 to 24 Fire Damage if you've Killed Recently",
"Adds 16 to 24 Cold Damage if you've been Hit Recently",
"Adds 1 to 56 Lightning Damage if you haven't Killed Recently",
"Adds 44 to 64 Chaos Damage if you've taken a Critical Strike Recently",
"8% increased Attack and Cast Speed if you've Killed Recently",
"60% increased Critical Strike Chance if you haven't Crit Recently",
"6% chance to Freeze, Shock and Ignite if you haven't Crit Recently",
"Damage Penetrates 6% of Enemy Elemental Resistances if you haven't Killed Recently",
"10% reduced Mana Cost of Skills if you've been Hit Recently",
"0.4% of Damage Leeched as Life and Mana if you've Killed Recently",
"Regenerate 1% of Life and Mana per second if you were Hit Recently",
"6% Chance to Dodge if you've taken a Critical Strike Recently",
"5% chance to Dodge Spell Damage if you've taken Spell Damage Recently",
"6% increased Movement Speed if you haven't been Hit Recently",
"50% chance to Avoid being Stunned if you've Killed Recently",
},
["MERCILESS"] = {
"Adds 33 to 50 Fire Damage if you've Killed Recently",
"Adds 33 to 50 Cold Damage if you've been Hit Recently",
"Adds 1 to 120 Lightning Damage if you haven't Killed Recently",
"Adds 88 to 132 Chaos Damage if you've taken a Critical Strike Recently",
"12% increased Attack and Cast Speed if you've Killed Recently",
"90% increased Critical Strike Chance if you haven't Crit Recently",
"8% chance to Freeze, Shock and Ignite if you haven't Crit Recently",
"Damage Penetrates 8% of Enemy Elemental Resistances if you haven't Killed Recently",
"14% reduced Mana Cost of Skills if you've been Hit Recently",
"0.5% of Damage Leeched as Life and Mana if you've Killed Recently",
"Regenerate 1.5% of Life and Mana per second if you were Hit Recently",
"8% Chance to Dodge if you've taken a Critical Strike Recently",
"6% chance to Dodge Spell Damage if you've taken Spell Damage Recently",
"8% increased Movement Speed if you haven't been Hit Recently",
"65% chance to Avoid being Stunned if you've Killed Recently",
},
["ENDGAME"] = {
"Adds 45 to 68 Fire Damage if you've Killed Recently",
"Adds 45 to 68 Cold Damage if you've been Hit Recently",
"Adds 1 to 160 Lightning Damage if you haven't Killed Recently",
"Adds 120 to 180 Chaos Damage if you've taken a Critical Strike Recently",
"16% increased Attack and Cast Speed if you've Killed Recently",
"120% increased Critical Strike Chance if you haven't Crit Recently",
"10% chance to Freeze, Shock and Ignite if you haven't Crit Recently",
"Damage Penetrates 10% of Enemy Elemental Resistances if you haven't Killed Recently",
"18% reduced Mana Cost of Skills if you've been Hit Recently",
"0.6% of Damage Leeched as Life and Mana if you've Killed Recently",
"Regenerate 2% of Life and Mana per second if you were Hit Recently",
"10% Chance to Dodge if you've taken a Critical Strike Recently",
"8% chance to Dodge Spell Damage if you've taken Spell Damage Recently",
"10% increased Movement Speed if you haven't been Hit Recently",
"80% chance to Avoid being Stunned if you've Killed Recently",
},
} | mit |
urzq/SpaceFighter | src/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
| mit |
zhs007/sanguo | sanguo/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
| mit |
akh00/kong | spec/03-plugins/07-loggly/01-log_spec.lua | 3 | 4995 | local helpers = require "spec.helpers"
local cjson = require "cjson"
local UDP_PORT = 20000
describe("Plugin: loggly (log)", function()
local client
setup(function()
local api1 = assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "logging.com" },
upstream_url = "http://mockbin.com"
})
local api2 = assert(helpers.dao.apis:insert {
name = "api-2",
hosts = { "logging1.com" },
upstream_url = "http://mockbin.com"
})
local api3 = assert(helpers.dao.apis:insert {
name = "api-3",
hosts = { "logging2.com" },
upstream_url = "http://mockbin.com"
})
local api4 = assert(helpers.dao.apis:insert {
name = "api-4",
hosts = { "logging3.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
api_id = api1.id,
name = "loggly",
config = {
host = "127.0.0.1",
port = UDP_PORT,
key = "123456789",
log_level = "info",
successful_severity = "warning"
}
})
assert(helpers.dao.plugins:insert {
api_id = api2.id,
name = "loggly",
config = {
host = "127.0.0.1",
port = UDP_PORT,
key = "123456789",
log_level = "debug",
timeout = 2000,
successful_severity = "info"
}
})
assert(helpers.dao.plugins:insert {
api_id = api3.id,
name = "loggly",
config = {
host = "127.0.0.1",
port = UDP_PORT,
key = "123456789",
log_level = "crit",
successful_severity = "crit",
client_errors_severity = "warning"
}
})
assert(helpers.dao.plugins:insert {
api_id = api4.id,
name = "loggly",
config = {
host = "127.0.0.1",
port = UDP_PORT,
key = "123456789"
}
})
assert(helpers.start_kong())
end)
teardown(function()
helpers.stop_kong()
end)
before_each(function()
client = helpers.proxy_client()
end)
after_each(function()
if client then client:close() end
end)
-- Helper; performs a single http request and catches the udp log output.
-- @param message the message table for the http client
-- @param status expected status code from the request, defaults to 200 if omitted
-- @return 2 values; 'pri' field (string) and the decoded json content (table)
local function run(message, status)
local thread = assert(helpers.udp_server(UDP_PORT))
local response = assert(client:send(message))
assert.res_status(status or 200, response)
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
local pri = assert(res:match("^<(%d-)>"))
local json = assert(res:match("{.*}"))
return pri, cjson.decode(json)
end
it("logs to UDP when severity is warning and log level info", function()
local pri, message = run({
method = "GET",
path = "/request",
headers = {
host = "logging.com"
}
})
assert.equal("12", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity is info and log level debug", function()
local pri, message = run({
method = "GET",
path = "/request",
headers = {
host = "logging1.com"
}
})
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity is critical and log level critical", function()
local pri, message = run({
method = "GET",
path = "/request",
headers = {
host = "logging2.com"
}
})
assert.equal("10", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity and log level are default values", function()
local pri, message = run({
method = "GET",
path = "/",
headers = {
host = "logging3.com"
}
})
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity and log level are default values and response status is 200", function()
local pri, message = run({
method = "GET",
path = "/",
headers = {
host = "logging3.com"
}
})
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity and log level are default values and response status is 401", function()
local pri, message = run({
method = "GET",
path = "/status/401/",
headers = {
host = "logging3.com"
}
}, 401)
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity and log level are default values and response status is 500", function()
local pri, message = run({
method = "GET",
path = "/status/500/",
headers = {
host = "logging3.com"
}
}, 500)
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
end)
| apache-2.0 |
UnluckyNinja/PathOfBuilding | Classes/CheckBoxControl.lua | 1 | 2127 | -- Path of Building
--
-- Class: Check Box Control
-- Basic check box control.
--
local launch, main = ...
local CheckBoxClass = common.NewClass("CheckBoxControl", "Control", "TooltipHost", function(self, anchor, x, y, size, label, changeFunc, tooltipText)
self.Control(anchor, x, y, size, size)
self.TooltipHost(tooltipText)
self.label = label
self.changeFunc = changeFunc
end)
function CheckBoxClass:IsMouseOver()
if not self:IsShown() then
return false
end
return self:IsMouseInBounds()
end
function CheckBoxClass:Draw(viewPort)
local x, y = self:GetPos()
local size = self.width
local enabled = self:IsEnabled()
local mOver = self:IsMouseOver()
if not enabled then
SetDrawColor(0.33, 0.33, 0.33)
elseif mOver then
SetDrawColor(1, 1, 1)
else
SetDrawColor(0.5, 0.5, 0.5)
end
DrawImage(nil, x, y, size, size)
if not enabled then
SetDrawColor(0, 0, 0)
elseif self.clicked and mOver then
SetDrawColor(0.5, 0.5, 0.5)
elseif mOver then
SetDrawColor(0.33, 0.33, 0.33)
else
SetDrawColor(0, 0, 0)
end
DrawImage(nil, x + 1, y + 1, size - 2, size - 2)
if self.state then
if not enabled then
SetDrawColor(0.33, 0.33, 0.33)
elseif mOver then
SetDrawColor(1, 1, 1)
else
SetDrawColor(0.75, 0.75, 0.75)
end
main:DrawCheckMark(x + size/2, y + size/2, size * 0.8)
end
if enabled then
SetDrawColor(1, 1, 1)
else
SetDrawColor(0.33, 0.33, 0.33)
end
local label = self:GetProperty("label")
if label then
DrawString(x - 5, y + 2, "RIGHT_X", size - 4, "VAR", label)
end
if mOver then
SetDrawLayer(nil, 100)
self:DrawTooltip(x, y, size, size, viewPort, self.state)
SetDrawLayer(nil, 0)
end
end
function CheckBoxClass:OnKeyDown(key)
if not self:IsShown() or not self:IsEnabled() then
return
end
if key == "LEFTBUTTON" then
self.clicked = true
end
return self
end
function CheckBoxClass:OnKeyUp(key)
if not self:IsShown() or not self:IsEnabled() then
return
end
if key == "LEFTBUTTON" then
if self:IsMouseOver() then
self.state = not self.state
if self.changeFunc then
self.changeFunc(self.state)
end
end
end
self.clicked = false
end
| mit |
ondravondra/vlc | share/lua/playlist/france2.lua | 113 | 2115 | --[[
$Id$
Copyright © 2008 the VideoLAN team
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "jt.france2.fr/player/" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "class=\"editiondate\"" ) then
_,_,editiondate = string.find( line, "<h1>(.-)</h1>" )
end
if string.match( line, "mms.*%.wmv" ) then
_,_,video = string.find( line, "mms(.-%.wmv)" )
video = "mmsh"..video
table.insert( p, { path = video; name = editiondate } )
end
if string.match( line, "class=\"subjecttimer\"" ) then
oldtime = time
_,_,time = string.find( line, "href=\"(.-)\"" )
if oldtime then
table.insert( p, { path = video; name = name; duration = time - oldtime; options = { ':start-time='..tostring(oldtime); ':stop-time='..tostring(time) } } )
end
name = vlc.strings.resolve_xml_special_chars( string.gsub( line, "^.*>(.*)<..*$", "%1" ) )
end
end
if oldtime then
table.insert( p, { path = video; name = name; options = { ':start-time='..tostring(time) } } )
end
return p
end
| gpl-2.0 |
LucentW/s-uzzbot | plugins/help.lua | 4 | 5209 | do
function pairsByKeys(t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
-- Returns true if is not empty
local function has_usage_data(dict)
if (dict.usage == nil or dict.usage == '') then
return false
end
return true
end
-- Get commands for that plugin
local function plugin_help(name,number,requester)
local plugin = ""
if number then
local i = 0
for name in pairsByKeys(plugins) do
if plugins[name].hidden or plugins[name].hide then
name = nil
else
i = i + 1
if i == tonumber(number) then
plugin = plugins[name]
end
end
end
else
plugin = plugins[name]
if not plugin then return nil end
end
local text = ""
if (type(plugin.usage) == "table") then
for ku,usage in pairs(plugin.usage) do
if ku == 'user' then -- usage for user
if (type(plugin.usage.user) == "table") then
for k,v in pairs(plugin.usage.user) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.user..'\n'
end
elseif ku == 'moderator' then -- usage for moderator
if requester == 'moderator' or requester == 'admin' or requester == 'sudo' then
if (type(plugin.usage.moderator) == "table") then
for k,v in pairs(plugin.usage.moderator) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.moderator..'\n'
end
end
elseif ku == 'admin' then -- usage for admin
if requester == 'admin' or requester == 'sudo' then
if (type(plugin.usage.admin) == "table") then
for k,v in pairs(plugin.usage.admin) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.admin..'\n'
end
end
elseif ku == 'sudo' then -- usage for sudo
if requester == 'sudo' then
if (type(plugin.usage.sudo) == "table") then
for k,v in pairs(plugin.usage.sudo) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.sudo..'\n'
end
end
else
text = text..usage..'\n'
end
end
text = text..'======================\n'
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage..'\n======================\n'
end
return text
end
-- !help command
local function telegram_help()
local i = 0
local text = str2emoji(':information_source:').." Plugins list:\n\n"
-- Plugins names
for name in pairsByKeys(plugins) do
if plugins[name].hidden or plugins[name].hide then
name = nil
elseif plugins[name].usage == nil then
name = nil
else
i = i + 1
text = text..i..'. '..name..'\n'
end
end
text = text..'\n'..str2emoji(':electric_plug:')..' There are '..i..' plugins with usage available.'
text = text..'\n'..str2emoji(":point_right:")..' Write "!help [plugin name]" or "!help [plugin number]" for more info.'
text = text..'\n'..str2emoji(":mag_right:")..' Or "!help all" to show all usage infos.'
return text
end
-- !help all command
local function help_all(requester)
local ret = ""
for name in pairsByKeys(plugins) do
if plugins[name].hidden or plugins[name].hide then
name = nil
else
ret = ret .. plugin_help(name, nil, requester)
end
end
return ret
end
local function run(msg, matches)
if is_sudo(msg) then
requester = "sudo"
elseif is_admin(msg) then
requester = "admin"
elseif is_momod(msg) then
requester = "moderator"
else
requester = "user"
end
if matches[1] == "!help" then
return telegram_help()
elseif matches[1] == "!help all" then
return help_all(requester)
else
local text = ""
if tonumber(matches[1]) then
text = plugin_help(nil, matches[1], requester)
else
text = plugin_help(matches[1], nil, requester)
end
if not text then
text = telegram_help()
end
return text
end
end
return {
description = "Help plugin. Get info from other plugins. ",
usage = {
"!help: Show list of plugins.",
"!help all: Show all commands for every plugin.",
"!help [plugin name]: Commands for that plugin.",
"!help [number]: Commands for that plugin. Type !help to get the plugin number."
},
patterns = {
"^!help$",
"^!help all",
"^/start$",
"^!help (.+)"
},
run = run
}
end
| gpl-2.0 |
mrfoxirani/teleseed-2 | 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 |
marshmellow42/proxmark3 | client/scripts/lf_bulk_program.lua | 5 | 4681 | --
-- lf_bulk_program.lua - A tool to clone a large number of tags at once.
-- Updated 2017-04-18
--
-- The getopt-functionality is loaded from pm3/client/lualibs/getopt.lua
-- Have a look there for further details
getopt = require('getopt')
bit32 = require('bit32')
usage = [[ script run lf_bulk_program.lua -f facility -b base_id_num -c count
e.g:
script run lf_bulk_program.lua -f 1 -b 1000 -c 10
]]
author = "Brian Redbeard"
desc =[[
Perform bulk enrollment of 26 bit H10301 style RFID Tags
For more info, check the comments in the code
]]
--[[Implement a function to simply visualize the bitstream in a text format
--This is especially helpful for troubleshooting bitwise math issues]]--
function toBits(num,bits)
-- returns a table of bits, most significant first.
bits = bits or math.max(1, select(2, math.frexp(num)))
local t = {} -- will contain the bits
for b = bits, 1, -1 do
t[b] = math.fmod(num, 2)
num = math.floor((num - t[b]) / 2)
end
return table.concat(t)
end
--[[Likely, I'm an idiot, but I couldn't find any parity functions in Lua
This can also be done with a combination of bitwise operations (in fact,
is the canonically "correct" way to do it, but my brain doesn't just
default to this and so counting some ones is good enough for me]]--
local function evenparity(s)
local _, count = string.gsub(s, "1", "")
local p = count % 2
if (p == 0) then
return(false)
else
return(true)
end
end
local function isempty(s)
return s == nil or s == ''
end
--[[The Proxmark3 "clone" functions expect the data to be in hex format so
take the card id number and facility ID as arguments and construct the
hex. This should be easy enough to extend to non 26bit formats]]--
local function cardHex(i,f)
fac = bit32.lshift(f,16)
id = bit32.bor(i, fac)
stream=toBits(id,24)
--As the function defaults to even parity and returns a boolean,
--perform a 'not' function to get odd parity
high = evenparity(string.sub(stream,1,12)) and 1 or 0
low = not evenparity(string.sub(stream,13)) and 1 or 0
bits = bit32.bor(bit32.lshift(id,1), low)
bits = bit32.bor(bits, bit32.lshift(high,25))
--Since the lua library bit32 is (obviously) 32 bits and we need to
--encode 36 bits to properly do a 26 bit tag with the preamble we need
--to create a higher order and lower order component which we will
--then assemble in the return. The math above defines the proper
--encoding as per HID/Weigand/etc. These bit flips are due to the
--format length check on bit 38 (cmdlfhid.c:64) and
--bit 31 (cmdlfhid.c:66).
preamble = bit32.bor(0, bit32.lshift(1,5))
bits = bit32.bor(bits, bit32.lshift(1,26))
return ("%04x%08x"):format(preamble,bits)
end
local function main(args)
--I really wish a better getopt function would be brought in supporting
--long arguments, but it seems this library was chosen for BSD style
--compatibility
for o, a in getopt.getopt(args, 'f:b:c:h') do
if o == 'f' then
if isempty(a) then
print("You did not supply a facility code, using 0")
facility = 0
else
facility = a
end
elseif o == 'b' then
if isempty(a) then
print("You must supply the flag -b (base id)")
return
else
baseid = a
end
elseif o == 'c' then
if isempty(a) then
print("You must supply the flag -c (count)")
return
else
count = a
end
elseif o == 'h' then
print(desc)
print(usage)
return
end
end
--Due to my earlier complaints about how this specific getopt library
--works, specifying ":" does not enforce supplying a value, thus we
--need to do these checks all over again.
if isempty(baseid) then
print("You must supply the flag -b (base id)")
print(usage)
return
end
if isempty(count) then
print("You must supply the flag -c (count)")
print(usage)
return
end
--If the facility ID is non specified, ensure we code it as zero
if isempty(facility) then
print("Using 0 for the facility code as -f was not supplied")
facility = 0
end
--The next baseid + count function presents a logic/UX conflict
--where users specifying -c 1 (count = 1) would try to program two
--tags. This makes it so that -c 0 & -c 1 both code one tag, and all
--other values encode the expected amount.
if tonumber(count) > 0 then count = count -1 end
endid = baseid + count
for cardnum = baseid,endid do
local card = cardHex(cardnum, facility)
print("Press enter to program card "..cardnum..":"..facility.." (hex: "..card..")")
--This would be better with "press any key", but we'll take
--what we can get.
io.read()
core.console( ('lf hid clone %s'):format(card) )
end
end
main(args)
| gpl-2.0 |
artynet/luci | modules/luci-base/luasrc/sgi/uhttpd.lua | 79 | 1956 | -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require "nixio.util"
require "luci.http"
require "luci.sys"
require "luci.dispatcher"
require "luci.ltn12"
function handle_request(env)
exectime = os.clock()
local renv = {
CONTENT_LENGTH = env.CONTENT_LENGTH,
CONTENT_TYPE = env.CONTENT_TYPE,
REQUEST_METHOD = env.REQUEST_METHOD,
REQUEST_URI = env.REQUEST_URI,
PATH_INFO = env.PATH_INFO,
SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""),
SCRIPT_FILENAME = env.SCRIPT_NAME,
SERVER_PROTOCOL = env.SERVER_PROTOCOL,
QUERY_STRING = env.QUERY_STRING
}
local k, v
for k, v in pairs(env.headers) do
k = k:upper():gsub("%-", "_")
renv["HTTP_" .. k] = v
end
local len = tonumber(env.CONTENT_LENGTH) or 0
local function recv()
if len > 0 then
local rlen, rbuf = uhttpd.recv(4096)
if rlen >= 0 then
len = len - rlen
return rbuf
end
end
return nil
end
local send = uhttpd.send
local req = luci.http.Request(
renv, recv, luci.ltn12.sink.file(io.stderr)
)
local x = coroutine.create(luci.dispatcher.httpdispatch)
local hcache = { }
local active = true
while coroutine.status(x) ~= "dead" do
local res, id, data1, data2 = coroutine.resume(x, req)
if not res then
send("Status: 500 Internal Server Error\r\n")
send("Content-Type: text/plain\r\n\r\n")
send(tostring(id))
break
end
if active then
if id == 1 then
send("Status: ")
send(tostring(data1))
send(" ")
send(tostring(data2))
send("\r\n")
elseif id == 2 then
hcache[data1] = data2
elseif id == 3 then
for k, v in pairs(hcache) do
send(tostring(k))
send(": ")
send(tostring(v))
send("\r\n")
end
send("\r\n")
elseif id == 4 then
send(tostring(data1 or ""))
elseif id == 5 then
active = false
elseif id == 6 then
data1:copyz(nixio.stdout, data2)
end
end
end
end
| apache-2.0 |
dmccuskey/dmc-wamp | examples/dmc-wamp-publish/dmc_corona/dmc_sockets/async_tcp.lua | 14 | 12640 | --====================================================================--
-- dmc_sockets/async_tcp.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2014-2015 David McCuskey
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.
--]]
--====================================================================--
--== DMC Corona Library : Async TCP
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.4.0"
--====================================================================--
--== Imports
local Objects = require 'lib.dmc_lua.lua_objects'
local socket = require 'socket'
local SSLParams = require 'dmc_sockets.ssl_params'
local TCPSocket = require 'dmc_sockets.tcp'
--====================================================================--
--== Setup, Constants
local tconcat = table.concat
local tinsert = table.insert
local tremove = table.remove
local ssl
local LOCAL_DEBUG = false
--====================================================================--
--== Support Functions
local function loadSSL()
local openssl = require 'plugin.openssl'
ssl = require 'plugin_luasec_ssl'
end
--====================================================================--
--== Async TCP Socket Class
--====================================================================--
local ATCPSocket = newClass( TCPSocket, { name="Async TCP Socket" } )
--======================================================--
-- Start: Setup Lua Objects
function ATCPSocket:__init__( params )
-- print( "ATCPSocket:__init__" )
params = params or {}
self:superCall( '__init__', params )
--==--
--== Create Properties ==--
self._timeout = 6000
self.__coroutine_queue_active = false
self._coroutine_queue = {}
self._read_in_process = false
self._ssl_params = params.ssl_params
--== Object References ==--
end
function ATCPSocket:__initComplete__()
-- print( "ATCPSocket:__initComplete__" )
self:superCall( '__initComplete__' )
--==--
self.ssl_params = self._ssl_params -- use setter
end
-- END: Setup Lua Objects
--======================================================--
--====================================================================--
--== Public Methods
function ATCPSocket.__getters:timeout( value )
self._timeout = value
end
function ATCPSocket.__setters:ssl_params( value )
-- print( "ATCPSocket.__setters:ssl_params", value )
assert( value==nil or type(value)=='table', "ATCPSocket.ssl_params incorrect value" )
--==--
if value == nil then
-- TODO: properly destroy
self._ssl_params = nil
elseif value.isa and value:isa( SSLParams ) then
self._ssl_params = value
else
self._ssl_params = SSLParams:new( value )
end
end
function ATCPSocket.__getters:ssl_params( value )
-- print( "ATCPSocket.__getters:ssl_params", is_secure )
return self._ssl_params
end
function ATCPSocket.__setters:secure( is_secure )
-- print( "ATCPSocket.__setters:secure", is_secure )
if not is_secure then
self._ssl_params = nil
elseif is_secure and self._ssl_params == nil then
self._ssl_params = SSLParams:new()
end
if is_secure and not ssl then loadSSL() end
end
function ATCPSocket.__getters:secure()
-- print( "ATCPSocket.__getters:secure" )
return (self._ssl_params ~= nil)
end
function ATCPSocket:connect( host, port, params )
-- print( 'ATCPSocket:connect', host, port, params )
params = params or {}
--==--
self._host = host
self._port = port
self._onConnect = params.onConnect
self._onData = params.onData
if self._status == ATCPSocket.CONNECTED then
local evt = {
type=self.CONNECT,
emsg=self.ERR_CONNECTED
}
if self._onConnect then self._onConnect( evt ) end
return
end
self:_createSocket( { timeout=0 } )
local f = function()
local beg_time = system.getTimer()
local timeout, time_diff = self._timeout, 0
local evt = {}
repeat
local success, emsg = self._socket:connect( host, port )
if LOCAL_DEBUG then
print( "dmc.ATCP: connect", success, emsg )
end
-- messages:
-- nil timeout
-- nil Operation already in progress
-- nil already connected
if success or emsg == self.ERR_CONNECTED then
self._status = self.CONNECTED
evt.type = self.CONNECT
evt.status = self._status
evt.emsg = emsg
if self.secure == true then
local sock, emsg = ssl.wrap( self._socket, self.ssl_params )
if sock then
self._socket = sock
else
evt.isError = true
evt.emsg = emsg
if self._onConnect then self._onConnect( evt ) end
return
end
local result, emsg = self._socket:dohandshake()
if not result then
evt.isError = true
evt.emsg = emsg
if self._onConnect then self._onConnect( evt ) end
return
end
self._socket:settimeout( 0 ) -- need to re-set for wrapped socket
self._socket:setoption( 'keepalive', true )
self._socket:setoption( 'tcp-nodelay', true )
end
self._master:_connect( self )
self:_removeCoroutineFromQueue()
if self._onConnect then self._onConnect( evt ) end
else
coroutine.yield()
end
time_diff = system.getTimer() - beg_time
until time_diff > timeout or self._status == self.CONNECTED
if self._status ~= self.CONNECTED then
self._status = self.NOT_CONNECTED
evt.type = self.CONNECT
evt.status = self._status
evt.emsg = self.ERR_TIMEOUT
self:_removeCoroutineFromQueue()
if self._onConnect then self._onConnect( evt ) end
end
end
self:_addCoroutineToQueue( f )
end
function ATCPSocket:send( data, callback )
-- print( 'ATCPSocket:send', #data, callback )
-- TODO: error handling
local bytes, emsg, index = self._socket:send( data )
local evt = {}
-- print( 'sent', bytes, emsg )
evt.isError = nil
evt.emsg = nil
if callback then callback( evt ) end
end
function ATCPSocket:receive( option, callback )
-- print( 'ATCPSocket:receive', option, callback )
if not callback or type( callback ) ~= 'function' then return end
local buffer = self._buffer
local evt = {}
local data
if type( option ) == 'string' and option == '*a' then
data = buffer
self._buffer = ""
evt.data, evt.emsg = data, nil
callback( evt )
return
elseif type( option ) == 'number' and #buffer >= option then
data = string.sub( buffer, 1, option )
self._buffer = string.sub( buffer, option+1 )
callback( { data=data, emsg=nil } )
elseif type( option ) == 'string' and option == '*l' then
-- create coroutine function
local f = function( not_coroutine )
local beg_time = system.getTimer()
local timeout, time_diff = self._timeout, 0
repeat
data = self:superCall( "receive", option )
if not_coroutine then return data end
if not data then
coroutine.yield()
else
self._read_in_process = false
evt.data, evt.emsg = data, nil
callback( evt )
end
time_diff = system.getTimer() - beg_time
until data or time_diff > timeout
if not data then
self._read_in_process = false
evt.data, evt.emsg = nil, self.ERR_TIMEOUT
callback( evt )
end
end
self._read_in_process = true
data = f( true )
if data then
self._read_in_process = false
evt.data, evt.emsg = data, nil
callback( evt )
else
local co = coroutine.create( f )
table.insert( self._coroutine_queue, co )
end
end
end
function ATCPSocket:receiveUntilNewline( callback )
-- print( 'ATCPSocket:receiveUntilNewline' )
assert( type(callback)=='function', "receiveUntilNewline: expected function callback" )
--==--
local data_list = {}
local evt = {}
-- create coroutine function
local doDataCall = function( not_coroutine )
-- print( "do data call", not_coroutine )
local beg_time = system.getTimer()
local timeout, time_diff = self._timeout, 0
repeat
local data = self:superCall( 'receive', '*l' )
-- data handling
if data then
tinsert( data_list, data )
if data == '' then
if not_coroutine then
return true
else
self:_removeCoroutineFromQueue()
evt.data, evt.emsg = data_list, nil
callback( evt )
end
end
end
-- control
if not data then
if not_coroutine then
return false
else
coroutine.yield()
end
end
time_diff = system.getTimer() - beg_time
until data == '' or time_diff > timeout
self:_removeCoroutineFromQueue()
if data_list[#data_list] ~= '' then
if #data_list > 0 then
local str = tconcat( data_list, '\r\n' )
self:unreceive( str )
end
evt.data, evt.emsg = nil, self.ERR_TIMEOUT
callback( evt )
end
end -- doDataCall
-- run doDataCall, see if we have data now
-- otherwise put in coroutine loop
if doDataCall( true ) == true then
evt.data, evt.emsg = data_list, nil
callback( evt )
else
if #data_list > 0 then
local str = tconcat( data_list, '\r\n' )
self:unreceive( str )
end
self:_addCoroutineToQueue( doDataCall )
end
end
--====================================================================--
--== Private Methods
function ATCPSocket:_closeSocketDispatch( evt )
-- print( 'ATCPSocket:_closeSocketDispatch', evt )
evt.type = self.CONNECT
if self._onConnect then self._onConnect( evt ) end
end
function ATCPSocket:_doAfterReadAction()
-- print( 'ATCPSocket:_doAfterReadAction' )
local buff_len = #self._buffer
if buff_len > 0 then
self:_processCoroutineQueue()
end
buff_len = #self._buffer
if buff_len > 0 and not self._read_in_process then
local evt = {
type=self.READ,
status = self._status,
bytes = buff_len
}
if self._onData then self._onData( evt ) end
end
end
function ATCPSocket:_getActiveCoroutine()
-- print( 'ATCPSocket:_getActiveCoroutine' )
return self._coroutine_queue[ 1 ]
end
function ATCPSocket:_addCoroutineToQueue( func )
-- print( 'ATCPSocket:_addCoroutineToQueue' )
assert( type(func)=='function', "expected function" )
--==--
local co = coroutine.create( func )
tinsert( self._coroutine_queue, co )
-- if we still have info left, then set listener
if not self._coroutine_queue_active and #self._coroutine_queue > 0 then
Runtime:addEventListener( 'enterFrame', self )
self._coroutine_queue_active = true
end
end
function ATCPSocket:_removeCoroutineFromQueue()
-- print( 'ATCPSocket:_removeCoroutineFromQueue' )
-- assert( type(func)=='function', "expected function" )
--==--
if #self._coroutine_queue > 0 then
tremove( self._coroutine_queue, 1 )
end
-- if no more routines, then unset listener
if #self._coroutine_queue == 0 and self._coroutine_queue_active then
Runtime:removeEventListener( 'enterFrame', self )
self._coroutine_queue_active = false
end
end
function ATCPSocket:_processCoroutineQueue()
-- print( 'ATCPSocket:_processCoroutineQueue' )
local co = self:_getActiveCoroutine()
if co then
local status, msg = coroutine.resume( co )
if not status then
self:_removeCoroutineFromQueue()
print( "ERROR in async_tcp coroutine" )
error( msg )
end
if coroutine.status( co ) ~= 'dead' then return end
end
-- coroutine is finished, remove it
self:_removeCoroutineFromQueue()
end
--====================================================================--
--== Event Handlers
function ATCPSocket:_socketsEvent_handler( event )
-- print( 'ATCPSocket:_socketsEvent_handler', event )
self:_processCoroutineQueue()
end
function ATCPSocket:enterFrame( event )
-- print( 'ATCPSocket:enterFrame', event )
self:_processCoroutineQueue()
end
return ATCPSocket
| mit |
changeway/packages | net/prosody/files/prosody.cfg.lua | 65 | 9428 | -- Prosody Example Configuration File
--
-- Information on configuring Prosody can be found on our
-- website at https://prosody.im/doc/configure
--
-- Tip: You can check that the syntax of this file is correct
-- when you have finished by running this command:
-- prosodyctl check config
-- If there are any errors, it will let you know what and where
-- they are, otherwise it will keep quiet.
--
-- The only thing left to do is rename this file to remove the .dist ending, and fill in the
-- blanks. Good luck, and happy Jabbering!
---------- Server-wide settings ----------
-- Settings in this section apply to the whole server and are the default settings
-- for any virtual hosts
-- This is a (by default, empty) list of accounts that are admins
-- for the server. Note that you must create the accounts separately
-- (see https://prosody.im/doc/creating_accounts for info)
-- Example: admins = { "user1@example.com", "user2@example.net" }
admins = { }
-- Enable use of libevent for better performance under high load
-- For more information see: https://prosody.im/doc/libevent
--use_libevent = true
-- Prosody will always look in its source directory for modules, but
-- this option allows you to specify additional locations where Prosody
-- will look for modules first. For community modules, see https://modules.prosody.im/
--plugin_paths = {}
-- This is the list of modules Prosody will load on startup.
-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
-- Documentation on modules can be found at: http://prosody.im/doc/modules
modules_enabled = {
-- Generally required
"roster"; -- Allow users to have a roster. Recommended ;)
"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"dialback"; -- s2s dialback support
"disco"; -- Service discovery
-- Not essential, but recommended
"carbons"; -- Keep multiple clients in sync
"pep"; -- Enables users to publish their avatar, mood, activity, playing music and more
"private"; -- Private XML storage (for room bookmarks, etc.)
"blocklist"; -- Allow users to block communications with other users
"vcard4"; -- User profiles (stored in PEP)
"vcard_legacy"; -- Conversion between legacy vCard and PEP Avatar, vcard
-- Nice to have
"version"; -- Replies to server version requests
"uptime"; -- Report how long server has been running
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"register"; -- Allow users to register on this server using a client and change passwords
--"mam"; -- Store messages in an archive and allow users to access it
--"csi_simple"; -- Simple Mobile optimizations
-- Admin interfaces
"admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
--"admin_telnet"; -- Opens telnet console interface on localhost port 5582
-- HTTP modules
--"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"
--"websocket"; -- XMPP over WebSockets
--"http_files"; -- Serve static files from a directory over HTTP
-- Other specific functionality
--"limits"; -- Enable bandwidth limiting for XMPP connections
--"groups"; -- Shared roster support
--"server_contact_info"; -- Publish contact information for this service
--"announce"; -- Send announcement to all online users
--"welcome"; -- Welcome users who register accounts
--"watchregistrations"; -- Alert admins of registrations
--"motd"; -- Send a message to users when they log in
--"legacyauth"; -- Legacy authentication. Only used by some old clients and bots.
--"proxy65"; -- Enables a file transfer proxy service which clients behind NAT can use
}
-- These modules are auto-loaded, but should you want
-- to disable them then uncomment them here:
modules_disabled = {
-- "offline"; -- Store offline messages
-- "c2s"; -- Handle client connections
-- "s2s"; -- Handle server-to-server connections
-- "posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
}
-- Disable account creation by default, for security
-- For more information see https://prosody.im/doc/creating_accounts
allow_registration = false
-- Force clients to use encrypted connections? This option will
-- prevent clients from authenticating unless they are using encryption.
c2s_require_encryption = true
-- Force servers to use encrypted connections? This option will
-- prevent servers from authenticating unless they are using encryption.
s2s_require_encryption = true
-- Force certificate authentication for server-to-server connections?
s2s_secure_auth = false
-- Some servers have invalid or self-signed certificates. You can list
-- remote domains here that will not be required to authenticate using
-- certificates. They will be authenticated using DNS instead, even
-- when s2s_secure_auth is enabled.
--s2s_insecure_domains = { "insecure.example" }
-- Even if you disable s2s_secure_auth, you can still require valid
-- certificates for some domains by specifying a list here.
--s2s_secure_domains = { "jabber.org" }
-- Select the authentication backend to use. The 'internal' providers
-- use Prosody's configured data storage to store the authentication data.
authentication = "internal_hashed"
-- Select the storage backend to use. By default Prosody uses flat files
-- in its configured data directory, but it also supports more backends
-- through modules. An "sql" backend is included by default, but requires
-- additional dependencies. See https://prosody.im/doc/storage for more info.
--storage = "sql" -- Default is "internal"
-- For the "sql" backend, you can uncomment *one* of the below to configure:
--sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename.
--sql = { driver = "MySQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
--sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
-- Archiving configuration
-- If mod_mam is enabled, Prosody will store a copy of every message. This
-- is used to synchronize conversations between multiple clients, even if
-- they are offline. This setting controls how long Prosody will keep
-- messages in the archive before removing them.
archive_expires_after = "1w" -- Remove archived messages after 1 week
-- You can also configure messages to be stored in-memory only. For more
-- archiving options, see https://prosody.im/doc/modules/mod_mam
-- Logging configuration
-- For advanced logging see http://prosody.im/doc/logging
log = {
info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging
error = "/var/log/prosody/prosody.err";
-- "*syslog"; -- Uncomment this for logging to syslog; needs mod_posix
-- "*console"; -- Log to the console, useful for debugging with daemonize=false
}
-- Uncomment to enable statistics
-- For more info see https://prosody.im/doc/statistics
-- statistics = "internal"
-- Pidfile, used by prosodyctl and the init.d script
pidfile = "/var/run/prosody/prosody.pid"
-- User and group, used for daemon
prosody_user = "prosody"
prosody_group = "prosody"
-- Certificates
-- Every virtual host and component needs a certificate so that clients and
-- servers can securely verify its identity. Prosody will automatically load
-- certificates/keys from the directory specified here.
-- For more information, including how to use 'prosodyctl' to auto-import certificates
-- (from e.g. Let's Encrypt) see https://prosody.im/doc/certificates
-- Location of directory to find certificates in (relative to main config file):
--certificates = "certs"
-- HTTPS currently only supports a single certificate, specify it here:
--https_certificate = "certs/localhost.crt"
----------- Virtual hosts -----------
-- You need to add a VirtualHost entry for each domain you wish Prosody to serve.
-- Settings under each VirtualHost entry apply *only* to that host.
VirtualHost "localhost"
VirtualHost "example.com"
enabled = false -- Remove this line to enable this host
-- Assign this host a certificate for TLS, otherwise it would use the one
-- set in the global section (if any).
-- Note that old-style SSL on port 5223 only supports one certificate, and will always
-- use the global one.
ssl = {
key = "/etc/prosody/certs/example.com.key";
certificate = "/etc/prosody/certs/example.com.crt";
}
------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
-- For more information on components, see http://prosody.im/doc/components
---Set up a MUC (multi-user chat) room server on conference.example.com:
--Component "conference.example.com" "muc"
-- Set up a SOCKS5 bytestream proxy for server-proxied file transfers:
--Component "proxy.example.com" "proxy65"
--- Store MUC messages in an archive and allow users to access it
--modules_enabled = { "muc_mam" }
---Set up an external component (default component port is 5347)
--
-- External components allow adding various services, such as gateways/
-- transports to other networks like ICQ, MSN and Yahoo. For more info
-- see: http://prosody.im/doc/components#adding_an_external_component
--
--Component "gateway.example.com"
-- component_secret = "password"
| gpl-2.0 |
nimaghorbani/telenima2 | plugins/bankickp.lua | 1 | 10514 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
local function ban_user(user_id, chat_id)
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
-- Save to redis
local hash = 'superbanned:'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned or false
end
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
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, msg.to.id)
if superbanned or banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, chat_id)
if superbanned then
print('SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
end
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if get_cmd == 'kick' then
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'superban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!')
return superban_user(member_id, chat_id)
elseif get_cmd == 'whitelist user' then
local hash = 'whitelist:user#id'..member_id
redis:set(hash, true)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted')
elseif get_cmd == 'whitelist delete user' then
local hash = 'whitelist:user#id'..member_id
redis:del(hash)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist')
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1] == 'باي @raobot' then
kick_user(msg.from.id, msg.to.id)
end
if not is_momod(msg) then
return nil
end
local receiver = get_receiver(msg)
if matches[4] then
get_cmd = matches[1]..' '..matches[2]..' '..matches[3]
elseif matches[3] then
get_cmd = matches[1]..' '..matches[2]
else
get_cmd = matches[1]
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
ban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'superban' and is_admin(msg) then
local user_id = matches[3]
local chat_id = msg.to.id
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
superban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' globally banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'superbanned:'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
kick_user(matches[2], msg.to.id)
else
local member = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
if string.match(matches[4], '^%d+$') then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
else
local member = string.gsub(matches[4], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
user = "باي @raobot: Exit from group",
moderator = {
"!whitelist <enable>/<disable> : Enable or disable whitelist mode",
"!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id> : Remove user from whitelist",
"!whitelist delete chat : Remove chat from whitelist",
"!ban user <user_id> : Kick user from chat and kicks it if joins chat again",
"!ban user <username> : Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id> : Unban user",
"!kick <user_id> : Kick user from chat group by id",
"!kick <username> : Kick user from chat group by username",
},
admin = {
"!superban user <user_id> : Kick user from all chat and kicks it if joins again",
"!superban user <username> : Kick user from all chat and kicks it if joins again",
"!superban delete <user_id> : Unban user",
},
},
patterns = {
"^([Ww]hitelist) (enable)$",
"^([Ww]hitelist) (disable)$",
"^([Ww]hitelist) (user) (.*)$",
"^([Ww]hitelist) (chat)$",
"^([Ww]hitelist) (delete) (user) (.*)$",
"^([Ww]hitelist) (delete) (chat)$",
"^([Bb]an) (user) (.*)$",
"^([Bb]an) (delete) (.*)$",
"^([Ss]uperban) (user) (.*)$",
"^([Ss]uperban) (delete) (.*)$",
"^([Kk]ick) (.*)$",
"^(باي @raobot)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
LucentW/s-uzzbot | plugins/pokedex.lua | 3 | 1803 | do
local images_enabled = true;
local function get_sprite(path)
local url = "http://pokeapi.co/"..path
print(url)
local b,c = http.request(url)
local data = json:decode(b)
local image = data.image
return image
end
local function callback(extra)
send_msg(extra.receiver, extra.text, ok_cb, false)
end
local function send_pokemon(query, receiver)
local url = "http://pokeapi.co/api/v1/pokemon/" .. query .. "/"
local b,c = http.request(url)
local pokemon = json:decode(b)
if pokemon == nil then
return 'No pokémon found.'
end
-- api returns height and weight x10
local height = tonumber(pokemon.height)/10
local weight = tonumber(pokemon.weight)/10
local text = 'Pokédex ID: ' .. pokemon.pkdx_id
..'\nName: ' .. pokemon.name
..'\nWeight: ' .. weight.." kg"
..'\nHeight: ' .. height.." m"
..'\nSpeed: ' .. pokemon.speed
local image = nil
if images_enabled and pokemon.sprites and pokemon.sprites[1] then
local sprite = pokemon.sprites[1].resource_uri
image = get_sprite(sprite)
end
if image then
image = "http://pokeapi.co"..image
local extra = {
receiver = receiver,
text = text
}
send_photo_from_url(receiver, image, callback, extra)
return text
else
return text
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local query = URL.escape(string.lower(matches[1]))
return send_pokemon(query, receiver)
end
return {
description = "Pokedex searcher for Telegram",
usage = "!pokedex [Name/ID]: Search the pokédex for Name/ID and get info of the pokémon!",
patterns = {
"^!pokedex (.*)$",
"^!pokemon (.+)$"
},
run = run
}
end
| gpl-2.0 |
BlubBlab/rom-bot | classes/inventoryitem.lua | 1 | 3230 | include("item.lua");
CInventoryItem = class(CItem,
function( self, slotnumber )
self.Location = "inventory"
self.Available = false; -- If slot is in unrented bag then = false
self.SlotNumber = slotnumber
self.BagId = 0
if self.SlotNumber ~= 0 and self.SlotNumber ~= nil then
self:update()
end
end
);
function CInventoryItem:update()
local oldBagId = self.BagId;
if self.SlotNumber > 60 then -- Is Bag Item
self.BagId = memoryReadUByte(getProc(), addresses.inventoryBagIds + self.SlotNumber - 1) + 1
else
self.BagId = self.SlotNumber
end
if self.BagId ~= oldBagId then -- need new address
self.Address = addresses.staticInventory + ( ( self.BagId - 61 ) * 68 );
end
-- Check if not rented
if self.BagId > 120 then
self.Available = memoryReadUInt(getProc(), addresses.rentBagBase + math.floor((self.BagId - 121)/30) * 4) ~= 0xFFFFFFFF
else
self.Available = true
end
-- Don't waste time updating if not available.
if not self.Available then return end
CItem.update(self)
if( settings.profile.options.DEBUG_INV ) then
if ( self.Empty ) then
printf( "BagID: %d is <EMPTY>.\n", self.BagId );
else
local _color = cli.white;
printf( "BagID: %d\tcontains: %d\t (%d) ", self.BagId, self.ItemCount, self.Id );
if ( self.Quality == 1 ) then
_color = cli.lightgreen;
end;
if ( self.Quality == 2 ) then
_color = cli.blue;
end;
if ( self.Quality == 3 ) then
_color = cli.purple;
end;
if ( self.Quality == 4 ) then
_color = cli.yellow;
end;
if ( self.Quality == 5 ) then
_color = cli.forestgreen;
end;
cprintf( _color, "[%s]\n", self.Name );
end;
end;
end
function CInventoryItem:use()
local canUse = true;
local reason = "";
self:update();
if self.Available == false or self.Empty then
return
end
-- If the item can't be used now we should be able to set a timer or something like that to recall this function and check again...
if not self.InUse then
local cd, success = self:getRemainingCooldown()
if success == true and cd ~= 0 then -- Item is on CoolDown we can't use it
--if ( self.CoolDownTime > 0 and self.LastTimeUsed ~= 0 and
--( deltaTime( getTime(), self.LastTimeUsed ) / 1000 ) < self.CoolDownTime ) then -- Item is on CoolDown we can't use it
canUse = false;
reason = "Cooldown";
end;
else -- Item is in use, locked, we can't use it
reason = "In use";
canUse = false;
end;
if ( canUse ) then
RoMCode("UseBagItem("..self.BagId..")");
self.LastTimeUsed = getTime();
yrest( 500 ); -- give time for server to respond with new item count
else
cprintf( cli.yellow, "DEBUG - Cannot use Item %s\t BagId: #%s ItemCount: %s\treason: %s\n", self.Name, self.BagId, self.ItemCount, reason );
logMessage( sprintf( "DEBUG - Cannot use Item %s\t BagId: #%s ItemCount: %s\treason: %s\n", self.Name, self.BagId, self.ItemCount, reason ) );
end;
self:update();
if ( settings.profile.options.DEBUG_INV ) then
cprintf( cli.lightblue, "DEBUG - Use Item BagId: #%s ItemCount: %s\n", self.BagId, self.ItemCount ); -- Open/eqipt item:
end;
return self.ItemCount;
end
| mit |
VurtualRuler98/kswep2 | lua/entities/sent_kgrent_law.lua | 1 | 1682 | ENT.Type = "Anim"
ENT.Base = "sent_kgren_base"
ENT.PrintName = "Grenade"
ENT.Author = "VurtualRuler98"
ENT.Contact = "steam"
ENT.Purpose = "Getting more ammo!"
ENT.Instructions = "Spawn. Use. Reload."
ENT.Category = "Vurtual's base"
ENT.DetFragMagnitude="150"
ENT.DetFragRadius="768"
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.DetonateSound="baseexplosioneffect.sound"
ENT.DeconstraintRadius=64
if (CLIENT) then
function ENT:Draw()
--AddWorldTip( self.Entity:EntIndex(), "ammo", 0.5, self.Entity:GetPos(),self.Entity)
self.Entity:DrawModel()
end
end
if (SERVER) then
AddCSLuaFile()
function ENT:SpawnFunction(ply, tr)
if (!tr.HitWorld) then return end
local ent = ents.Create("sent_kgrent_law")
ent:SetPos(tr.HitPos + Vector(0, 0, 15))
ent:Spawn()
return ent
end
function ENT:Initialize()
self.Entity:SetModel("models/weapons/w_missile_closed.mdl")
self.Entity:PhysicsInit( SOLID_VPHYSICS)
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
self.Entity:SetUseType(SIMPLE_USE)
self.Entity:SetCollisionGroup(COLLISION_GROUP_PROJECTILE)
local phys = self.Entity:GetPhysicsObject()
if (phys:IsValid()) then
phys:SetMass(10)
phys:EnableGravity(false)
phys:Wake()
end
self:CreateFear()
end
function ENT:PhysicsCollide(data,phys)
self:SetNWFloat("Fuze",1)
end
end
function ENT:Think()
if (self:GetNWFloat("Fuze")==1 and not self.Detonated) then
self.Detonated=true
self:Detonate()
end
end
function ENT:Detonate()
if (not IsFirstTimePredicted()) then return end
self:AdvanceFear()
self:EmitGunSound(self.DetonateSound)
self:EffectRocketBoom()
self:DetConstraints()
self:DetBoom()
self:Remove()
end
| apache-2.0 |
emadni/telelord-bot | plugins/anti_spam.lua | 102 | 3744 |
--An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
local data = load_data(_config.moderation.data)
-- 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
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is one or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
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
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- 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
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
local chat = msg.to.id
local user = msg.from.id
-- Return end if user was kicked before
if kicktable[user] == true then
return
end
kick_user(user, chat)
local name = user_print_name(msg.from)
--save it to log file
savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ")
-- 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)
local username = " "
if msg.from.username ~= nil then
username = msg.from.username
end
local name = user_print_name(msg.from)
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)")
local log_group = 1 --set log group caht id
--send it to log group
send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)")
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
stephank/luci | contrib/luadoc/lua/luadoc/lp.lua | 175 | 4389 | ----------------------------------------------------------------------------
-- Lua Pages Template Preprocessor.
--
-- @release $Id: lp.lua,v 1.7 2007/04/18 14:28:39 tomas Exp $
----------------------------------------------------------------------------
local assert, error, getfenv, loadstring, setfenv = assert, error, getfenv, loadstring, setfenv
local find, format, gsub, strsub = string.find, string.format, string.gsub, string.sub
local concat, tinsert = table.concat, table.insert
local open = io.open
module (...)
----------------------------------------------------------------------------
-- function to do output
local outfunc = "io.write"
-- accepts the old expression field: `$| <Lua expression> |$'
local compatmode = true
--
-- Builds a piece of Lua code which outputs the (part of the) given string.
-- @param s String.
-- @param i Number with the initial position in the string.
-- @param f Number with the final position in the string (default == -1).
-- @return String with the correspondent Lua code which outputs the part of the string.
--
local function out (s, i, f)
s = strsub(s, i, f or -1)
if s == "" then return s end
-- we could use `%q' here, but this way we have better control
s = gsub(s, "([\\\n\'])", "\\%1")
-- substitute '\r' by '\'+'r' and let `loadstring' reconstruct it
s = gsub(s, "\r", "\\r")
return format(" %s('%s'); ", outfunc, s)
end
----------------------------------------------------------------------------
-- Translate the template to Lua code.
-- @param s String to translate.
-- @return String with translated code.
----------------------------------------------------------------------------
function translate (s)
if compatmode then
s = gsub(s, "$|(.-)|%$", "<?lua = %1 ?>")
s = gsub(s, "<!%-%-$$(.-)$$%-%->", "<?lua %1 ?>")
end
s = gsub(s, "<%%(.-)%%>", "<?lua %1 ?>")
local res = {}
local start = 1 -- start of untranslated part in `s'
while true do
local ip, fp, target, exp, code = find(s, "<%?(%w*)[ \t]*(=?)(.-)%?>", start)
if not ip then break end
tinsert(res, out(s, start, ip-1))
if target ~= "" and target ~= "lua" then
-- not for Lua; pass whole instruction to the output
tinsert(res, out(s, ip, fp))
else
if exp == "=" then -- expression?
tinsert(res, format(" %s(%s);", outfunc, code))
else -- command
tinsert(res, format(" %s ", code))
end
end
start = fp + 1
end
tinsert(res, out(s, start))
return concat(res)
end
----------------------------------------------------------------------------
-- Defines the name of the output function.
-- @param f String with the name of the function which produces output.
function setoutfunc (f)
outfunc = f
end
----------------------------------------------------------------------------
-- Turns on or off the compatibility with old CGILua 3.X behavior.
-- @param c Boolean indicating if the compatibility mode should be used.
function setcompatmode (c)
compatmode = c
end
----------------------------------------------------------------------------
-- Internal compilation cache.
local cache = {}
----------------------------------------------------------------------------
-- Translates a template into a Lua function.
-- Does NOT execute the resulting function.
-- Uses a cache of templates.
-- @param string String with the template to be translated.
-- @param chunkname String with the name of the chunk, for debugging purposes.
-- @return Function with the resulting translation.
function compile (string, chunkname)
local f, err = cache[string]
if f then return f end
f, err = loadstring (translate (string), chunkname)
if not f then error (err, 3) end
cache[string] = f
return f
end
----------------------------------------------------------------------------
-- Translates and executes a template in a given file.
-- The translation creates a Lua function which will be executed in an
-- optionally given environment.
-- @param filename String with the name of the file containing the template.
-- @param env Table with the environment to run the resulting function.
function include (filename, env)
-- read the whole contents of the file
local fh = assert (open (filename))
local src = fh:read("*a")
fh:close()
-- translates the file into a function
local prog = compile (src, '@'..filename)
local _env
if env then
_env = getfenv (prog)
setfenv (prog, env)
end
prog ()
end
| apache-2.0 |
dmccuskey/dmc-wamp | dmc_corona/lib/dmc_lua/lua_error.lua | 46 | 3628 | --====================================================================--
-- lua_error.lua
--
-- Documentation:
-- * http://github.com/dmccuskey/lua-error
--====================================================================--
--[[
The MIT License (MIT)
Copyright (C) 2014-2015 David McCuskey. All Rights Reserved.
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.
--]]
--====================================================================--
--== DMC Lua Library : Lua Error
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.3.0"
--====================================================================--
--== Imports
local Class = require 'lua_class'
-- Check imports
-- TODO: work on this
assert( Class, "lua_error: requires lua_class" )
if checkModule then checkModule( Class, '1.1.2' ) end
--====================================================================--
--== Setup, Constants
-- none
--====================================================================--
--== Support Functions
-- based on https://gist.github.com/cwarden/1207556
local function try( funcs )
local try_f, catch_f, finally_f = funcs[1], funcs[2], funcs[3]
assert( try_f, "lua-error: missing function for try()" )
--==--
local status, result = pcall(try_f)
if not status and catch_f then
catch_f(result)
end
if finally_f then finally_f() end
return result
end
local function catch(f)
return f[1]
end
local function finally(f)
return f[1]
end
--====================================================================--
--== Error Base Class
--====================================================================--
local Error = newClass( nil, { name="Error Instance" } )
--== Class Constants ==--
Error.__version = VERSION
Error.DEFAULT_PREFIX = "ERROR: "
Error.DEFAULT_MESSAGE = "There was an error"
function Error:__new__( message, params )
message = message or self.DEFAULT_MESSAGE
params = params or {}
params.prefix = params.prefix or self.DEFAULT_PREFIX
--==--
-- guard subclasses
if self.is_class then return end
-- save args
self.prefix = params.prefix
self.message = message
self.traceback = debug.traceback()
end
-- must return a string
--
function Error:__tostring__( id )
return table.concat( { self.prefix, self.message, "\n", self.traceback } )
end
--====================================================================--
--== Error API Setup
--====================================================================--
-- globals
_G.try = try
_G.catch = catch
_G.finally = finally
return Error
| mit |
dxmgame/dxm-cocos-demo | src/lua-fantasy-warrior-3d/Resources/src/cocos/cocos2d/extern.lua | 39 | 2506 |
function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
--Create an class.
function class(classname, super)
local superType = type(super)
local cls
if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end
if superType == "function" or (super and super.__ctype == 1) then
-- inherited from native C++ Object
cls = {}
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.__create = super.__create
cls.super = super
else
cls.__create = super
end
cls.ctor = function() end
cls.__cname = classname
cls.__ctype = 1
function cls.new(...)
local instance = cls.__create(...)
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance.class = cls
instance:ctor(...)
return instance
end
else
-- inherited from Lua Object
if super then
cls = clone(super)
cls.super = super
else
cls = {ctor = function() end}
end
cls.__cname = classname
cls.__ctype = 2 -- lua
cls.__index = cls
function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
end
return cls
end
function schedule(node, callback, delay)
local delay = cc.DelayTime:create(delay)
local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback))
local action = cc.RepeatForever:create(sequence)
node:runAction(action)
return action
end
function performWithDelay(node, callback, delay)
local delay = cc.DelayTime:create(delay)
local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback))
node:runAction(sequence)
return sequence
end
| mit |
UnluckyNinja/PathOfBuilding | Classes/ItemDBControl.lua | 1 | 7831 | -- Path of Building
--
-- Class: Item DB
-- Item DB control.
--
local launch, main = ...
local pairs = pairs
local ipairs = ipairs
local t_insert = table.insert
local m_max = math.max
local ItemDBClass = common.NewClass("ItemDB", "ListControl", function(self, anchor, x, y, width, height, itemsTab, db)
self.ListControl(anchor, x, y, width, height, 16, false)
self.itemsTab = itemsTab
self.db = db
self.defaultText = "^7No items found that match those filters."
self.dragTargetList = { }
self.sortControl = {
NAME = { key = "name", order = 2, dir = "ASCEND", func = function(a,b) return a:gsub("^The ","") < b:gsub("^The ","") end },
--DEEPS = { key = "CombinedDPS", order = 1, dir = "DESCEND" },
}
local leagueFlag = { }
local typeFlag = { }
for _, item in pairs(db.list) do
if item.league then
for leagueName in item.league:gmatch(" ?([%w ]+),?") do
leagueFlag[leagueName] = true
end
end
typeFlag[item.type] = true
end
self.leagueList = { }
for leagueName in pairs(leagueFlag) do
t_insert(self.leagueList, leagueName)
end
table.sort(self.leagueList)
t_insert(self.leagueList, 1, "Any league")
t_insert(self.leagueList, 2, "No league")
self.typeList = { }
for type in pairs(typeFlag) do
t_insert(self.typeList, type)
end
table.sort(self.typeList)
t_insert(self.typeList, 1, "Any type")
t_insert(self.typeList, 2, "Armour")
t_insert(self.typeList, 3, "Jewellery")
t_insert(self.typeList, 4, "One Handed Melee")
t_insert(self.typeList, 5, "Two Handed Melee")
self.slotList = { "Any slot", "Weapon 1", "Weapon 2", "Helmet", "Body Armour", "Gloves", "Boots", "Amulet", "Ring", "Belt", "Jewel" }
self.controls.slot = common.New("DropDownControl", {"BOTTOMLEFT",self,"TOPLEFT"}, 0, -22, 95, 18, self.slotList, function(index, value)
self:BuildList()
end)
self.controls.type = common.New("DropDownControl", {"LEFT",self.controls.slot,"RIGHT"}, 2, 0, 135, 18, self.typeList, function(index, value)
self:BuildList()
end)
self.controls.league = common.New("DropDownControl", {"LEFT",self.controls.type,"RIGHT"}, 2, 0, 126, 18, self.leagueList, function(index, value)
self:BuildList()
end)
self.controls.league.shown = function()
return #self.leagueList > 2
end
self.controls.search = common.New("EditControl", {"BOTTOMLEFT",self,"TOPLEFT"}, 0, -2, 258, 18, "", "Search", "%c", 100, function()
self:BuildList()
end)
self.controls.searchMode = common.New("DropDownControl", {"LEFT",self.controls.search,"RIGHT"}, 2, 0, 100, 18, { "Anywhere", "Names", "Modifiers" }, function(index, value)
self:BuildList()
end)
self:BuildSortOrder()
self:BuildList()
end)
function ItemDBClass:DoesItemMatchFilters(item)
if self.controls.slot.selIndex > 1 then
local primarySlot = itemLib.getPrimarySlotForItem(item)
if primarySlot ~= self.slotList[self.controls.slot.selIndex] and primarySlot:gsub(" %d","") ~= self.slotList[self.controls.slot.selIndex] then
return false
end
end
local typeSel = self.controls.type.selIndex
if typeSel > 1 then
if typeSel == 2 then
if not item.base.armour then
return false
end
elseif typeSel == 3 then
if not (item.type == "Amulet" or item.type == "Ring" or item.type == "Belt") then
return false
end
elseif typeSel == 4 or typeSel == 5 then
local weaponInfo = self.itemsTab.build.data.weaponTypeInfo[item.type]
if not (weaponInfo and weaponInfo.melee and ((typeSel == 4 and weaponInfo.oneHand) or (typeSel == 5 and not weaponInfo.oneHand))) then
return false
end
elseif item.type ~= self.typeList[typeSel] then
return false
end
end
if self.controls.league.selIndex > 1 then
if (self.controls.league.selIndex == 2 and item.league) or (self.controls.league.selIndex > 2 and (not item.league or not item.league:match(self.leagueList[self.controls.league.selIndex]))) then
return false
end
end
local searchStr = self.controls.search.buf:lower()
if searchStr:match("%S") then
local found = false
local mode = self.controls.searchMode.selIndex
if mode == 1 or mode == 2 then
if item.name:lower():find(searchStr, 1, true) then
found = true
end
end
if mode == 1 or mode == 3 then
for _, line in pairs(item.modLines) do
if line.line:lower():find(searchStr, 1, true) then
found = true
break
end
end
if not found then
searchStr = searchStr:gsub(" ","")
for i, mod in ipairs(item.baseModList) do
if mod.name:lower():find(searchStr, 1, true) then
found = true
break
end
end
end
end
if not found then
return false
end
end
return true
end
function ItemDBClass:BuildSortOrder()
self.sortOrder = wipeTable(self.sortOrder)
for field, data in pairs(self.sortControl) do
t_insert(self.sortOrder, data)
end
table.sort(self.sortOrder, function(a, b)
return a.order < b.order
end)
end
function ItemDBClass:BuildList()
wipeTable(self.list)
for id, item in pairs(self.db.list) do
if self:DoesItemMatchFilters(item) then
t_insert(self.list, item)
end
end
--[[if self.itemsTab.build.calcsTab then
local calcFunc, calcBase = self.itemsTab.build.calcsTab:GetMiscCalculator(self.build)
local baseDPS = calcBase.Minion and calcBase.Minion.CombinedDPS or calcBase.CombinedDPS
for _, item in ipairs(self.list) do
item.CombinedDPS = 0
for slotName, slot in pairs(self.itemsTab.slots) do
if self.itemsTab:IsItemValidForSlot(item, slotName) and not slot.inactive and (not slot.weaponSet or slot.weaponSet == (self.itemsTab.activeItemSet.useSecondWeaponSet and 2 or 1)) then
local output = calcFunc({ repSlotName = slotName, repItem = item })
item.CombinedDPS = m_max(item.CombinedDPS, output.Minion and output.Minion.CombinedDPS or output.CombinedDPS)
end
end
end
end]]
table.sort(self.list, function(a, b)
for _, data in ipairs(self.sortOrder) do
local aVal = a[data.key]
local bVal = b[data.key]
if aVal ~= bVal then
if data.dir == "DESCEND" then
if data.func then
return data.func(bVal, aVal)
else
return bVal < aVal
end
else
if data.func then
return data.func(aVal, bVal)
else
return aVal < bVal
end
end
end
end
end)
end
function ItemDBClass:GetRowValue(column, index, item)
if column == 1 then
return colorCodes[item.rarity] .. item.name
end
end
function ItemDBClass:AddValueTooltip(tooltip, index, item)
if main.popups[1] then
tooltip:Clear()
return
end
if tooltip:CheckForUpdate(item, IsKeyDown("SHIFT"), launch.devModeAlt, self.itemsTab.build.outputRevision) then
self.itemsTab:AddItemTooltip(tooltip, item, nil, true)
end
end
function ItemDBClass:GetDragValue(index, item)
return "Item", item
end
function ItemDBClass:OnSelClick(index, item, doubleClick)
if IsKeyDown("CTRL") then
-- Add item
local newItem = itemLib.makeItemFromRaw(self.itemsTab.build.targetVersion, item.raw)
itemLib.normaliseQuality(newItem)
self.itemsTab:AddItem(newItem, true)
-- Equip item if able
local slotName = itemLib.getPrimarySlotForItem(newItem)
if slotName and self.itemsTab.slots[slotName] then
if self.itemsTab.slots[slotName].weaponSet == 1 and self.itemsTab.activeItemSet.useSecondWeaponSet then
-- Redirect to second weapon set
slotName = slotName .. " Swap"
end
if IsKeyDown("SHIFT") then
-- Redirect to second slot if possible
local altSlot = slotName:gsub("1","2")
if self.itemsTab:IsItemValidForSlot(newItem, altSlot) then
slotName = altSlot
end
end
self.itemsTab.slots[slotName]:SetSelItemId(newItem.id)
end
self.itemsTab:PopulateSlots()
self.itemsTab:AddUndoState()
self.itemsTab.build.buildFlag = true
elseif doubleClick then
self.itemsTab:CreateDisplayItemFromRaw(item.raw, true)
end
end
function ItemDBClass:OnSelCopy(index, item)
Copy(item.raw:gsub("\n","\r\n"))
end | mit |
mymedia2/it_cat_butler | plugins/configure.lua | 8 | 3170 | local config = require 'config'
local u = require 'utilities'
local api = require 'methods'
local plugin = {}
local function cache_chat_title(chat_id, title)
print('caching title...')
local key = 'chat:'..chat_id..':title'
db:set(key, title)
db:expire(key, config.bot_settings.cache_time.chat_titles)
return title
end
local function get_chat_title(chat_id)
local cached_title = db:get('chat:'..chat_id..':title')
if not cached_title then
local chat_object = api.getChat(chat_id)
if chat_object then
return cache_chat_title(chat_id, chat_object.result.title)
end
else
return cached_title
end
end
local function do_keyboard_config(chat_id, user_id, is_admin)
local keyboard = {
inline_keyboard = {
{{text = _("🛠 Menu"), callback_data = 'config:menu:'..chat_id}},
{{text = _("⚡️ Antiflood"), callback_data = 'config:antiflood:'..chat_id}},
{{text = _("🌈 Media"), callback_data = 'config:media:'..chat_id}},
{{text = _("🚫 Antispam"), callback_data = 'config:antispam:'..chat_id}},
{{text = _("📥 Log channel"), callback_data = 'config:logchannel:'..chat_id}}
}
}
local show_mod_button = db:hget('chat:'..chat_id..':modsettings', 'promdem') or config.chat_settings['modsettings']['promdem']
if u.is_owner(chat_id, user_id) or (show_mod_button == 'yes' and is_admin) then
table.insert(keyboard.inline_keyboard, {{text = _("👔 Moderators"), callback_data = 'config:mods:'..chat_id}})
end
return keyboard
end
function plugin.onTextMessage(msg, blocks)
if msg.chat.type ~= 'private' then
if u.is_allowed('config', msg.chat.id, msg.from) then
local chat_id = msg.chat.id
local keyboard = do_keyboard_config(chat_id, msg.from.id)
if not db:get('chat:'..chat_id..':title') then cache_chat_title(chat_id, msg.chat.title) end
local res = api.sendMessage(msg.from.id, _("<b>%s</b>\n<i>Change the settings of your group</i>"):format(msg.chat.title:escape_html()), 'html', keyboard)
if not u.is_silentmode_on(msg.chat.id) then --send the responde in the group only if the silent mode is off
if res then
api.sendMessage(msg.chat.id, _("_I've sent you the keyboard via private message_"), true)
else
u.sendStartMe(msg)
end
end
end
end
end
function plugin.onCallbackQuery(msg, blocks)
local chat_id = msg.target_id
local keyboard = do_keyboard_config(chat_id, msg.from.id, msg.from.admin)
local text = _("<i>Change the settings of your group</i>")
local chat_title = get_chat_title(chat_id)
if chat_title then
text = ("<b>%s</b>\n"):format(chat_title:escape_html())..text
end
api.editMessageText(msg.chat.id, msg.message_id, text, 'html', keyboard)
end
plugin.triggers = {
onTextMessage = {
config.cmd..'config$',
config.cmd..'settings$',
},
onCallbackQuery = {
'^###cb:config:back:'
}
}
return plugin | gpl-2.0 |
soheil22222222/ub | plugins/inSuper.lua | 1 | 75851 | --Begin supergrpup.lua
--Check members #Add supergroup
local function check_member_super(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
if success == 0 then
send_large_msg(receiver, "Promote me to admin first!")
end
for k,v in pairs(result) do
local member_id = v.peer_id
if member_id ~= our_id then
-- SuperGroup configuration
data[tostring(msg.to.id)] = {
group_type = 'SuperGroup',
long_id = msg.to.peer_id,
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.title, '_', ' '),
lock_arabic = 'no',
lock_link = "no",
flood = 'yes',
lock_spam = 'yes',
lock_sticker = 'no',
member = 'no',
public = 'no',
lock_rtl = 'no',
lock_tgservice = 'yes',
lock_contacts = 'no',
strict = 'no'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
local text = '☞گروه باموفقیت ثبت شد☜'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Check Members #rem supergroup
local function check_member_superrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local text = 'گروه از لیست حذف شد🚫'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Function to Add supergroup
local function superadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg})
end
--Function to remove supergroup
local function superrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg})
end
--Get and output admins and bots in supergroup
local function callback(cb_extra, success, result)
local i = 1
local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ")
local member_type = cb_extra.member_type
local text = member_type.." for "..chat_name..":\n"
for k,v in pairsByKeys(result) do
if not v.first_name then
name = " "
else
vname = v.first_name:gsub("", "")
name = vname:gsub("_", " ")
end
text = text.."\n"..i.." - "..name.."["..v.peer_id.."]"
i = i + 1
end
send_large_msg(cb_extra.receiver, text)
end
--Get and output info about supergroup
local function callback_info(cb_extra, success, result)
local title ="اطلاعات سوپر گروه☞["..result.title.."]\n\n"
local admin_num = "تعداد ادمین☞"..result.admins_count.."\n"
local user_num = "تعداد اعضا ☞ "..result.participants_count.."\n"
local kicked_num = "تعداد افراد کیک شده ☞ "..result.kicked_count.."\n"
local channel_id = "ایدی ☞ "..result.peer_id.."\n"
if result.username then
channel_username = "یوزرنیم ☞@"..result.username
else
channel_username = "@Team_focus"
end
local text = title..admin_num..user_num..kicked_num..channel_id..channel_username
send_large_msg(cb_extra.receiver, text)
end
--Get and output members of supergroup
local function callback_who(cb_extra, success, result)
local text = "Members for "..cb_extra.receiver
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
username = " @"..v.username
else
username = ""
end
text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n"
--text = text.."\n"..username
i = i + 1
end
local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false)
post_msg(cb_extra.receiver, text, ok_cb, false)
end
--Get and output list of kicked users for supergroup
local function callback_kicked(cb_extra, success, result)
--vardump(result)
local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n☞ "
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
name = name.." @"..v.username
end
text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n"
i = i + 1
end
local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false)
--send_large_msg(cb_extra.receiver, text)
end
--Begin supergroup locks
local function lock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'ℹLink posting is already locked🔒'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹLink posting has been locked🔒'
end
end
local function unlock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'ℹLink posting is not locked🔐'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹLink posting has been unlocked🔓'
end
end
local function lock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "ℹOwners only"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'ℹSuperGroup spam is already locked🔒'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹSuperGroup spam has been locked🔒'
end
end
local function unlock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'ℹSuperGroup spam is not locked🔐'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹSuperGroup spam has been unlocked🔓'
end
end
local function lock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'ℹSpamming is already locked🔒'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹSpamming has been locked🔒'
end
end
local function unlock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'ℹSpamming is not locked🔐'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹSpamming has been unlocked🔓'
end
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'ℹArabic/Persian is already locked🔒'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹArabic/Persian has been locked🔒'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'ℹArabic/Persian is already unlocked🔓'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹArabic/Persian has been unlocked🔓'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'ℹSuperGroup members are already locked🔒'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ℹSuperGroup members has been locked🔒'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'ℹSuperGroup members are not locked🔐'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹSuperGroup members has been unlocked🔓'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'ℹRTL is already locked🔒'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹRTL has been locked🔒'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'ℹRTL is already unlocked🔓'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹRTL has been unlocked🔓'
end
end
local function lock_group_tgservice(msg, data, target)
if not is_momod(msg) then
return
end
local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice']
if group_tgservice_lock == 'yes' then
return 'ℹTGservice is already locked🔒'
else
data[tostring(target)]['settings']['lock_tgservice'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹTGservice has been locked🔒'
end
end
local function unlock_group_tgservice(msg, data, target)
if not is_momod(msg) then
return
end
local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice']
if group_tgservice_lock == 'no' then
return 'ℹTGService Is Not Locked🔐'
else
data[tostring(target)]['settings']['lock_tgservice'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹTGservice has been unlocked🔓'
end
end
local function lock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'ℹSticker posting is already locked🔒'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹSticker posting has been locked🔒'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'ℹSticker posting is already unlocked🔓'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹSticker posting has been unlocked🔓'
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'ℹContact posting is already locked🔒'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹContact posting has been locked🔒'
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'ℹContact posting is already unlocked🔓'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹContact posting has been unlocked🔓'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'yes' then
return 'ℹSettings are already strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'ℹSettings will be strictly enforced'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'no' then
return 'ℹSettings are not strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'ℹSettings will not be strictly enforced'
end
end
--End supergroup locks
--'Set supergroup rules' function
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'ℹقوانین تنظیم شد'
end
--'Get supergroup rules' function
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'ℹقوانینی وجود ندارد'
end
local rules = data[tostring(msg.to.id)][data_cat]
local group_name = data[tostring(msg.to.id)]['settings']['set_name']
local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ")
return rules
end
--Set supergroup to public or not public function
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "ℹFor moderators only"
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'yes' then
return 'ℹGroup is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ℹSuperGroup is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'no' then
return 'ℹGroup is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
data[tostring(target)]['long_id'] = msg.to.long_id
save_data(_config.moderation.data, data)
return 'ℹSuperGroup is now: not public'
end
end
--Show supergroup settings; function
function show_supergroup_settingsmod(msg, target)
if not is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_tgservice'] then
data[tostring(target)]['settings']['lock_tgservice'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "تنظیمات سوپر گروه:\n\n#Lock Links ☞ "..settings.lock_link.."\n#Lock Flood ☞ "..settings.flood.."\n#Flood sensitivity ☞ "..NUM_MSG_MAX.."\n#Lock Spam☞"..settings.lock_spam.."\n#Lock Arabic/Persian ☞ "..settings.lock_arabic.."\n#Lock Member ☞ "..settings.lock_member.."\n#Lock RTL ☞ "..settings.lock_rtl.."\n#Lock TGservice ☞ "..settings.lock_tgservice.."\n#Lock Sticker ☞"..settings.lock_sticker.."\n#Public ☞ "..settings.public.."\n#Strict Settings ☞ "..settings.strict
return text
end
local function promote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
end
local function demote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..' is not a moderator.')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
end
local function promote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return send_large_msg(receiver, 'سوپر گروه اد نشد')
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..' has been promoted.')
end
local function demote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return send_large_msg(receiver, 'گروه اد نشد😣')
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..' is not a moderator.')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..' has been demoted.')
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'سوپر گروه اد شد'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'ℹ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
-- Start by reply actions
function get_message_callback(extra, success, result)
local get_cmd = extra.get_cmd
local msg = extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
if get_cmd == "id" and not result.action then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]")
id1 = send_large_msg(channel, result.from.peer_id)
elseif get_cmd == 'id' and result.action then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
else
user_id = result.peer_id
end
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]")
id1 = send_large_msg(channel, user_id)
end
elseif get_cmd == "idfrom" then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]")
id2 = send_large_msg(channel, result.fwd_from.peer_id)
elseif get_cmd == 'channel_block' and not result.action then
local member_id = result.from.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
--savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply")
kick_user(member_id, channel_id)
elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then
local user_id = result.action.user.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.")
kick_user(user_id, channel_id)
elseif get_cmd == "del" then
delete_msg(result.id, ok_cb, false)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply")
elseif get_cmd == "setadmin" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." set as an admin"
else
text = "[ "..user_id.." ]set as an admin"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "demoteadmin" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
if is_admin2(result.from.peer_id) then
return send_large_msg(channel_id, "You can't demote global admins!")
end
channel_demote(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." has been demoted from admin"
else
text = "[ "..user_id.." ] has been demoted from admin"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "setowner" then
local group_owner = data[tostring(result.to.peer_id)]['set_owner']
if group_owner then
local channel_id = 'channel#id'..result.to.peer_id
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(channel_id, user, ok_cb, false)
end
local user_id = "user#id"..result.from.peer_id
channel_set_admin(channel_id, user_id, ok_cb, false)
data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply")
if result.from.username then
text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as owner"
else
text = "[ "..result.from.peer_id.." ] added as owner"
end
send_large_msg(channel_id, text)
end
elseif get_cmd == "promote" then
local receiver = result.to.peer_id
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
if result.to.peer_type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply")
promote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_set_mod(channel_id, user, ok_cb, false)
end
elseif get_cmd == "demote" then
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
--local user = "user#id"..result.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..user_id.."] by reply")
demote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_demote(channel_id, user, ok_cb, false)
elseif get_cmd == 'mute_user' then
if result.service then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
end
end
if action == 'chat_add_user_link' then
if result.from then
user_id = result.from.peer_id
end
end
else
user_id = result.from.peer_id
end
local receiver = extra.receiver
local chat_id = msg.to.id
print(user_id)
print(chat_id)
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, "["..user_id.."] removed from the muted user list")
elseif is_admin1(msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to the muted user list")
end
end
end
-- End by reply actions
--By ID actions
local function cb_user_info(extra, success, result)
local receiver = extra.receiver
local user_id = result.peer_id
local get_cmd = extra.get_cmd
local data = load_data(_config.moderation.data)
--[[if get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
else
text = "[ "..result.peer_id.." ] has been set as an admin"
end
send_large_msg(receiver, text)]]
if get_cmd == "demoteadmin" then
if is_admin2(result.peer_id) then
return send_large_msg(receiver, "You can't demote global admins!")
end
local user_id = "user#id"..result.peer_id
channel_demote(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been demoted from admin"
send_large_msg(receiver, text)
else
text = "[ "..result.peer_id.." ] has been demoted from admin"
send_large_msg(receiver, text)
end
elseif get_cmd == "promote" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
promote2(receiver, member_username, user_id)
elseif get_cmd == "demote" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
demote2(receiver, member_username, user_id)
end
end
-- Begin resolve username actions
local function callbackres(extra, success, result)
local member_id = result.peer_id
local member_username = "@"..result.username
local get_cmd = extra.get_cmd
if get_cmd == "res" then
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user..'\n'..name)
return user
elseif get_cmd == "id" then
local user = result.peer_id
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user)
return user
elseif get_cmd == "invite" then
local receiver = extra.channel
local user_id = "user#id"..result.peer_id
channel_invite(receiver, user_id, ok_cb, false)
--elseif get_cmd == "channel_block" then
local user_id = result.peer_id
local channel_id = extra.channelid
local sender = extra.sender
if member_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
kick_user(user_id, channel_id)
elseif get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
channel_set_admin(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been set as an admin"
send_large_msg(channel_id, text)
end
elseif get_cmd == "setowner" then
local receiver = extra.channel
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = extra.from_id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
local user = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(result.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username")
if result.username then
text = member_username.."ℹ [ "..result.peer_id.." ] added as owner"
else
text = "ℹ [ "..result.peer_id.." ] added as owner"
end
send_large_msg(receiver, text)
end
elseif get_cmd == "promote" then
local receiver = extra.channel
local user_id = result.peer_id
--local user = "user#id"..result.peer_id
promote2(receiver, member_username, user_id)
--channel_set_mod(receiver, user, ok_cb, false)
elseif get_cmd == "demote" then
local receiver = extra.channel
local user_id = result.peer_id
local user = "user#id"..result.peer_id
demote2(receiver, member_username, user_id)
elseif get_cmd == "demoteadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
if is_admin2(result.peer_id) then
return send_large_msg(channel_id, "You can't demote global admins!")
end
channel_demote(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been demoted from admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been demoted from admin"
send_large_msg(channel_id, text)
end
local receiver = extra.channel
local user_id = result.peer_id
demote_admin(receiver, member_username, user_id)
elseif get_cmd == 'mute_user' then
local user_id = result.peer_id
local receiver = extra.receiver
local chat_id = string.gsub(receiver, 'channel#id', '')
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] removed from muted user list")
elseif is_owner(extra.msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to muted user list")
end
end
end
--End resolve username actions
--Begin non-channel_invite username actions
local function in_channel_cb(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local msg = cb_extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(cb_extra.msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local member = cb_extra.username
local memberid = cb_extra.user_id
if member then
text = 'ℹNo user @'..member..' in this SuperGroup.'
else
text = 'ℹNo user ['..memberid..'] in this SuperGroup.'
end
if get_cmd == "channel_block" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = v.peer_id
local channel_id = cb_extra.msg.to.id
local sender = cb_extra.msg.from.id
if user_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(user_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(user_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
if v.username then
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]")
else
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]")
end
kick_user(user_id, channel_id)
return
end
end
elseif get_cmd == "setadmin" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = "user#id"..v.peer_id
local channel_id = "channel#id"..cb_extra.msg.to.id
channel_set_admin(channel_id, user_id, ok_cb, false)
if v.username then
text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]")
else
text = "ℹ ["..v.peer_id.."] has been set as an admin"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id)
end
if v.username then
member_username = "@"..v.username
else
member_username = string.gsub(v.print_name, '_', ' ')
end
local receiver = channel_id
local user_id = v.peer_id
promote_admin(receiver, member_username, user_id)
end
send_large_msg(channel_id, text)
return
end
elseif get_cmd == 'setowner' then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..v.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(v.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username")
if result.username then
text = member_username.." ["..v.peer_id.."] added as owner"
else
text = "ℹ ["..v.peer_id.."] added as owner"
end
end
elseif memberid and vusername ~= member and vpeer_id ~= memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
data[tostring(channel)]['set_owner'] = tostring(memberid)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username")
text = "ℹ ["..memberid.."] added as owner"
end
end
end
end
send_large_msg(receiver, text)
end
--End non-channel_invite username actions
--'Set supergroup photo' function
local function set_supergroup_photo(msg, success, result)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return
end
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
channel_set_photo(receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'عکس ذخیره شد', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, '*Failed, please try again!', ok_cb, false)
end
end
--Run function
local function run(msg, matches)
if msg.to.type == 'chat' then
if matches[1] == 'upchat' then
if not is_admin1(msg) then
return
end
local receiver = get_receiver(msg)
chat_upgrade(receiver, ok_cb, false)
end
elseif msg.to.type == 'channel'then
if matches[1] == 'upchat' then
if not is_admin1(msg) then
return
end
return "Already a SuperGroup"
end
end
if msg.to.type == 'channel' then
local support_id = msg.from.id
local receiver = get_receiver(msg)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local data = load_data(_config.moderation.data)
if matches[1] == 'add' and not matches[2] then
if not is_admin1(msg) and not is_support(support_id) then
return
end
if is_super_group(msg) then
return reply_msg(msg.id, '✪سوپر گروه باموفقت ثبت شد✪', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup")
superadd(msg)
set_mutes(msg.to.id)
channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false)
end
if matches[1] == 'rem' and is_admin1(msg) and not matches[2] then
if not is_super_group(msg) then
return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed")
superrem(msg)
rem_mutes(msg.to.id)
end
if not data[tostring(msg.to.id)] then
return
end
if matches[1] == "info" then
if not is_owner(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info")
channel_info(receiver, callback_info, {receiver = receiver, msg = msg})
end
if matches[1] == "admins" then
if not is_owner(msg) and not is_support(msg.from.id) then
return
end
member_type = 'Admins'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list")
admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "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 SuperGroup"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "SuperGroup owner is ℹ ["..group_owner..']'
end
if matches[1] == "modlist" then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
-- channel_get_admins(receiver,callback, {receiver = receiver})
end
if matches[1] == "bots" and is_momod(msg) then
member_type = 'Bots'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list")
channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "who" and not matches[2] and is_momod(msg) then
local user_id = msg.from.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list")
channel_get_users(receiver, callback_who, {receiver = receiver})
end
if matches[1] == "kicked" and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list")
channel_get_kicked(receiver, callback_kicked, {receiver = receiver})
end
if matches[1] == 'del' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'del',
msg = msg
}
delete_msg(msg.id, ok_cb, false)
get_message(msg.reply_id, get_message_callback, cbreply_extra)
end
end
if matches[1] == 'kick' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'channel_block',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'kick' and string.match(matches[2], '^%d+$') then
local user_id = matches[2]
local channel_id = msg.to.id
if is_momod2(user_id, channel_id) and not is_admin2(user_id) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]")
kick_user(user_id, channel_id)
local get_cmd = 'channel_block'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif msg.text:match("@[%a%d]") then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'channel_block',
sender = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username)
resolve_username(username, callbackres, cbres_extra)
local get_cmd = 'channel_block'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'id' then
if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then
local cbreply_extra = {
get_cmd = 'id',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then
local cbreply_extra = {
get_cmd = 'idfrom',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif msg.text:match("@[%a%d]") then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'id'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username)
resolve_username(username, callbackres, cbres_extra)
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID")
return "☞ #Group ID: "..msg.to.id.."\n☞ #Group Name: "..msg.to.title.."\n☞ #First Name: "..(msg.from.first_name or '').."\n☞ #Last Name: "..(msg.from.last_name or '').."\n☞ #Your ID: "..msg.from.id.."\n☞ #Username: @"..(msg.from.username or '').."\n☞ #Phone Number: +"..(msg.from.phone or '') end
end
if matches[1] == 'kickme' then
if msg.to.type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme")
channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if matches[1] == 'newlink' and is_momod(msg)then
local function callback_link (extra , success, result)
local receiver = get_receiver(msg)
if success == 0 then
send_large_msg(receiver, '*Error \nReason: Not creator \n please use /setlink to set it')
data[tostring(msg.to.id)]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
else
send_large_msg(receiver, "لینک جدید ساخته شد")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_link, false)
end
if matches[1] == 'setlink' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting'
save_data(_config.moderation.data, data)
return 'لطفا لینک جدید را ارسال کنید'
end
if msg.text then
if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = msg.text
save_data(_config.moderation.data, data)
return "عملیات باموفقیت انجام شد"
end
end
if matches[1] == 'link' then
if not is_momod(msg) then
return
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "ℹهشدار شما هنوز لینکی نساختید برای ساخت لینک جدیداز دستور /newlink استفاده کنید وبرای عوض کردن لینک خوداز دستور /setlink استفاده کنید"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "لینک سوپرگروه:\n "..group_link
end
if matches[1] == "invite" and is_sudo(msg) then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = "invite"
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username)
resolve_username(username, callbackres, cbres_extra)
end
if matches[1] == 'res' and is_owner(msg) then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'res'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username)
resolve_username(username, callbackres, cbres_extra)
end
if matches[1] == 'kick' and is_momod(msg) then
local receiver = channel..matches[3]
local user = "user#id"..matches[2]
chaannel_kick(receiver, user, ok_cb, false)
end
if matches[1] == 'setadmin' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'setadmin',
msg = msg
}
setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'setadmin' and string.match(matches[2], '^%d+$') then
--[[] local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'setadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]]
local get_cmd = 'setadmin'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'setadmin' and not string.match(matches[2], '^%d+$') then
--[[local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'setadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'setadmin'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'demoteadmin' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'demoteadmin',
msg = msg
}
demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'demoteadmin' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'demoteadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'demoteadmin' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'demoteadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username)
resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'setowner' and is_owner(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'setowner',
msg = msg
}
setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'setowner' and string.match(matches[2], '^%d+$') then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if group_owner then
local receiver = get_receiver(msg)
local user_id = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user_id, ok_cb, false)
end
local user = "user#id"..matches[2]
channel_set_admin(receiver, user, ok_cb, false)
data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2])
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = "[ "..matches[2].." ] added as owner"
return text
end
local get_cmd = 'setowner'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'setowner' and not string.match(matches[2], '^%d+$') then
local get_cmd = 'setowner'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'promote' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "ℹError \nOnly owner/admin can promote"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'promote',
msg = msg
}
promote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'promote' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'promote' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'promote',
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'mp' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_set_mod(channel, user_id, ok_cb, false)
return "Done"
end
if matches[1] == 'md' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_demote(channel, user_id, ok_cb, false)
return "Done"
end
if matches[1] == 'demote' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "ℹError \nOnly owner/support/admin can promote"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'demote',
msg = msg
}
demote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'demote' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'demote'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == "setname" and is_momod(msg) then
local receiver = get_receiver(msg)
local set_name = string.gsub(matches[2], '_', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2])
rename_channel(receiver, set_name, ok_cb, false)
end
if msg.service and msg.action.type == 'chat_rename' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title)
data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title
save_data(_config.moderation.data, data)
end
if matches[1] == "setabout" and is_momod(msg) then
local receiver = get_receiver(msg)
local about_text = matches[2]
local data_cat = 'description'
local target = msg.to.id
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text)
channel_set_about(receiver, about_text, ok_cb, false)
return "Description has been set.\n\nSelect the chat again to see the changes."
end
if matches[1] == "setusername" and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.")
elseif success == 0 then
send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.")
end
end
local username = string.gsub(matches[2], '@', '')
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
if matches[1] == 'setrules' and is_momod(msg) then
rules = matches[2]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]")
return set_rulesmod(msg, data, target)
end
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo")
load_photo(msg.id, set_supergroup_photo, msg)
return
end
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo")
return 'لطفا عکس جدیدگروه را ارسال کنید'
end
if matches[1] == 'clean' then
if not is_momod(msg) then
return
end
if not is_momod(msg) then
return "Only owner can clean"
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'No moderator(s) in this SuperGroup!'
end
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
return 'Modlist has been cleaned!'
end
if matches[2] == 'rules' then
local data_cat = 'rules'
if data[tostring(msg.to.id)][data_cat] == nil then
return "Rules have not been set"
end
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
return 'Rules have been cleaned'
end
if matches[2] == 'about' then
local receiver = get_receiver(msg)
local about_text = ' '
local data_cat = 'description'
if data[tostring(msg.to.id)][data_cat] == nil then
return 'About is not set'
end
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
channel_set_about(receiver, about_text, ok_cb, false)
return "About has been cleaned"
end
if matches[2] == 'mutelist' then
chat_id = msg.to.id
local hash = 'mute_user:'..chat_id
redis:del(hash)
return "Mutelist Cleaned"
end
if matches[2] == 'username' and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "SuperGroup username cleaned.")
elseif success == 0 then
send_large_msg(receiver, "Failed to clean SuperGroup username.")
end
end
local username = ""
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
end
if matches[1] == 'lock' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'links' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ")
return lock_group_links(msg, data, target)
end
if matches[2] == 'spam' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_flood(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] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'rtl' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names")
return lock_group_rtl(msg, data, target)
end
if matches[2] == 'tgservice' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions")
return lock_group_tgservice(msg, data, target)
end
if matches[2] == 'sticker' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting")
return lock_group_sticker(msg, data, target)
end
if matches[2] == 'contacts' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[2] == 'strict' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
end
if matches[1] == 'unlock' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'links' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting")
return unlock_group_links(msg, data, target)
end
if matches[2] == 'spam' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam")
return unlock_group_spam(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood")
return unlock_group_flood(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] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'rtl' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[2] == 'tgservice' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions")
return unlock_group_tgservice(msg, data, target)
end
if matches[2] == 'sticker' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting")
return unlock_group_sticker(msg, data, target)
end
if matches[2] == 'contacts' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting")
return unlock_group_contacts(msg, data, target)
end
if matches[2] == 'strict' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings")
return disable_strict_rules(msg, data, target)
end
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return
end
if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 50 then
return "Wrong number,range is [2-50]"
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 'Flood has been set to: '..matches[2]
end
if matches[1] == 'public' and is_momod(msg) 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 SuperGroup to: not public")
return unset_public_membermod(msg, data, target)
end
end
if matches[1] == 'mute' and is_owner(msg) then
local chat_id = msg.to.id
if matches[2] == 'audio' then
local msg_type = 'Audio'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'photo' then
local msg_type = 'Photo'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'video' then
local msg_type = 'Video'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'gifs' then
local msg_type = 'Gifs'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'documents' then
local msg_type = 'Documents'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'text' then
local msg_type = 'Text'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "Mute "..msg_type.." is already on"
end
end
if matches[2] == 'all' then
local msg_type = 'All'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return "Mute "..msg_type.." has been enabled"
else
return "Mute "..msg_type.." is already on"
end
end
end
if matches[1] == 'unmute' and is_momod(msg) then
local chat_id = msg.to.id
if matches[2] == 'audio' then
local msg_type = 'Audio'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'photo' then
local msg_type = 'Photo'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'video' then
local msg_type = 'Video'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'gifs' then
local msg_type = 'Gifs'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'documents' then
local msg_type = 'Documents'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'text' then
local msg_type = 'Text'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message")
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute text is already off"
end
end
if matches[2] == 'all' then
local msg_type = 'All'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return "ℹ Mute "..msg_type.." has been disabled"
else
return "ℹ Mute "..msg_type.." is already disabled"
end
end
end
if matches[1] == "muteuser" and is_momod(msg) then
local chat_id = msg.to.id
local hash = "mute_user"..chat_id
local user_id = ""
if type(msg.reply_id) ~= "nil" then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg})
elseif matches[1] == "muteuser" and string.match(matches[2], '^%d+$') then
local user_id = matches[2]
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list")
return "ℹ ["..user_id.."] removed from the muted users list"
elseif is_owner(msg) then
mute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list")
return "ℹ ["..user_id.."] added to the muted user list"
end
elseif matches[1] == "muteuser" and not string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg})
end
end
if matches[1] == "muteslist" and is_momod(msg) then
local chat_id = msg.to.id
if not has_mutes(chat_id) then
set_mutes(chat_id)
return mutes_list(chat_id)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist")
return mutes_list(chat_id)
end
if matches[1] == "mutelist" and is_momod(msg) then
local chat_id = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist")
return muted_user_list(chat_id)
end
if matches[1] == 'settings' and is_momod(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_supergroup_settingsmod(msg, target)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'help' and not is_owner(msg) then
text = "برای گرفتن دستورات سوپر گروه دستور /superhelp را درپیوی @Focus_robot بزنید"
reply_msg(msg.id, text, ok_cb, false)
elseif matches[1] == 'help' and is_owner(msg) then
local name_log = user_print_name(msg.from)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp")
return super_help()
end
if matches[1] == 'peer_id' and is_admin1(msg)then
text = msg.to.peer_id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
if matches[1] == 'msg.to.id' and is_admin1(msg) then
text = msg.to.id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
--Admin Join Service Message
if msg.service then
local action = msg.action.type
if action == 'chat_add_user_link' then
if is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.from.id) and not is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup")
channel_set_mod(receiver, user, ok_cb, false)
end
end
if action == 'chat_add_user' then
if is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_mod(receiver, user, ok_cb, false)
end
end
end
if matches[1] == 'msg.to.peer_id' then
post_large_msg(receiver, msg.to.peer_id)
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^[#!/]([Aa]dd)$",
"^[#!/]([Rr]em)$",
"^[#!/]([Mm]ove) (.*)$",
"^[#!/]([Ii]nfo)$",
"^[#!/]([Aa]dmins)$",
"^[#!/]([Oo]wner)$",
"^[#!/]([Mm]odlist)$",
"^[#!/]([Bb]ots)$",
"^[#!/]([Ww]ho)$",
"^[#!/]([Kk]icked)$",
"^[#!/]([Kk]ick) (.*)",
"^[#!/]([Kk]ick)",
"^[#!/]([Uu]pchat)$",
"^[#!/]([Ii][Dd])$",
"^[#!/]([Ii][Dd]) (.*)$",
"^[#!/]([Kk]ickme)$",
"^[#!/]([Kk]ick) (.*)$",
"^[#!/]([Nn]ewlink)$",
"^[#!/]([Ss]etlink)$",
"^[#!/]([Ll]ink)$",
"^[#!/]([Rr]es) (.*)$",
"^[#!/]([Ss]etadmin) (.*)$",
"^[#!/]([Ss]etadmin)",
"^[#!/]([Dd]emoteadmin) (.*)$",
"^[#!/]([Dd]emoteadmin)",
"^[#!/]([Ss]etowner) (.*)$",
"^[#!/]([Ss]etowner)$",
"^[#!/]([Pp]romote) (.*)$",
"^[#!/]([Pp]romote)",
"^[#!/]([Dd]emote) (.*)$",
"^[#!/]([Dd]emote)",
"^[#!/]([Ss]etname) (.*)$",
"^[#!/]([Ss]etabout) (.*)$",
"^[#!/]([Ss]etrules) (.*)$",
"^[#!/]([Ss]etphoto)$",
"^[#!/]([Ss]etusername) (.*)$",
"^[#!/]([Dd]el)$",
"^[#!/]([Ll]ock) (.*)$",
"^[#!/]([Uu]nlock) (.*)$",
"^[#!/]([Mm]ute) ([^%s]+)$",
"^[#!/]([Uu]nmute) ([^%s]+)$",
"^[#!/]([Mm]uteuser)$",
"^[#!/]([Mm]uteuser) (.*)$",
"^[#!/]([Pp]ublic) (.*)$",
"^[#!/]([Ss]ettings)$",
"^[#!/]([Rr]ules)$",
"^[#!/]([Ss]etflood) (%d+)$",
"^[#!/]([Cc]lean) (.*)$",
"^[#!/]([Hh]elp)$",
"^[#!/]([Mm]uteslist)$",
"^[#!/]([Mm]utelist)$",
"[#!/](mp) (.*)",
"[#!/](md) (.*)",
"([Hh][Tt][Tt][Pp][Ss]://[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/[Jj][Oo][Ii][Nn][Cc][Hh][Aa][Tt]/%S+)",
"msg.to.peer_id",
"%[(document)%]",
"%[(photo)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(contact)%]",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
--End supergrpup.lua
--by @Team_focus
| gpl-2.0 |
moltafet35/ssssis | 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 |
Whit3Tig3R/SpammBot | 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 |
aqasaeed/mamad | 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 |
Perkovec/starwars-names-lua | src/names.lua | 3 | 1034 | return {
"4-LOM",
"Aayla Secura",
"Admiral Thrawn",
"Ahsoka Tano",
"Anakin Solo",
"Asajj Ventress",
"Aurra Sing",
"Senator Bail Organa",
"Barriss Offee",
"Bastila Shan",
"Ben Skywalker",
"Bib Fortuna",
"Biggs Darklighter",
"Boba Fett",
"Bossk",
"Brakiss",
"C-3PO",
"Cad Bane",
"Cade Skywalker",
"Callista Ming",
"Captain Rex",
"Carnor Jax",
"Chewbacca",
"Clone Commander Cody",
"Count Dooku",
"Darth Bane",
"Darth Krayt",
"Darth Vader",
"Han Solo",
"Jabba the Hutt",
"Luke Skywalker",
"Plo Koon",
"Pre Vizsla",
"Prince Xizor",
"Princess leia",
"PROXY",
"Qui-Gon Jinn",
"Quinlan Vos",
"R2-D2",
"Rahm Kota",
"Revan",
"Satele Shan",
"Savage Opress",
"Sebulba",
"Shaak Ti",
"Shmi Skywalker",
"Talon Karrde",
"Ulic Qel-Droma",
"Visas Marr",
"Watto",
"Wedge Antilles",
"Yoda",
"Zam Wessel",
"Zayne Carrick",
"Zuckuss"
}
| mit |
c4augustus/Urho3D | bin/Data/LuaScripts/06_SkeletalAnimation.lua | 17 | 10180 | -- Skeletal animation example.
-- This sample demonstrates:
-- - Populating a 3D scene with skeletally animated AnimatedModel components
-- - Moving the animated models and advancing their animation using a script object
-- - Enabling a cascaded shadow map on a directional light, which allows high-quality shadows
-- over a large area (typically used in outdoor scenes for shadows cast by sunlight)
-- - Displaying renderer debug geometry
require "LuaScripts/Utilities/Sample"
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Hook up to the frame update and render post-update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
-- Also create a DebugRenderer component so that we can draw debug geometry
scene_:CreateComponent("Octree")
scene_:CreateComponent("DebugRenderer")
-- Create scene node & StaticModel component for showing a static plane
local planeNode = scene_:CreateChild("Plane")
planeNode.scale = Vector3(50.0, 1.0, 50.0)
local planeObject = planeNode:CreateComponent("StaticModel")
planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
-- Create a Zone component for ambient lighting & fog control
local zoneNode = scene_:CreateChild("Zone")
local zone = zoneNode:CreateComponent("Zone")
zone.boundingBox = BoundingBox(-1000.0, 1000.0)
zone.ambientColor = Color(0.5, 0.5, 0.5)
zone.fogColor = Color(0.4, 0.5, 0.8)
zone.fogStart = 100.0
zone.fogEnd = 300.0
-- Create a directional light to the world. Enable cascaded shadows on it
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(0.6, -1.0, 0.8)
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
light.castShadows = true
light.color = Color(0.5, 0.5, 0.5)
light.shadowBias = BiasParameters(0.00025, 0.5)
-- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
-- Create animated models
local uint NUM_MODELS = 30
local MODEL_MOVE_SPEED = 2.0
local MODEL_ROTATE_SPEED = 100.0
local bounds = BoundingBox(Vector3(-20.0, 0.0, -20.0), Vector3(20.0, 0.0, 20.0))
for i = 1, NUM_MODELS do
local modelNode = scene_:CreateChild("Jill")
modelNode.position = Vector3(Random(40.0) - 20.0, 0.0, Random(40.0) - 20.0)
modelNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
local modelObject = modelNode:CreateComponent("AnimatedModel")
modelObject.model = cache:GetResource("Model", "Models/Kachujin/Kachujin.mdl")
modelObject.material = cache:GetResource("Material", "Models/Kachujin/Materials/Kachujin.xml")
modelObject.castShadows = true
-- Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
-- animation, The alternative would be to use an AnimationController component which updates the animation automatically,
-- but we need to update the model's position manually in any case
local walkAnimation = cache:GetResource("Animation", "Models/Kachujin/Kachujin_Walk.ani")
local state = modelObject:AddAnimationState(walkAnimation)
-- Enable full blending weight and looping
state.weight = 1.0
state.looped = true
state.time = Random(walkAnimation.length)
-- Create our Mover script object that will move & animate the model during each frame's update.
local object = modelNode:CreateScriptObject("Mover")
object:SetParameters(MODEL_MOVE_SPEED, MODEL_ROTATE_SPEED, bounds)
end
-- Create the camera. Limit far clip distance to match the fog
cameraNode = scene_:CreateChild("Camera")
local camera = cameraNode:CreateComponent("Camera")
camera.farClip = 300.0
-- Set an initial position for the camera scene node above the plane
cameraNode.position = Vector3(0.0, 5.0, 0.0)
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move\n"..
"Space to toggle debug geometry")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- The text has multiple rows. Center them in relation to each other
instructionText.textAlignment = HA_CENTER
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
-- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, sent after Renderer subsystem is
-- done with defining the draw calls for the viewports (but before actually executing them.) We will request debug geometry
-- rendering during that event
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
local mouseMove = input.mouseMove
yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
-- Toggle debug geometry with space
if input:GetKeyPress(KEY_SPACE) then
drawDebug = not drawDebug
end
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
end
function HandlePostRenderUpdate(eventType, eventData)
-- If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
-- bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
-- bones properly
if drawDebug then
renderer:DrawDebugGeometry(false)
end
end
-- Mover script object class
Mover = ScriptObject()
function Mover:Start()
self.moveSpeed = 0.0
self.rotationSpeed = 0.0
self.bounds = BoundingBox()
end
function Mover:SetParameters(moveSpeed, rotationSpeed, bounds)
self.moveSpeed = moveSpeed
self.rotationSpeed = rotationSpeed
self.bounds = bounds
end
function Mover:Update(timeStep)
local node = self.node
node:Translate(Vector3(0.0, 0.0, 1.0) * self.moveSpeed * timeStep)
-- If in risk of going outside the plane, rotate the model right
local pos = node.position
local bounds = self.bounds
if pos.x < bounds.min.x or pos.x > bounds.max.x or pos.z < bounds.min.z or pos.z > bounds.max.z then
node:Yaw(self.rotationSpeed * timeStep)
end
-- Get the model's first (only) animation state and advance its time
local model = node:GetComponent("AnimatedModel", true)
local state = model:GetAnimationState(0)
if state ~= nil then
state:AddTime(timeStep)
end
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>"..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />"..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>"..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">"..
" <element type=\"Text\">"..
" <attribute name=\"Name\" value=\"KeyBinding\" />"..
" <attribute name=\"Text\" value=\"SPACE\" />"..
" </element>"..
" </add>"..
"</patch>"
end
| mit |
Bpalkmim/NatDProver | Test/Logic/NaturalDeductionLogic.lua | 2 | 22919 | -------------------------------------------------------------------------------
-- Natural Deduction Logic Module
--
-- This module defines the logic of proving utilizing Natural Deduction.
--
-- @authors: bpalkmim
--
-------------------------------------------------------------------------------
require "Logic/NatDGraph"
require "Logic/ConstantsForNatD"
require "logging"
require "logging.file"
local logger = logging.file("aux/prover%s.log", "%Y-%m-%d")
logger:setLevel(logging.INFO)
LogicModule = {}
-- Lista dos ramos ativos no momento
openBranchesList = {}
-- O grafo em si (global ao módulo)
local graph = nil
-- Variável para indexação de descartes de hipótese
-- Também utilizado para indexação das →-Intro
local currentStepNumber = 0
-- Contagem das →-Elim
local elimIndex = 0
-- Array com os nós que representam átomos
local atoms = {}
-- Lista das hipóteses a serem descartadas (também chamados de Goals).
-- Uma hipótese é um predicado lógico. Na prática, essa lista contém os
-- nós do grafo da prova.
LogicModule.dischargeable = {}
-- Private functions
-- Remove um ramo aberto da lista de ramos abertos.
-- Uso principal: quando o ramo já foi expandido/descartado.
-- @param natDNode Nó a ser removido.
local function removeOpenBranch(natDNode)
local foundInTable = false
for i, node in ipairs(openBranchesList) do
if LogicModule.nodeEquals(node, natDNode) then
table.remove(openBranchesList, i)
foundInTable = true
end
end
if not foundInTable then
logger:info("WARNING - Attempted to remove a node from openBranchesList which was not in it.")
end
end
-- Adiciona um novo ramo aberto na lista de ramos abertos.
-- @param natDNode Nó a ser adicionado.
local function addNewOpenBranch(natDNode)
openBranchesList[#openBranchesList + 1] = natDNode
end
-- Função que verifica se o goal corrente pode ser alcançado pelo nó (ramo) recebido, diretamente.
-- Caso seja, retorna true, e false caso contrário. Em caso de reotrno positivo também retorna o label
-- da regra a ser utilizada (no caso, →-Intro ou →-Elim).
-- A preferência de retorno é dada à →-Intro, pois há menos possibilidade de aumento do tamanho da
-- demonstração por só abrir um ramo.
local function isGoalReachable(currentGoalNode, currentNode)
-- Verifica se é alcançável via →-Intro
-- currentNode deve ser uma implicação e seu nó à direita deve ser currentGoalNode
if currentNode:getInformation("type") == opImp.graph then
if LogicModule.nodeEquals(currentGoalNode, currentNode:getEdgeOut(lblEdgeDir):getDestino()) then
return true, lblRuleImpIntro
end
end
-- Verifica se é alcançável via →-Elim
-- currentNode deve ser o nó à direita de currentGoalNode
if currentGoalNode:getInformation("type") == opImp.graph then
if LogicModule.nodeEquals(currentNode, currentGoalNode:getEdgeOut(lblEdgeDir):getDestino()) then
return true, lblRuleImpElim
end
end
return false, ""
end
-- Cria um grafo vazio.
-- @return O grafo criado.
local function createGraphEmpty()
local NatDGraph = Graph:new()
NatDNode:resetCounters()
local NodeGG = NatDNode:new(lblNodeGG)
local nodes = {NodeGG}
local edges = {}
NatDGraph:addNodes(nodes)
NatDGraph:addEdges(edges)
NatDGraph:setRoot(NodeGG)
return NatDGraph
end
-- Cria o grafo de uma fórmula de acordo com a entrada do usuário.
-- @param formulasTable Tabela com as fórmulas.
-- @param letters Stores all atoms.
-- @return O grafo e os strings dos átomos.
local function createGraphFormula(formulasTable, letters)
local S1
local S2
local nodes
local edges
local NodeLetter = nil
local FormulaGraph = Graph:new()
if formulasTable.tag == "Atom" then
local prop_letter = formulasTable["1"]
for k,v in pairs(letters) do
if k == prop_letter then
NodeLetter = v
end
end
if not NodeLetter then
NodeLetter = NatDNode:new(prop_letter)
letters[prop_letter] = NodeLetter
end
nodes = {NodeLetter}
edges = {}
NodeLetter:setInformation("nextDED", 1)
FormulaGraph:addNodes(nodes)
FormulaGraph:addEdges(edges)
FormulaGraph:setRoot(NodeLetter)
elseif formulasTable.tag == "imp" then
S1, letters = createGraphFormula(formulasTable["1"],letters)
S2, letters = createGraphFormula(formulasTable["2"],letters)
local NodeImp = NatDNode:new(opImp.graph)
local EdgeEsq = NatDEdge:new(lblEdgeEsq, NodeImp, S1.root)
local EdgeDir = NatDEdge:new(lblEdgeDir, NodeImp, S2.root)
nodes = {NodeImp}
edges = {EdgeEsq, EdgeDir}
NodeImp:setInformation("nextDED", 1)
FormulaGraph:addNodes(S1.nodes)
FormulaGraph:addNodes(S2.nodes)
FormulaGraph:addNodes(nodes)
FormulaGraph:addEdges(S1.edges)
FormulaGraph:addEdges(S2.edges)
FormulaGraph:addEdges(edges)
FormulaGraph:setRoot(NodeImp)
-- TODO criar demais casos que não só implicação
end
return FormulaGraph, letters
end
-- Cria o grafo de acordo com a entrada do usuário.
-- @param formulasTable Tabela com as fórmulas.
-- @param letters Stores all atoms.
-- @return O grafo criado.
local function createGraphNatD(form_table, letters)
local NatDGraph = Graph:new()
local S,L
local NodeGG = NatDNode:new(lblNodeGG)
S,L = createGraphFormula(form_table, letters)
atoms = L
local newEdge = NatDEdge:new(lblRootEdge, NodeGG, S.root)
local nodes = {NodeGG}
NatDGraph:addNodes(nodes)
NatDGraph:addNodes(S.nodes)
local edges = {newEdge}
NatDGraph:addEdges(edges)
NatDGraph:addEdges(S.edges)
currentStepNumber = 0
elimIndex = 0
return NatDGraph
end
-- TODO ⊥ classico, ⊥ intuicionista, ¬ intro e ¬ elim.
-- Aplica a regra de introdução da implicação no nó selecionado, adicionando um elemento à lista
-- de hipóteses para descarte posterior.
-- @param formulaNode Nó da fórmula a ser expandida.
-- @return O grafo atualizado.
local function applyImplyIntroRule(formulaNode)
logger:debug("ImplyIntro: Expanding "..formulaNode:getLabel())
local impLeft = formulaNode:getEdgeOut(lblEdgeEsq):getDestino()
local impRight = formulaNode:getEdgeOut(lblEdgeDir):getDestino()
-- Nós e arestas novos.
local introStepNode = NatDNode:new(lblRuleImpIntro)
local introStepEdge = NatDEdge:new(lblEdgeDeduction..formulaNode:getInformation("nextDED"), formulaNode, introStepNode)
local hypothesisEdge = NatDEdge:new(lblEdgeHypothesis, introStepNode, impLeft)
local predicateEdge = NatDEdge:new(lblEdgePredicate, introStepNode, impRight)
currentStepNumber = currentStepNumber + 1
introStepEdge:setInformation("rule", opImp.tex.." \\mbox{intro}".."_{"..currentStepNumber.."}")
-- Adiciona a hipótese à lista de hipóteses descartáveis
LogicModule.dischargeable[currentStepNumber] = impLeft
local newEdges = {introStepEdge, hypothesisEdge, predicateEdge}
graph:addNode(introStepNode)
graph:addEdges(newEdges)
formulaNode:setInformation("isExpanded", true)
logger:info("applyImplyIntroRule - "..formulaNode:getLabel().." was expanded")
-- Aqui verificamos se o nó presente na parte superior da prova pode ser hipótese a descartar.
introStepNode:setInformation("isClosed", true)
impRight:setInformation("discharged", false)
for _, node in ipairs(LogicModule.dischargeable) do
if LogicModule.nodeEquals(node, impRight) then
introStepNode:setInformation("isClosed", true)
impRight:setInformation("discharged", true)
break
end
end
-- Caso não seja hipótese a descartar, adicionamos o ramo à lista de ramos abertos.
if not impRight:getInformation("discharged") then
addNewOpenBranch(impRight)
end
-- Remove o nó corrente da lista de ramos abertos.
removeOpenBranch(formulaNode)
formulaNode:setInformation("nextDED", formulaNode:getInformation("nextDED") + 1)
return graph, formulaNode:getInformation("nextDED") - 1
end
-- Função que aplica a →-Elim em formulaNode.
-- Ela pode receber também outros nós: hypNode (que representa o predicado sem a implicação a ser eliminada),
-- e implyNode (que representa o predicado cuja implicação será eliminada). Caso sejam recebidos juntos é
-- verificado se são compatíveis.
-- Sempre é verificada a compatibilidade da conclusão de implyNode com formulaNode (caso contrário não faria
-- sentido a →-Elim).
-- Caso seja recebido apenas hypNode, implyNode será gerado ao criar uma implicação hypNode → formulaNode.
-- Caso seja recebido apenas implyNode, hypNode será gerado a partir da premissa da implicação de implyNode.
local function applyImplyElimRule(formulaNode, hypNode, implyNode)
logger:debug("ImplyElim: Expanding "..formulaNode:getLabel())
-- Nós novos
local hypothesisNode, elimStepNode, impNode = nil
local newNodes = {}
-- Arestas novas
local impLeftEdge, impRightEdge, elimStepEdge, predicateHypEdge, predicateImpEdge = nil
local newEdges = {}
-- Ambos os nós recebidos
if hypNode ~= nil and implyNode ~= nil then
-- Nós incompatíveis
if not LogicModule.nodeEquals(implyNode:getEdgesOut(lblEdgeEsq):getDestino(), hypNode) then
logger:info("applyImpElimRule recieved 3 unrelated nodes.")
return graph
-- Nós compatíveis
else
hypothesisNode = hypNode
impNode = implyNode
impLeftEdge = impNode:getEdgeOut(lblEdgeEsq)
impRightEdge = impNode:getEdgeOut(lblEdgeDir)
end
-- Recebeu apenas o nó de hipótese
elseif hypNode ~= nil and implyNode == nil then
hypothesisNode = hypNode
impNode = NatDNode:new(opImp.graph)
impLeftEdge = NatDEdge:new(lblEdgeEsq, impNode, hypothesisNode)
impRightEdge = NatDEdge:new(lblEdgeDir, impNode, formulaNode)
table.insert(newNodes, impNode)
table.insert(newEdges, impLeftEdge)
table.insert(newEdges, impRightEdge)
-- Recebeu apenas o nó de implicação
elseif hypNode == nil and implyNode ~= nil then
impNode = implyNode
impLeftEdge = impNode:getEdgeOut(lblEdgeEsq)
impRightEdge = impNode:getEdgeOut(lblEdgeDir)
hypothesisNode = impLeftEdge:getDestino()
-- Ambos nulos; não recebeu nenhum dos dois.
else
-- TODO ver como tratar esse caso
logger:info("applyImpElimRule recieved 1 node only, when it needs at least 2.")
return graph
end
elimStepNode = NatDNode:new(lblRuleImpElim)
elimStepEdge = NatDEdge:new(lblEdgeDeduction..formulaNode:getInformation("nextDED"), formulaNode, elimStepNode)
predicateHypEdge = NatDEdge:new(lblEdgePredicate.."1", elimStepNode, hypothesisNode)
predicateImpEdge = NatDEdge:new(lblEdgePredicate.."2", elimStepNode, impNode)
elimIndex = elimIndex + 1
elimStepEdge:setInformation("rule", opImp.tex.." \\mbox{elim}".."_{"..elimIndex.."}")
table.insert(newNodes, elimStepNode)
table.insert(newEdges, elimStepEdge)
table.insert(newEdges, predicateHypEdge)
table.insert(newEdges, predicateImpEdge)
graph:addNodes(newNodes)
graph:addEdges(newEdges)
formulaNode:setInformation("isExpanded", true)
logger:info("applyImplyElimRule - "..formulaNode:getLabel().." was expanded")
-- Aqui verificamos se os nós presentes na parte superior da prova podem ser hipóteses a descartar.
elimStepNode:setInformation("isLeftClosed", false)
elimStepNode:setInformation("isRightClosed", false)
hypothesisNode:setInformation("discharged", false)
impNode:setInformation("discharged", false)
for i, node in ipairs(LogicModule.dischargeable) do
if LogicModule.nodeEquals(node, hypothesisNode) then
elimStepNode:setInformation("isLeftClosed", true)
hypothesisNode:setInformation("discharged", true)
elseif LogicModule.nodeEquals(node, impNode) then
elimStepNode:setInformation("isRightClosed", true)
impNode:setInformation("discharged", true)
end
end
-- Caso não seja hipótese a descartar, adicionamos o ramo à lista de ramos abertos.
-- hypothesisNode (pred1)
if not hypothesisNode:getInformation("discharged") then
addNewOpenBranch(hypothesisNode)
end
-- impNode (pred2)
if not impNode:getInformation("discharged") then
addNewOpenBranch(impNode)
end
-- Remove o nó corrente da lista de ramos abertos.
removeOpenBranch(formulaNode)
formulaNode:setInformation("nextDED", formulaNode:getInformation("nextDED") + 1)
return graph, formulaNode:getInformation("nextDED") - 1
end
----------------------------------------------------------------------------------
-- Funções externas ao módulo
----------------------------------------------------------------------------------
-- Expande o grafo via uma regra de →-intro.
-- @param agraph Grafo da prova.
-- @param formulaNode Ramo a ser expandido.
-- @return Um flag e o grafo atualizado.
function LogicModule.expandImplyIntroRule(agraph, formulaNode)
local typeOfNode = formulaNode:getInformation("type")
graph = agraph
if typeOfNode == opImp.graph then
graph = applyImplyIntroRule(formulaNode)
print_all()
else
logger:info("WARNING - ImpIntro used on an non-implication node.")
end
return true, graph
end
-- Expande o grafo via uma regra de →-elim.
-- @param agraph Grafo da prova.
-- @param formulaNode Ramo a ser expandido.
-- @param hypothesisNode Nó de hipótese a partir do qual será realizada a →-elim.
-- @return Um flag e o grafo atualizado.
function LogicModule.expandImplyElimRule(agraph, formulaNode, hypothesisNode)
graph = agraph
graph = applyImplyElimRule(formulaNode, hypothesisNode)
print_all()
return true, graph
end
--- Create a graph from a formula in table form.
--- Returns a graph that represents the given formula.
--- @param form_table - Formula in table form.
function LogicModule.createGraphFromTable(form_table)
local letters = {}
local graph = nil
if form_table =="empty" then
graph = createGraphEmpty()
else
graph = createGraphNatD(form_table, letters)
end
return graph
end
-- Função principal do módulo, que realiza a expansão geral dos nós do grafo.
-- @param agraph Grafo da prova.
-- @param natDNode Nó do ramo a ser expandido inicialmente.
-- @return O grafo atualizado.
function LogicModule.expandAll(agraph, natDNode)
openBranchesList = {}
LogicModule.dischargeable = {}
graph = agraph
local deductionStep = 1
local numBla = 0
-- Começar a prova pelo nó inicial caso não tenha sido dado um nó
local currentNode = natDNode
if currentNode == nil then
currentNode = graph:getNode(lblNodeGG):getEdgeOut(lblRootEdge):getDestino()
end
-- Primeiros passos: realizar repetidamente ImpIntros até não ter mais uma implicação
while currentNode:getInformation("type") == opImp.graph do
graph, deductionStep = applyImplyIntroRule(currentNode)
if #openBranchesList == 0 then
break
else
currentNode = currentNode:getEdgeOut(lblEdgeDeduction..deductionStep):getDestino():getEdgeOut(lblEdgePredicate):getDestino()
end
end
-- Até aqui, temos a certeza de que há apenas um ramo a ser expandido, então guardamos esse nó.
-- subRootNode será um nó fixo, para o qual voltaremos com currentNode caso necessário.
local subRootNode = currentNode
-- Passos seguintes: realizar ImpElims e ImpIntros conforme necessário nos ramos livres.
-- Ramo aberto: sentença lógica ainda não provada.
-- Ramo fechado: hipótese descartada.
-- Goals: serão retirados da lista de dischargeable.
local currentGoalNode = LogicModule.dischargeable[1]
local parentGoalNode = currentGoalNode
local currentGoalIndex = 1
local isReachable = nil
local ruleToApply = ""
while #openBranchesList > 0 do
currentNode = openBranchesList[1]
if currentNode:getInformation("Attempts") == nil then
currentNode:setInformation("Attempts", 0)
end
isReachable, ruleToApply = isGoalReachable(currentGoalNode, currentNode)
if isReachable then
-- Nó que não é de implicação. Não é possível realizar ImpIntro, então deveremos realizar ImpElim.
-- TODO A VER: nesse caso, realizamos ImpElim utilizando a hipótese descartável de menor tamanho
-- para ser o nó maior da →-Elim.
if currentNode:getInformation("type") ~= opImp.graph then
if currentGoalNode:getInformation("type") == opImp.graph then
--print("ping")
--print(currentNode:getLabel())
--print(currentGoalNode:getLabel())
graph, deductionStep = applyImplyElimRule(currentNode, nil, currentGoalNode)
else
graph, deductionStep = applyImplyElimRule(currentNode, currentGoalNode, nil)
end
-- Nó de implicação. Devemos decidir entre ImpElim ou ImpIntro.
else
if ruleToApply == lblRuleImpIntro then
--print("pong")
--print(currentNode:getLabel())
--print(currentGoalNode:getLabel())
graph, deductionStep = applyImplyIntroRule(currentNode)
--[[numBla = numBla + 1
if numBla > 5 then
logger:info("INFO - A prova não pôde ser concluída. Teorema não válido.")
currentNode:setInformation("Invalid", true)
-- Marca os demais nós abertos como inválidos
for i, node in ipairs(openBranchesList) do
node:setInformation("Invalid", true)
end
print(numBla)
-- Reseta os valores de nextDED dos nós para imprimir
for i, node in ipairs(graph:getNodes()) do
node:setInformation("nextDED", 1)
end
return false, graph
end
--]]
-- TODO verificar se nesse caso é sempre esse tratamento
elseif ruleToApply == lblRuleImpElim then
if currentGoalNode:getInformation("type") == opImp.graph then
graph, deductionStep = applyImplyElimRule(currentNode, nil, currentGoalNode)
else
graph, deductionStep = applyImplyElimRule(currentNode, currentGoalNode, nil)
end
else
logger:info("ERRO - ruleToApply em LogicModule.expandAll não apresenta valor válido.")
return false, graph
end
end
currentGoalNode = parentGoalNode
-- Goal atual não alcançável. Passamos para o subgoal (caso não seja possível, vamos para outro goal).
-- Subgoal: o nó à direita da implicação do goal atual.
else
if currentGoalNode:getInformation("type") == opImp.graph then
--print("pang")
--print(currentNode:getLabel())
--print(currentGoalNode:getLabel())
parentGoalNode = currentGoalNode
currentGoalNode = currentGoalNode:getEdgeOut(lblEdgeDir):getDestino()
-- Não sendo uma implicação, partimos para o Goal seguinte. Não havendo um Goal seguinte,
-- voltamos ao inicial.
-- Caso não seja possível continuar aprova após mais de duas passadas para esse currentNode,
-- temor que o teorema não é válido.
-- TODO podemos ter essa certeza?
else
if currentGoalIndex + 1 > #LogicModule.dischargeable then
-- Nesse caso, aplicar a regra de →-Intro.
if currentNode:getInformation("type") == opImp.graph then
graph, deductionStep = applyImplyIntroRule(currentNode)
currentGoalNode = parentGoalNode
-- O número máximo de tentativas é 2^{i}, onde i é o número de fórmulas atômicas.
-- doi do artigo fonte: j.entcs.2015.06.004
elseif currentNode:getInformation("Attempts") > math.pow(2, #atoms) then
logger:info("INFO - A prova não pôde ser concluída. Teorema não válido.")
currentNode:setInformation("Invalid", true)
-- Marca os demais nós abertos como inválidos
for i, node in ipairs(openBranchesList) do
node:setInformation("Invalid", true)
end
-- Reseta os valores de nextDED dos nós para imprimir
for i, node in ipairs(graph:getNodes()) do
node:setInformation("nextDED", 1)
end
return false, graph
-- Voltamos ao primeiro Goal.
else
currentNode:setInformation("Attempts", currentNode:getInformation("Attempts") + 1)
currentGoalNode = LogicModule.dischargeable[1]
parentGoalNode = currentGoalNode
currentGoalIndex = 1
end
-- Goal seguinte.
else
currentGoalNode = LogicModule.dischargeable[currentGoalIndex + 1]
parentGoalNode = currentGoalNode
currentGoalIndex = currentGoalIndex + 1
end
end
end
end
-- Reseta os valores de nextDED dos nós para imprimir
for i, node in ipairs(graph:getNodes()) do
node:setInformation("nextDED", 1)
end
return true, graph
end
function LogicModule.getGraph()
return graph
end
local numRecursions = 0
-- Função auxiliar recursiva para verificar igualdade de dois nós do grafo.
-- Adaptada apenas para implicações e termos atômicos, utilizada principalmente
-- para verificar se uma proposição lógica é uma hipótese a ser descartada.
-- @param node1 Primeiro nó.
-- @param node2 Segundo nó.
-- @return true se são iguais, ou false caso sejam diferentes.
function LogicModule.nodeEquals(node1, node2)
local node1Left, node1Right, node2Left, node2Right = nil
-- Checagem de nós nulos. Aqui não é utilizado assert pois dois nós nulos teoricamente são iguais.
--- Casos base
if node1 == nil then
logger:info("WARNING - function nodeEquals in module NaturalDeductionLogic recieved first parameter nil")
-- Ambos os nós nulos, tecnicamente são iguais (mas é lançado um aviso).
if node2 == nil then
logger:info("WARNING - function nodeEquals in module NaturalDeductionLogic recieved second parameter nil")
return true
-- Primeiro nó nulo e segundo não nulo.
else
return false
end
else
-- Primeiro nó não nulo e segundo nulo.
if node2 == nil then
logger:info("WARNING - function nodeEquals in module NaturalDeductionLogic recieved second parameter nil")
return false
end
end
-- Ambos os nós não nulos
-- Ambos nós atômicos; basta comparar seus labels
if node1:getInformation("type") ~= opImp.graph and node2:getInformation("type") ~= opImp.graph then
return node1:getLabel() == node2:getLabel()
-- Primeiro nó implicação, segundo nó atômico
elseif node1:getInformation("type") == opImp.graph and node2:getInformation("type") ~= opImp.graph then
return false
-- Primeiro nó atômico, segundo nó implicação
elseif node1:getInformation("type") ~= opImp.graph then
return false
-- Ambos nós de implicação.
else
-- São a mesma implicação.
if node1:getLabel() == node2:getLabel() then
return true
end
numRecursions = numRecursions + 1
--print(numRecursions)
-- São implicações diferentes.
-- Passo indutivo
for i, edge in ipairs(node1:getEdgesOut()) do
if edge:getLabel() == lblEdgeEsq then
node1Left = edge:getDestino()
elseif edge:getLabel() == lblEdgeDir then
node1Right = edge:getDestino()
end
end
for i, edge in ipairs(node2:getEdgesOut()) do
if edge:getLabel() == lblEdgeEsq then
node2Left = edge:getDestino()
elseif edge:getLabel() == lblEdgeDir then
node2Right = edge:getDestino()
end
end
--print(node1:getLabel())
--print(node2:getLabel())
return LogicModule.nodeEquals(node1Left, node2Left) and LogicModule.nodeEquals(node1Right, node2Right)
end
end
--[[
function load()
local f = loadfile("commands.lua")
f()
end
function run()
LogicModule.expandAll(graph)
end
function step(pstep)
LogicModule.expandAll(graph, pstep)
end
function print_all()
PrintModule.printProof(graph, "")
os.showProofOnBrowser()
clear()
end
]] | gpl-2.0 |
facebokiii/Uproject | 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 |
stephank/luci | modules/admin-full/luasrc/model/cbi/admin_network/iface_add.lua | 6 | 3337 | --[[
LuCI - Lua Configuration Interface
Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local nw = require "luci.model.network".init()
local fw = require "luci.model.firewall".init()
local utl = require "luci.util"
local uci = require "luci.model.uci".cursor()
m = SimpleForm("network", translate("Create Interface"))
m.redirect = luci.dispatcher.build_url("admin/network/network")
m.reset = false
newnet = m:field(Value, "_netname", translate("Name of the new interface"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet:depends("_attach", "")
newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_")
newnet.datatype = "uciname"
newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface"))
netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces"))
sifname = m:field(Value, "_ifname", translate("Cover the following interface"),
translate("Note: If you choose an interface here which is part of another network, it will be moved into this network."))
sifname.widget = "radio"
sifname.template = "cbi/network_ifacelist"
sifname.nobridges = true
mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces"),
translate("Note: If you choose an interface here which is part of another network, it will be moved into this network."))
mifname.widget = "checkbox"
mifname.template = "cbi/network_ifacelist"
mifname.nobridges = true
local _, p
for _, p in ipairs(nw:get_protocols()) do
if p:is_installed() then
newproto:value(p:proto(), p:get_i18n())
if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end
if not p:is_floating() then
sifname:depends({ _bridge = "", _netproto = p:proto()})
mifname:depends({ _bridge = "1", _netproto = p:proto()})
end
end
end
function newproto.validate(self, value, section)
local name = newnet:formvalue(section)
if not name or #name == 0 then
newnet:add_error(section, translate("No network name specified"))
elseif m:get(name) then
newnet:add_error(section, translate("The given network name is not unique"))
end
local proto = nw:get_protocol(value)
if proto and not proto:is_floating() then
local br = (netbridge:formvalue(section) == "1")
local ifn = br and mifname:formvalue(section) or sifname:formvalue(section)
for ifn in utl.imatch(ifn) do
return value
end
return nil, translate("The selected protocol needs a device assigned")
end
return value
end
function newproto.write(self, section, value)
local name = newnet:formvalue(section)
if name and #name > 0 then
local br = (netbridge:formvalue(section) == "1") and "bridge" or nil
local net = nw:add_network(name, { proto = value, type = br })
if net then
local ifn
for ifn in utl.imatch(
br and mifname:formvalue(section) or sifname:formvalue(section)
) do
net:add_interface(ifn)
end
nw:save("network")
nw:save("wireless")
end
luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name))
end
end
return m
| apache-2.0 |
SatoshiNXSimudrone/sl4a-damon-clone | lua/luasocket/src/url.lua | 148 | 10529 | -----------------------------------------------------------------------------
-- URI parsing, composition and relative URL resolution
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local base = _G
local table = require("table")
module("socket.url")
-----------------------------------------------------------------------------
-- Module version
-----------------------------------------------------------------------------
_VERSION = "URL 1.0.1"
-----------------------------------------------------------------------------
-- Encodes a string into its escaped hexadecimal representation
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
function escape(s)
return string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02x", string.byte(c))
end)
end
-----------------------------------------------------------------------------
-- Protects a path segment, to prevent it from interfering with the
-- url parsing.
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
local function make_set(t)
local s = {}
for i,v in base.ipairs(t) do
s[t[i]] = 1
end
return s
end
-- these are allowed withing a path segment, along with alphanum
-- other characters must be escaped
local segment_set = make_set {
"-", "_", ".", "!", "~", "*", "'", "(",
")", ":", "@", "&", "=", "+", "$", ",",
}
local function protect_segment(s)
return string.gsub(s, "([^A-Za-z0-9_])", function (c)
if segment_set[c] then return c
else return string.format("%%%02x", string.byte(c)) end
end)
end
-----------------------------------------------------------------------------
-- Encodes a string into its escaped hexadecimal representation
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
function unescape(s)
return string.gsub(s, "%%(%x%x)", function(hex)
return string.char(base.tonumber(hex, 16))
end)
end
-----------------------------------------------------------------------------
-- Builds a path from a base path and a relative path
-- Input
-- base_path
-- relative_path
-- Returns
-- corresponding absolute path
-----------------------------------------------------------------------------
local function absolute_path(base_path, relative_path)
if string.sub(relative_path, 1, 1) == "/" then return relative_path end
local path = string.gsub(base_path, "[^/]*$", "")
path = path .. relative_path
path = string.gsub(path, "([^/]*%./)", function (s)
if s ~= "./" then return s else return "" end
end)
path = string.gsub(path, "/%.$", "/")
local reduced
while reduced ~= path do
reduced = path
path = string.gsub(reduced, "([^/]*/%.%./)", function (s)
if s ~= "../../" then return "" else return s end
end)
end
path = string.gsub(reduced, "([^/]*/%.%.)$", function (s)
if s ~= "../.." then return "" else return s end
end)
return path
end
-----------------------------------------------------------------------------
-- Parses a url and returns a table with all its parts according to RFC 2396
-- The following grammar describes the names given to the URL parts
-- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment>
-- <authority> ::= <userinfo>@<host>:<port>
-- <userinfo> ::= <user>[:<password>]
-- <path> :: = {<segment>/}<segment>
-- Input
-- url: uniform resource locator of request
-- default: table with default values for each field
-- Returns
-- table with the following fields, where RFC naming conventions have
-- been preserved:
-- scheme, authority, userinfo, user, password, host, port,
-- path, params, query, fragment
-- Obs:
-- the leading '/' in {/<path>} is considered part of <path>
-----------------------------------------------------------------------------
function parse(url, default)
-- initialize default parameters
local parsed = {}
for i,v in base.pairs(default or parsed) do parsed[i] = v end
-- empty url is parsed to nil
if not url or url == "" then return nil, "invalid url" end
-- remove whitespace
-- url = string.gsub(url, "%s", "")
-- get fragment
url = string.gsub(url, "#(.*)$", function(f)
parsed.fragment = f
return ""
end)
-- get scheme
url = string.gsub(url, "^([%w][%w%+%-%.]*)%:",
function(s) parsed.scheme = s; return "" end)
-- get authority
url = string.gsub(url, "^//([^/]*)", function(n)
parsed.authority = n
return ""
end)
-- get query stringing
url = string.gsub(url, "%?(.*)", function(q)
parsed.query = q
return ""
end)
-- get params
url = string.gsub(url, "%;(.*)", function(p)
parsed.params = p
return ""
end)
-- path is whatever was left
if url ~= "" then parsed.path = url end
local authority = parsed.authority
if not authority then return parsed end
authority = string.gsub(authority,"^([^@]*)@",
function(u) parsed.userinfo = u; return "" end)
authority = string.gsub(authority, ":([^:]*)$",
function(p) parsed.port = p; return "" end)
if authority ~= "" then parsed.host = authority end
local userinfo = parsed.userinfo
if not userinfo then return parsed end
userinfo = string.gsub(userinfo, ":([^:]*)$",
function(p) parsed.password = p; return "" end)
parsed.user = userinfo
return parsed
end
-----------------------------------------------------------------------------
-- Rebuilds a parsed URL from its components.
-- Components are protected if any reserved or unallowed characters are found
-- Input
-- parsed: parsed URL, as returned by parse
-- Returns
-- a stringing with the corresponding URL
-----------------------------------------------------------------------------
function build(parsed)
local ppath = parse_path(parsed.path or "")
local url = build_path(ppath)
if parsed.params then url = url .. ";" .. parsed.params end
if parsed.query then url = url .. "?" .. parsed.query end
local authority = parsed.authority
if parsed.host then
authority = parsed.host
if parsed.port then authority = authority .. ":" .. parsed.port end
local userinfo = parsed.userinfo
if parsed.user then
userinfo = parsed.user
if parsed.password then
userinfo = userinfo .. ":" .. parsed.password
end
end
if userinfo then authority = userinfo .. "@" .. authority end
end
if authority then url = "//" .. authority .. url end
if parsed.scheme then url = parsed.scheme .. ":" .. url end
if parsed.fragment then url = url .. "#" .. parsed.fragment end
-- url = string.gsub(url, "%s", "")
return url
end
-----------------------------------------------------------------------------
-- Builds a absolute URL from a base and a relative URL according to RFC 2396
-- Input
-- base_url
-- relative_url
-- Returns
-- corresponding absolute url
-----------------------------------------------------------------------------
function absolute(base_url, relative_url)
if base.type(base_url) == "table" then
base_parsed = base_url
base_url = build(base_parsed)
else
base_parsed = parse(base_url)
end
local relative_parsed = parse(relative_url)
if not base_parsed then return relative_url
elseif not relative_parsed then return base_url
elseif relative_parsed.scheme then return relative_url
else
relative_parsed.scheme = base_parsed.scheme
if not relative_parsed.authority then
relative_parsed.authority = base_parsed.authority
if not relative_parsed.path then
relative_parsed.path = base_parsed.path
if not relative_parsed.params then
relative_parsed.params = base_parsed.params
if not relative_parsed.query then
relative_parsed.query = base_parsed.query
end
end
else
relative_parsed.path = absolute_path(base_parsed.path or "",
relative_parsed.path)
end
end
return build(relative_parsed)
end
end
-----------------------------------------------------------------------------
-- Breaks a path into its segments, unescaping the segments
-- Input
-- path
-- Returns
-- segment: a table with one entry per segment
-----------------------------------------------------------------------------
function parse_path(path)
local parsed = {}
path = path or ""
--path = string.gsub(path, "%s", "")
string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end)
for i = 1, table.getn(parsed) do
parsed[i] = unescape(parsed[i])
end
if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end
if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end
return parsed
end
-----------------------------------------------------------------------------
-- Builds a path component from its segments, escaping protected characters.
-- Input
-- parsed: path segments
-- unsafe: if true, segments are not protected before path is built
-- Returns
-- path: corresponding path stringing
-----------------------------------------------------------------------------
function build_path(parsed, unsafe)
local path = ""
local n = table.getn(parsed)
if unsafe then
for i = 1, n-1 do
path = path .. parsed[i]
path = path .. "/"
end
if n > 0 then
path = path .. parsed[n]
if parsed.is_directory then path = path .. "/" end
end
else
for i = 1, n-1 do
path = path .. protect_segment(parsed[i])
path = path .. "/"
end
if n > 0 then
path = path .. protect_segment(parsed[n])
if parsed.is_directory then path = path .. "/" end
end
end
if parsed.is_absolute then path = "/" .. path end
return path
end
| apache-2.0 |
MeGa-TeAm/megabot | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
ioiasff/hiu | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
devlaith/DEVLAITH | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
fegimanam/ssd | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
aqasaeed/spartav1 | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
aqasaeed/mamad | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
artynet/luci | modules/luci-base/luasrc/ccache.lua | 81 | 1651 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local io = require "io"
local fs = require "nixio.fs"
local util = require "luci.util"
local nixio = require "nixio"
local debug = require "debug"
local string = require "string"
local package = require "package"
local type, loadfile = type, loadfile
module "luci.ccache"
function cache_ondemand(...)
if debug.getinfo(1, 'S').source ~= "=?" then
cache_enable(...)
end
end
function cache_enable(cachepath, mode)
cachepath = cachepath or "/tmp/luci-modulecache"
mode = mode or "r--r--r--"
local loader = package.loaders[2]
local uid = nixio.getuid()
if not fs.stat(cachepath) then
fs.mkdir(cachepath)
end
local function _encode_filename(name)
local encoded = ""
for i=1, #name do
encoded = encoded .. ("%2X" % string.byte(name, i))
end
return encoded
end
local function _load_sane(file)
local stat = fs.stat(file)
if stat and stat.uid == uid and stat.modestr == mode then
return loadfile(file)
end
end
local function _write_sane(file, func)
if nixio.getuid() == uid then
local fp = io.open(file, "w")
if fp then
fp:write(util.get_bytecode(func))
fp:close()
fs.chmod(file, mode)
end
end
end
package.loaders[2] = function(mod)
local encoded = cachepath .. "/" .. _encode_filename(mod)
local modcons = _load_sane(encoded)
if modcons then
return modcons
end
-- No cachefile
modcons = loader(mod)
if type(modcons) == "function" then
_write_sane(encoded, modcons)
end
return modcons
end
end
| apache-2.0 |
Nostrademous/Dota2-WebAI | abilities/hero/antimage/antimage_blink.lua | 1 | 1496 | local VectorHelper = require(GetScriptDirectory().."/dev/helper/vector_helper")
local Action = require(GetScriptDirectory().."/actions/basic_actions/action_use_ability_on_location")
local AntimageBlink = {}
AntimageBlink.Name = heroData.antimage.SKILL_1
function AntimageBlink:Ability()
return GetBot():GetAbilityByName(self.Name)
end
function AntimageBlink:Desire()
local bot = GetBot()
local ability = self:Ability()
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE
end
local move_loc = bot.mybot.moving_location
if not move_loc then
return BOT_ACTION_DESIRE_NONE
end
local distance = GetUnitToLocationDistance(bot, move_loc)
-- minimum blink distance is 200
if distance < 200 then
return BOT_ACTION_DESIRE_NONE
end
if bot:GetMana() > 120 and (distance > 900) then
return BOT_ACTION_DESIRE_MEDIUM
end
return BOT_ACTION_DESIRE_NONE
end
function AntimageBlink:Call()
local bot = GetBot()
local ability = self:Ability()
local max_blink_range = ability:GetSpecialValueInt("blink_range")
local move_loc = bot.mybot.moving_location
local distance = GetUnitToLocationDistance(bot, move_loc)
if distance > max_blink_range then
move_loc = VectorHelper:VectorTowards(bot:GetLocation(), move_loc, max_blink_range)
end
Action:Call(ability, move_loc, ability:GetCastPoint())
end
return AntimageBlink | mit |
lbchao/SimplifyReader | library_youku/src/main/res/raw/aes.lua | 130 | 3338 |
---------------------- bit utils
bit={data32={}}
for i=1,32 do
bit.data32[i]=2^(32-i)
end
function bit.d2b(arg)
local tr={}
for i=1,32 do
if arg >= bit.data32[i] then
tr[i]=1
arg=arg-bit.data32[i]
else
tr[i]=0
end
end
return tr
end --bit:d2b
function bit.b2d(arg)
local nr=0
for i=1,32 do
if arg[i] ==1 then
nr=nr+2^(32-i)
end
end
return nr
end --bit:b2d
function bit._xor(a,b)
local op1=bit.d2b(a)
local op2=bit.d2b(b)
local r={}
for i=1,32 do
if op1[i]==op2[i] then
r[i]=0
else
r[i]=1
end
end
return bit.b2d(r)
end --bit:xor
function bit._and(a,b)
local op1=bit.d2b(a)
local op2=bit.d2b(b)
local r={}
for i=1,32 do
if op1[i]==1 and op2[i]==1 then
r[i]=1
else
r[i]=0
end
end
return bit.b2d(r)
end --bit:_and
function bit._or(a,b)
local op1=bit.d2b(a)
local op2=bit.d2b(b)
local r={}
for i=1,32 do
if op1[i]==1 or op2[i]==1 then
r[i]=1
else
r[i]=0
end
end
return bit.b2d(r)
end --bit:_or
function bit._not(a)
local op1=bit.d2b(a)
local r={}
for i=1,32 do
if op1[i]==1 then
r[i]=0
else
r[i]=1
end
end
return bit.b2d(r)
end --bit:_not
function bit._rshift(a,n)
local op1=bit.d2b(a)
local r=bit.d2b(0)
if n < 32 and n > 0 then
for i=1,n do
for i=31,1,-1 do
op1[i+1]=op1[i]
end
op1[1]=0
end
r=op1
end
return bit.b2d(r)
end --bit:_rshift
function bit._lshift(a,n)
local op1=bit.d2b(a)
local r=bit.d2b(0)
if n < 32 and n > 0 then
for i=1,n do
for i=1,31 do
op1[i]=op1[i+1]
end
op1[32]=0
end
r=op1
end
return bit.b2d(r)
end --bit:_lshift
function bit.print(ta)
local sr=""
for i=1,32 do
sr=sr..ta[i]
end
print(sr)
end
-------------------------------- core
y_key = {1206625642, 1092691841, 3888211297, 1403752353}
t_key = {768304513, 3648063403, 1200350539, 1135324489}
y_live_key = {2380375339, 3372821835, 757854091, 3417384251}
t_live_key = {1307283402, 3415975219, 130748267, 1094264761}
function getConfused(flag)
local ftr = math.log10(1000);
local ftr2 = math.log10(100);
local key = {};
if flag==0 then
key = y_key;
elseif flag == 1 then
key = t_key;
elseif flag == 2 then
key = y_live_key;
elseif flag == 3 then
key = t_live_key;
end
local a = math.max(key[1], ftr);
local b = math.min(key[2], ftr2);
local c = math.max(key[3], ftr);
local d = math.min(key[4], ftr2);
return a, b, c, d;
end
function doDec(ciphertxt, len, flag)
dc = luajava.newInstance("com.decapi.Decryptions");
local L, l, R, r = getConfused(flag);
ret = dc:AESDec(ciphertxt, len, math.btan2(L, l, R, r));
return ret;
end
function doEnc(plaintxt, flag)
ec = luajava.newInstance("com.decapi.Decryptions");
local L, l, R, r = getConfused(flag);
ret = ec:AESEnc(plaintxt, math.btan2(L, l, R, r));
return ret;
end | apache-2.0 |
yanyongshan/SimplifyReader | library_youku/src/main/res/raw/aes.lua | 130 | 3338 |
---------------------- bit utils
bit={data32={}}
for i=1,32 do
bit.data32[i]=2^(32-i)
end
function bit.d2b(arg)
local tr={}
for i=1,32 do
if arg >= bit.data32[i] then
tr[i]=1
arg=arg-bit.data32[i]
else
tr[i]=0
end
end
return tr
end --bit:d2b
function bit.b2d(arg)
local nr=0
for i=1,32 do
if arg[i] ==1 then
nr=nr+2^(32-i)
end
end
return nr
end --bit:b2d
function bit._xor(a,b)
local op1=bit.d2b(a)
local op2=bit.d2b(b)
local r={}
for i=1,32 do
if op1[i]==op2[i] then
r[i]=0
else
r[i]=1
end
end
return bit.b2d(r)
end --bit:xor
function bit._and(a,b)
local op1=bit.d2b(a)
local op2=bit.d2b(b)
local r={}
for i=1,32 do
if op1[i]==1 and op2[i]==1 then
r[i]=1
else
r[i]=0
end
end
return bit.b2d(r)
end --bit:_and
function bit._or(a,b)
local op1=bit.d2b(a)
local op2=bit.d2b(b)
local r={}
for i=1,32 do
if op1[i]==1 or op2[i]==1 then
r[i]=1
else
r[i]=0
end
end
return bit.b2d(r)
end --bit:_or
function bit._not(a)
local op1=bit.d2b(a)
local r={}
for i=1,32 do
if op1[i]==1 then
r[i]=0
else
r[i]=1
end
end
return bit.b2d(r)
end --bit:_not
function bit._rshift(a,n)
local op1=bit.d2b(a)
local r=bit.d2b(0)
if n < 32 and n > 0 then
for i=1,n do
for i=31,1,-1 do
op1[i+1]=op1[i]
end
op1[1]=0
end
r=op1
end
return bit.b2d(r)
end --bit:_rshift
function bit._lshift(a,n)
local op1=bit.d2b(a)
local r=bit.d2b(0)
if n < 32 and n > 0 then
for i=1,n do
for i=1,31 do
op1[i]=op1[i+1]
end
op1[32]=0
end
r=op1
end
return bit.b2d(r)
end --bit:_lshift
function bit.print(ta)
local sr=""
for i=1,32 do
sr=sr..ta[i]
end
print(sr)
end
-------------------------------- core
y_key = {1206625642, 1092691841, 3888211297, 1403752353}
t_key = {768304513, 3648063403, 1200350539, 1135324489}
y_live_key = {2380375339, 3372821835, 757854091, 3417384251}
t_live_key = {1307283402, 3415975219, 130748267, 1094264761}
function getConfused(flag)
local ftr = math.log10(1000);
local ftr2 = math.log10(100);
local key = {};
if flag==0 then
key = y_key;
elseif flag == 1 then
key = t_key;
elseif flag == 2 then
key = y_live_key;
elseif flag == 3 then
key = t_live_key;
end
local a = math.max(key[1], ftr);
local b = math.min(key[2], ftr2);
local c = math.max(key[3], ftr);
local d = math.min(key[4], ftr2);
return a, b, c, d;
end
function doDec(ciphertxt, len, flag)
dc = luajava.newInstance("com.decapi.Decryptions");
local L, l, R, r = getConfused(flag);
ret = dc:AESDec(ciphertxt, len, math.btan2(L, l, R, r));
return ret;
end
function doEnc(plaintxt, flag)
ec = luajava.newInstance("com.decapi.Decryptions");
local L, l, R, r = getConfused(flag);
ret = ec:AESEnc(plaintxt, math.btan2(L, l, R, r));
return ret;
end | apache-2.0 |
tudelft/chdkptp | lua/extras/simplemulticam.lua | 6 | 3361 | --[[
Copyright (C) 2013 <reyalp (at) gmail dot com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--]]
--[[
simple script to connect and shoot multiple cameras
no effort is made to shoot cameras in sync, see multicam.lua for that
usage
chdkptp -e"exec m=dofile('simplemulticam.lua'); \
m.connect({dev='<cam 1 dev id>'}); \
m.connect({dev='<cam 2 dev id>'}); \
m.shoot({tv96=<tv96>,iso=<real ISO value>})"
]]
local m = {}
-- connections
m.cams = {}
m.verbose=2
m.infomsg = util.make_msgf( function() return m.verbose end, 1)
m.dbgmsg = util.make_msgf( function() return m.verbose end, 2)
--[[
devpsec should be an array of
{
dev={device},
bus={bus}
}
but for compatibility with test_keypedal.sh, accepts empty bus and attempts to guess
--]]
function m.connect(devspec)
if type(devspec) ~= 'table' then
error('missing or invalid devspec:'..tostring(devspec))
end
if not devspec.dev then
error('missing device id')
end
if not devspec.bus then
local devs=chdk.list_usb_devices()
if not devs then
error('no devices found');
end
for i,d in ipairs(devs) do
if devspec.dev == d.dev then
if devspec.bus then
error(string.format("multiple devices matching dev %s\n",tostring(devspec.dev)))
end
m.dbgmsg("found bus %s for dev %s\n",tostring(d.bus),tostring(devspec.dev))
devspec.bus = d.bus
end
end
if not devspec.bus then
error('no devices match dev:'..tostring(devspec.dev))
end
end
local lcon = chdku.connection(devspec)
-- if not already connected, try to connect
if lcon:is_connected() then
lcon:update_connection_info()
else
lcon:connect()
end
-- if connection didn't fail
if lcon:is_connected() then
m.dbgmsg('%d:%s bus=%s dev=%s sn=%s\n',
#m.cams+1,
lcon.ptpdev.model,
lcon.condev.dev,
lcon.condev.bus,
tostring(lcon.ptpdev.serial_number))
table.insert(m.cams,lcon)
end
end
--[[
connect to all available devices
--]]
function m.connect_all()
local devs=chdk.list_usb_devices()
if not devs then
error('no devices found');
end
for i,d in ipairs(devs) do
m.connect(d)
end
end
--[[
do con:exec on all connections
--]]
function m.exec(code,opts)
for i,lcon in ipairs(m.cams) do
local status,err = lcon:exec_pcall(code,opts)
if not status then
error(string.format('exec cam %d failed %s',i,tostring(err)))
end
end
end
--[[
--shoot(opts)
where opts is (optionally)
{
tv96=<tv96>,
iso=<iso_real>,
}
does not wait for execution to complete or check for runtime errors
--]]
function m.shoot(opts)
if opts then
optstr = util.serialize(opts)
else
optstr = '{}'
end
m.exec([[
function do_shot(opts)
if opts.tv96 then
set_tv96_direct(opts.tv96)
end
if opts.iso then
set_iso_real(opts.iso)
end
shoot()
end
]]..'do_shot('..optstr..')')
end
return m
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.