code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
<#--通过主机ID查询模板ID--> { "jsonrpc": "2.0", "method": "host.get", "params": { "output": [ "hostid" ], "selectParentTemplates": [ "templateid", "name" ], "filter": { "host": [ "${hostname}" ] } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/host/host.tempid.get.ftl
Fluent
gpl-3.0
388
{ "jsonrpc": "2.0", "method": "host.update", "params": { "hostid":"${hostid}", <#if interfaces??> "interfaces": [ { "type": ${interfaces.type}, "main": ${interfaces.main}, "useip": ${interfaces.useip}, "ip": "${interfaces.ip}", "dns": "${interfaces.dns}", "port": "${interfaces.port}" } ], </#if> <#if proxyid??> "proxy_hostid": "${proxyid}", </#if> "groups": [ <#if groupids??> <#list groupids as groupid> { "groupid": "${groupid}" }<#if groupid_has_next>,</#if> </#list> </#if> ], "templates": [ { "templateid": "${templateid}" } ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/host/host.update.ftl
Fluent
gpl-3.0
965
{ "jsonrpc": "2.0", "method": "hostgroup.create", "params": { "name": "${hostGroupName}" }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/hostgroup/hostgroup.create.ftl
Fluent
gpl-3.0
156
{ "jsonrpc": "2.0", "method": "hostgroup.delete", "params": [ <#if hostGroupIds??> <#list hostGroupIds as hostgroupid> "${hostgroupid}"<#if hostgroupid_has_next>,</#if> </#list> </#if> ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/hostgroup/hostgroup.delete.ftl
Fluent
gpl-3.0
300
{ "jsonrpc": "2.0", "method": "hostgroup.get", "params": { "output": "extend", "groupids": ${groupids} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/hostgroup/hostgroup.get.ftl
Fluent
gpl-3.0
178
{ "jsonrpc": "2.0", "method": "hostgroup.get", "params": { "output": [ "groupid" ], "filter": { "name": [ "__global__" ] } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/hostgroup/hostgroup.global.get.ftl
Fluent
gpl-3.0
266
{ "jsonrpc": "2.0", "method": "hostgroup.create", "params": { "name": "__global__" }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/hostgroup/hostgroup.init.create.ftl
Fluent
gpl-3.0
150
{ "jsonrpc": "2.0", "method": "hostinterface.get", "params": { "hostids": ${hostid} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/hostinterface/hostinterface.get.ftl
Fluent
gpl-3.0
151
{ "jsonrpc": "2.0", "method": "item.create", "params": { "name": "温度", "key_": "temp_01", "hostid": "10468", "type": 2, "value_type": 4, "preprocessing": [ { "type": 25, "params": "a\nb", "error_handler": "0", "error_handler_params": "" } ] }, "auth": "d32e7060656e0de30a3cc1ac23b34974", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/item/item.dependent.create.ftl
Fluent
gpl-3.0
469
{ "jsonrpc": "2.0", "method": "item.get", "params": { "selectTags":"extend", "selectValueMap":"extend", "selectPreprocessing":"extend", <#if key??> "search":{ "key_":"${key}" }, </#if> <#if itemId??> "itemids": ${itemId}, </#if> <#if hostid??> "hostids": ${hostid}, </#if> "output": [ "itemid", "hostid", "name", "key_", "status", "value_type", "units", "valuemapid", "interfaceid", "error" ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/item/item.get.ftl
Fluent
gpl-3.0
724
{ "jsonrpc": "2.0", "method": "item.create", "params": { "name": "温度", "key_": "temp_01", "hostid": "10468", "type": 2, "value_type": 4, "preprocessing": [ { "type": 25, "params": "a\nb", "error_handler": "0", "error_handler_params": "" } ] }, "auth": "d32e7060656e0de30a3cc1ac23b34974", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/item/item.http.create.ftl
Fluent
gpl-3.0
469
{ "jsonrpc": "2.0", "method": "item.get", "params": { "selectHosts":["host"], <#if name??> "search":{ "name":"${name}" }, </#if> "output": [ "itemid", "hostid", "name", "key_", "status", "value_type", "units", "valuemapid", "interfaceid" ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/item/item.name.get.ftl
Fluent
gpl-3.0
487
{ "jsonrpc": "2.0", "method": "item.create", "params": { "name": "温度", "key_": "temp_01", "hostid": "10468", "type": 2, "value_type": 4, "preprocessing": [ { "type": 25, "params": "a\nb", "error_handler": "0", "error_handler_params": "" } ] }, "auth": "d32e7060656e0de30a3cc1ac23b34974", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/item/item.snmp.create.ftl
Fluent
gpl-3.0
469
{ "jsonrpc": "2.0", "method": "item.create", "params": { "name": "${itemName}", "key_": "${itemKey}", "hostid": "${hostId}", "type": ${source}, <#if interfaceid??> "interfaceid": "${interfaceid}", </#if> "trends":"0", <#if delay??> "delay":"${delay}", </#if> "history":"30d", <#if source == '18'> "master_itemid":${masterItemid}, </#if> "value_type": ${valueType}, <#if valuemapid?? && valuemapid != ''> "valuemapid":${valuemapid}, </#if> <#if valueType == '0' || valueType == '3'> <#if units??> "units": "${units}", </#if> </#if> "preprocessing": [ <#if processList??> <#list processList as process> { "type": ${process.type}, "params": "${process.params}", "error_handler": "0", "error_handler_params": "" }<#if process_has_next>,</#if> </#list> </#if> ], "tags": [ <#if tagMap??> <#list tagMap? keys as key> { "tag": "${key}", "value": "${tagMap[key]}" }<#if key_has_next>,</#if> </#list> </#if> ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/item/item.trapper.create.ftl
Fluent
gpl-3.0
1,428
{ "jsonrpc": "2.0", "method": "item.delete", "params": [ <#if itemIds??> <#list itemIds as itemid> "${itemid}"<#if itemid_has_next>,</#if> </#list> </#if> ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/item/item.trapper.delete.ftl
Fluent
gpl-3.0
270
{ "jsonrpc": "2.0", "method": "item.update", "params": { "itemid": "${itemid}", "name": "${itemName}", "key_": "${itemKey}", "hostid": "${hostId}", <#if interfaceid??> "interfaceid": "${interfaceid}", </#if> "type": ${source}, <#if delay??> "delay":"${delay}", </#if> <#if source == '18'> "master_itemid":${masterItemid}, </#if> "value_type": ${valueType}, <#if valuemapid?? && valuemapid != ''> "valuemapid":${valuemapid}, </#if> <#if valueType == '0' || valueType == '3'> <#if units??> "units": "${units}", </#if> </#if> "preprocessing": [ <#if processList??> <#list processList as process> { "type": ${process.type}, "params": "${process.params}", "error_handler": "0", "error_handler_params": "" }<#if process_has_next>,</#if> </#list> </#if> ], "tags": [ <#if tagMap??> <#list tagMap? keys as key> { "tag": "${key}", "value": "${tagMap[key]}" }<#if key_has_next>,</#if> </#list> </#if> ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/item/item.trapper.update.ftl
Fluent
gpl-3.0
1,432
{ "jsonrpc": "2.0", "method": "usermacro.create", "params": { "hostid": "${hostid}", "macro": "${macro}", "value": "${value}" <#if description??> ,"description":"${description}" </#if> }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/macro/usermacro.create.ftl
Fluent
gpl-3.0
296
{ "jsonrpc": "2.0", "method": "usermacro.delete", "params": [ <#list macroids as id> "${id}"<#if id_has_next>,</#if> </#list> ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/macro/usermacro.delete.ftl
Fluent
gpl-3.0
213
{ "jsonrpc": "2.0", "method": "usermacro.get", "params": { "output": [ "macro", "value", "description" ], "hostids": "${hostid}", <#if macro??> "filter": { "macro": "${macro}" } </#if> }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/macro/usermacro.filter.get.ftl
Fluent
gpl-3.0
348
{ "jsonrpc": "2.0", "method": "usermacro.get", "params": { "output": [ "hostmacroid", "macro", "value", "description" ], "hostids": "${hostid}" }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/macro/usermacro.get.ftl
Fluent
gpl-3.0
275
{ "jsonrpc": "2.0", "method": "usermacro.update", "params": { "hostmacroid": "${macroid}", "macro": "${macro}", "value": "${value}", <#if description??> "description":"${description}" </#if> }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/macro/usermacro.update.ftl
Fluent
gpl-3.0
298
{ "jsonrpc": "2.0", "method": "event.acknowledge", "params": { "eventids": "${eventId}", "action": ${action} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/problem/problem.acknowledgement.ftl
Fluent
gpl-3.0
184
{ "jsonrpc": "2.0", "method": "problem.get", "params": { "output": "extend", "selectTags": "extend", "recent": ${recent}, "sortfield": ["eventid"], <#if hostId??> "hostids":${hostId}, </#if> <#if timeFrom??> "time_from":${timeFrom}, </#if> <#if timeTill??> "time_till":${timeTill}, </#if> "tags":[{"tag": "__event__"}], "filter":{ "source":"0" }, "sortorder": "DESC" }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/problem/problem.event.get.ftl
Fluent
gpl-3.0
586
{ "jsonrpc": "2.0", "method": "problem.get", "params": { "output": "extend", "selectAcknowledges": "extend", "selectTags": "extend", "selectSuppressionData": "extend", "recent": ${recent}, "sortfield": ["eventid"], <#if hostId??> "hostids":${hostId}, </#if> <#if timeFrom??> "time_from":${timeFrom}, </#if> <#if timeTill??> "time_till":${timeTill}, </#if> <#if severity?? && severity != ''> "severities":${severity}, </#if> "tags":[{"tag": "__alarm__"}], "filter":{ "source":"0" }, "sortorder": "DESC" }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/problem/problem.get.ftl
Fluent
gpl-3.0
765
{ "jsonrpc": "2.0", "method": "proxy.create", "params": { "host": "${name}", "status": "5" }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/proxy/proxy.create.ftl
Fluent
gpl-3.0
166
{ "jsonrpc": "2.0", "method": "proxy.delete", "params": [ <#if hostIds??> <#list hostIds as hostId> "${hostId}"<#if hostId_has_next>,</#if> </#list> </#if> ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/proxy/proxy.delete.ftl
Fluent
gpl-3.0
271
{ "jsonrpc": "2.0", "method": "proxy.get", "params": { "output": "extend", "selectInterface": "extend", "proxyids": ${proxyids} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/proxy/proxy.get.ftl
Fluent
gpl-3.0
211
{ "jsonrpc": "2.0", "method": "role.get", "params": { "output": "extend", "filter": { "name":"Super admin role" } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/role/adminRole.get.ftl
Fluent
gpl-3.0
209
{ "jsonrpc": "2.0", "method": "role.get", "params": { "output": "extend", "filter": { "name":"Guest role" } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/role/guestRole.get.ftl
Fluent
gpl-3.0
203
{ "jsonrpc": "2.0", "method": "role.get", "params": { "output": "extend", "filter": { "name":"Super admin role" } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/role/superAdminRole.get.ftl
Fluent
gpl-3.0
209
{ "jsonrpc": "2.0", "method": "script.create", "params": [ { "name": "__offline_status__", <#--上下线 调用 webapp--> "command": "curl -H \\"Content-Type:application/json\\" -X POST --data '{\\"hostname\\":\\"{HOST.HOST}\\",\\"recovery\\":\\"{EVENT.RECOVERY.STATUS}\\"}' http://127.0.0.1:9090/device/status", "type": 0, "execute_on": 1 },{ "name": "__trigger_webhook__", <#-- 告警 回调 --> "command": "curl -H \\"Content-Type:application/json\\" -X POST --data '{\\"hostname\\":\\"{HOST.HOST}\\",\\"triggerName\\":\\"{TRIGGER.NAME}\\"}' http://127.0.0.1:9090/device/problem", "type": 0, "execute_on": 1 },{ "name": "__trigger_execute__", <#-- 执行 方法 --> "command": "curl -H \\"Content-Type:application/json\\" -X POST --data '{\\"triggerName\\":\\"{TRIGGER.NAME}\\",\\"triggerId\\":\\"{TRIGGER.ID}\\"}' http://127.0.0.1:12800/device/action/exec", "type": 0, "execute_on": 1 },{ "name": "__attr_event__", <#-- 属性事件 回调 --> "command": "curl -H \\"Content-Type:application/json\\" -X POST --data '{\\"hostname\\":\\"{HOST.HOST}\\",\\"itemName\\":\\"{ITEM.NAME}\\"}' http://127.0.0.1:12800/device/event", "type": 0, "execute_on": 1 } ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/script/script.init.create.ftl
Fluent
gpl-3.0
1,447
{ "jsonrpc": "2.0", "method": "script.get", "params": { "output": [ "scriptid", "name" ], "search": { "name": "__" <#--在线状态--> } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/script/script.offline.get.ftl
Fluent
gpl-3.0
264
{ "jsonrpc": "2.0", "method": "template.create", "params": { "host": "${templateName}", "groups": { "groupid": ${groupId} } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/template/template.create.ftl
Fluent
gpl-3.0
235
{ "jsonrpc": "2.0", "method": "template.delete", "params": [ "${templateid}" ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/template/template.delete.ftl
Fluent
gpl-3.0
144
{ "jsonrpc": "2.0", "method": "template.get", "params": { "output": "extend", "selectTags":"extend", "selectMacros":"extend", "selectValueMaps":"extend", "templateids":${templateid} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/template/template.detail.get.ftl
Fluent
gpl-3.0
285
{ "jsonrpc": "2.0", "method": "template.get", "params": { "output": "extend", "templateids":${templateid} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/template/template.get.ftl
Fluent
gpl-3.0
185
{ "jsonrpc": "2.0", "method": "template.update", "params": { "templateid": "${templateId}", "tags": [ <#if tagMap??> <#list tagMap? keys as key> { "tag": "${key}", "value": "${tagMap[key]}" }<#if key_has_next>,</#if> </#list> </#if> ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/template/template.tag.update.ftl
Fluent
gpl-3.0
446
{ "name": "${runnerName}", "batch_interval": ${batchInterval}, "batch_size": ${batchSize}, "extra_info": false, "reader": { "log_path": "${logPath}", "read_from": "oldest", "datasource_tag": "datasource", "encoding": "UTF-8", "mode": "file" }, "cleaner": {}, "parser": { "type": "json", "keep_raw_data": "false", "name": "parser", "disable_record_errdata": "false" }, "transforms": [ { "key": "groups,applications,datasource,name", "type": "discard" }, { "key": "type", "mode": "keep", "pattern": "^[0|3]$", "type": "filter" }, { "key": "source", "override": false, "type": "label", "value": "s1" } ], "senders": [{ "http_sender_url": "http://127.0.0.1:12800/zabbix/data-transfer", "http_sender_protocol": "json", "http_sender_escape_html": "true", "http_sender_csv_split": ",", "http_sender_gzip": "true", "http_sender_timeout": "30s", "ft_strategy": "backup_only", "ft_discard_failed_data": "false", "ft_memory_channel": "false", "ft_long_data_discard": "false", "max_disk_used_bytes": "524288000", "max_size_per_file": "104857600", "sender_type": "http" }] }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/transfer/create.ftl
Fluent
gpl-3.0
1,459
{ "jsonrpc": "2.0", "method": "trigger.create", "params": [ { "description": "${ruleId}", <#--trigger name--> <#if ruleFunction == "nodata"> "expression": "nodata(/${deviceId}/${itemKey},${ruleCondition}) = 1", <#--下线规则,nodata = 1 --> <#else> "expression": "last(/${deviceId}/${itemKey}) ${ruleFunction} ${ruleCondition}", </#if> "recovery_mode": 2, "type": 1, "tags": [ { "tag": "__offline__", "value": "{HOST.HOST}" <#--device id--> } ] }, { "description": "${ruleId}", <#--trigger name--> "recovery_mode": 2, "type": 1, <#if ruleFunctionRecovery == "nodata"> "expression": "nodata(/${deviceId}/${itemKeyRecovery},${ruleConditionRecovery}) = 0", <#-- 上线规则 nodata = 0 --> <#else> "expression": "last(/${deviceId}/${itemKeyRecovery}) ${ruleFunctionRecovery} ${ruleConditionRecovery}", </#if> "tags": [ { "tag": "__online__", "value": "{HOST.HOST}" <#--device id--> } ] } <#-- nodata(/Zabbix server/system.cpu.util[,nice],20s)=0 --> ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/device.status.trigger.ftl
Fluent
gpl-3.0
1,449
{ "jsonrpc": "2.0", "method": "trigger.update", "params": [ { "triggerid": "${triggerId}", "description": "${ruleId}", <#--trigger name--> <#if ruleFunction == "nodata"> "expression": "nodata(/${deviceId}/${itemKey},${ruleCondition}) = 1" <#--下线规则,nodata = 1 --> <#else> "expression": "last(/${deviceId}/${itemKey}) ${ruleFunction} ${ruleCondition}" </#if> },{ "triggerid": "${recoveryTriggerId}", "description": "${ruleId}", <#--trigger name--> <#if ruleFunctionRecovery == "nodata"> "expression": "nodata(/${deviceId}/${itemKeyRecovery},${ruleConditionRecovery}) = 0" <#-- 上线规则 nodata = 0 --> <#else> "expression": "last(/${deviceId}/${itemKeyRecovery}) ${ruleFunctionRecovery} ${ruleConditionRecovery}" </#if> } <#-- nodata(/Zabbix server/system.cpu.util[,nice],20s)=0 --> ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/device.status.trigger.update.ftl
Fluent
gpl-3.0
1,069
{ "jsonrpc": "2.0", "method": "trigger.create", "params": { "description": "${triggerName}", "expression": "${expression}", "priority" : ${ruleLevel}, "manual_close":1 }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/trigger.create.ftl
Fluent
gpl-3.0
259
{ "jsonrpc": "2.0", "method": "trigger.delete", "params": [ ${triggerid} ], "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/trigger.delete.ftl
Fluent
gpl-3.0
140
{ "jsonrpc": "2.0", "method": "trigger.create", "params": { "description": "${triggerName}", "expression": "${expression}", "priority" : ${ruleLevel}, "manual_close":1, "recovery_mode":2, "type":1 }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/trigger.execute.create.ftl
Fluent
gpl-3.0
304
{ "jsonrpc": "2.0", "method": "trigger.get", "params": { "selectHosts":["host"], "selectTags":["tag"], <#if triggerIds??> "triggerids":${triggerIds}, </#if> <#if host??> "host":"${host}", </#if> <#if description??> "filter":{ "description":${description} }, </#if> "output": "extend" }, "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/trigger.get.ftl
Fluent
gpl-3.0
467
{ "jsonrpc": "2.0", "method": "trigger.update", "params": { "triggerid": "${triggerid}", "status": ${status} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/trigger.status.update.ftl
Fluent
gpl-3.0
184
{ "jsonrpc": "2.0", "method": "trigger.update", "params": { "triggerid": "${triggerId}", "tags": [ <#list tagMap?keys as key> { "tag": "${key}", "value": "${tagMap[key]}" }<#if key_has_next>,</#if> </#list> ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/trigger.tags.update.ftl
Fluent
gpl-3.0
372
{ "jsonrpc": "2.0", "method": "trigger.update", "params": { "triggerid": "${triggerId}", "expression": "${expression}", "priority" : ${ruleLevel} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/trigger.update.ftl
Fluent
gpl-3.0
229
{ "jsonrpc": "2.0", "method": "trigger.get", "params": { "selectTags":"extend", "triggerids":${triggerIds}, "output": "extend" }, "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/trigger/triggerAndTags.get.ftl
Fluent
gpl-3.0
210
{ "jsonrpc": "2.0", "method": "user.create", "params": { "username": "cookie", "passwd": "cookie", "roleid": "${roleId}", "usrgrps": [ { "usrgrpid": "${usrGrpId}" } ] }, "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/user/cookieUserAdd.ftl
Fluent
gpl-3.0
302
{ "jsonrpc": "2.0", "method": "user.get", "params": { "output": "extend", "filter":{ "username":"cookie" } }, "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/user/cookieUserGet.ftl
Fluent
gpl-3.0
202
{ "jsonrpc": "2.0", "method": "user.create", "params": { "username": "${name}", "passwd": "${password}", "roleid": "${roleId}", "autologout":"0s", "usrgrps": [ { "usrgrpid": "${usrGrpId}" } ] }, "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/user/userAdd.ftl
Fluent
gpl-3.0
335
{ "jsonrpc": "2.0", "method": "user.delete", "params": [ <#--删除用户 ID--> <#if usrids??> <#list usrids as usrid> ${usrid} <#if usrid_has_next>,</#if> </#list> </#if> ], "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/user/userDelete.ftl
Fluent
gpl-3.0
295
{ "jsonrpc": "2.0", "method": "user.get", "params": { "output": "extend", "userids": ${userids} }, "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/user/userGet.ftl
Fluent
gpl-3.0
171
{ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "${username}", "password": "${password}" }, "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/user/userLogin.ftl
Fluent
gpl-3.0
153
{ "jsonrpc": "2.0", "method": "user.update", "params": { "userid": "${userId}", "roleid": "${roleId}", "usrgrps": [ { "usrgrpid": "${usrGrpId}" } ] }, "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/user/userUpdate.ftl
Fluent
gpl-3.0
279
{ "jsonrpc": "2.0", "method": "user.update", "params": { "userid": "${userId}", "passwd": "${passwd}" }, "id": 1, "auth": "${userAuth}" }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/user/userUpdatePwd.ftl
Fluent
gpl-3.0
177
{ "jsonrpc": "2.0", "method": "usergroup.create", "params": { "name": "cookie", "gui_access": 0, "rights": { "permission": 2, "id": "${hostGroupId}" } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/usergroup/cookieUserGroupCreate.ftl
Fluent
gpl-3.0
266
{ "jsonrpc": "2.0", "method": "usergroup.get", "params": { "output": "extend", "status": 0, "filter":{ "name":"cookie" } }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/usergroup/cookieUserGroupGet.ftl
Fluent
gpl-3.0
224
{ "jsonrpc": "2.0", "method": "usergroup.update", "params": { "rights": [ <#if hostGroupIds??> <#list hostGroupIds as hostGrpId> { "id":"${hostGrpId}", "permission":"3" <#--读写权限--> } <#if hostGrpId_has_next>,</#if> </#list> </#if> ], "usrgrpid": "${userGroupId}" }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/usergroup/userGroupBindHostGroup.ftl
Fluent
gpl-3.0
518
{ "jsonrpc": "2.0", "method": "usergroup.create", "params": { "name": "${userGroupName}", "gui_access": 3 }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/usergroup/userGroupCreate.ftl
Fluent
gpl-3.0
181
{ "jsonrpc": "2.0", "method": "usergroup.delete", "params": [ <#--删除用户组 ids --> <#if usrgrpids??> <#list usrgrpids as id> ${id} <#if id_has_next>,</#if> </#list> </#if> ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/usergroup/userGroupDelete.ftl
Fluent
gpl-3.0
302
{ "jsonrpc": "2.0", "method": "usergroup.get", "params": { "output": "extend", "usrgrpids": ${usrgrpids} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/usergroup/userGroupGet.ftl
Fluent
gpl-3.0
180
{ "jsonrpc": "2.0", "method": "valuemap.create", "params": { "hostid": "${hostId}", "name": "${valueMapName}", "mappings": [ <#if valMaps??> <#list valMaps?keys as key> { "type": "0", <#--全部精确匹配--> "value": "${key}", "newvalue": "${valMaps[key]}" }<#if key_has_next>,</#if> </#list> </#if> ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/valuemap/valuemap.create.ftl
Fluent
gpl-3.0
563
{ "jsonrpc": "2.0", "method": "valuemap.delete", "params": [ "${valueMapId}" ], "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/valuemap/valuemap.delete.ftl
Fluent
gpl-3.0
144
{ "jsonrpc": "2.0", "method": "valuemap.get", "params": { "output": "extend", "selectMappings": "extend", "valuemapids": ${valuemapids} }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/valuemap/valuemap.get.ftl
Fluent
gpl-3.0
219
{ "jsonrpc": "2.0", "method": "valuemap.update", "params": { "name": "${valueMapName}", "valuemapid":${valueMapId}, "mappings": [ <#if valMaps??> <#list valMaps?keys as key> { "type": "0", <#--全部精确匹配--> "value": "${key}", "newvalue": "${valMaps[key]}" }<#if key_has_next>,</#if> </#list> </#if> ] }, "auth": "${userAuth}", "id": 1 }
2301_81045437/zeus-iot
zeus-driver/src/main/resources/api-json/valuemap/valuemap.update.ftl
Fluent
gpl-3.0
392
package com.zmops.iot.media; import com.zmops.iot.domain.alarm.AlarmMessage; import java.util.List; /** * Alarm call back will be called by alarm implementor, after it decided alarm should be sent. */ public interface AlarmCallback { void doAlarm(List<AlarmMessage> alarmMessage,Long tenantId); String getType(); }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/AlarmCallback.java
Java
gpl-3.0
330
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zmops.iot.media; import java.util.ArrayList; import java.util.List; /** * This is a formatter especially for alarm message. * <p> * Format string in alarm-settings.yml, such as: * <p> * - Successful rate of endpoint {name} is lower than 75% */ public class AlarmMessageFormatter { private List<String> formatSegments; private List<ValueFrom> valueFroms; public AlarmMessageFormatter(String format) { if (format == null) { format = ""; } formatSegments = new ArrayList<>(); this.valueFroms = new ArrayList<>(); boolean match = false; int idx = 0; do { match = false; int start = format.indexOf("{", idx); if (start > -1) { int end = format.indexOf("}", start); if (end > -1) { String name = format.substring(start + 1, end); switch (name) { case "id": valueFroms.add(ValueFrom.ID); break; case "name": valueFroms.add(ValueFrom.NAME); break; default: throw new IllegalArgumentException("Var [" + name + "] in alarm message [" + format + "] is illegal"); } formatSegments.add(format.substring(idx, start)); idx = end + 1; match = true; } } if (!match) { formatSegments.add(format.substring(idx)); } } while (match); } // public String format(MetaInAlarm meta) { // StringBuilder message = new StringBuilder(); // for (int i = 0; i < formatSegments.size(); i++) { // message.append(formatSegments.get(i)); // if (i != formatSegments.size() - 1) { // switch (valueFroms.get(i)) { // case ID: // message.append(meta.getId0()); // break; // case NAME: // message.append(meta.getName()); // } // } // } // return message.toString(); // } private enum ValueFrom { ID, NAME } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/AlarmMessageFormatter.java
Java
gpl-3.0
3,188
package com.zmops.iot.media; import com.zmops.iot.domain.messages.NoticeResult; import com.zmops.iot.domain.sys.SysUser; import java.util.Map; public interface Notice { int sms = 1; int email = 2; int wechat = 3; int dingtalk = 4; /** * 发送通知 * * @param receiver * @param macroMap * @return */ NoticeResult send(SysUser receiver, Map<String, String> macroMap); int getType(); int getSilent(); }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/Notice.java
Java
gpl-3.0
481
package com.zmops.iot.media; import com.zmops.iot.domain.messages.NoticeResult; import com.zmops.iot.domain.messages.query.QNoticeRecord; import com.zmops.iot.domain.sys.SysUser; import com.zmops.iot.util.LocalDateTimeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Collection; import java.util.HashMap; import java.util.Map; @Service public class NoticeService { @Autowired Collection<Notice> notices; public Map<Integer, NoticeResult> notice(SysUser sysUser, Map<String, String> macroMap,String triggerId) { // Problem problem = problemMapper.selectById(Integer.parseInt(macroMap.get("${eventId}"))); Map<Integer, NoticeResult> res = new HashMap<>(); notices.forEach(notice -> { int type = notice.getType(); QNoticeRecord eq = new QNoticeRecord().noticeType .eq(type).creatTime .ge(LocalDateTimeUtils.minu(LocalDateTime.now(), notice.getSilent(), ChronoUnit.MINUTES)) .problemId.eq(triggerId); if (eq.findCount() > 0) { return; } try { NoticeResult send = notice.send(sysUser, macroMap); if (send.getStatus() != NoticeResult.NoticeStatus.skipped) { res.put(notice.getType(), send); } } catch (Exception e) { e.printStackTrace(); } }); return res; } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/NoticeService.java
Java
gpl-3.0
1,617
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zmops.iot.media; import com.zmops.iot.domain.alarm.AlarmMessage; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.config.RequestConfig; import java.util.List; @Slf4j public class WebhookCallback implements AlarmCallback { private static final int HTTP_CONNECT_TIMEOUT = 1000; private static final int HTTP_CONNECTION_REQUEST_TIMEOUT = 1000; private static final int HTTP_SOCKET_TIMEOUT = 10000; private RequestConfig requestConfig; @Override public void doAlarm(List<AlarmMessage> alarmMessage,Long tenantId) { } @Override public String getType() { return "Dingding"; } // private Gson gson = new Gson(); // // public WebhookCallback(AlarmRulesWatcher alarmRulesWatcher) { // this.alarmRulesWatcher = alarmRulesWatcher; // requestConfig = RequestConfig.custom() // .setConnectTimeout(HTTP_CONNECT_TIMEOUT) // .setConnectionRequestTimeout(HTTP_CONNECTION_REQUEST_TIMEOUT) // .setSocketTimeout(HTTP_SOCKET_TIMEOUT) // .build(); // } // // @Override // public void doAlarm(List<AlarmMessage> alarmMessage) { // if (alarmRulesWatcher.getWebHooks().isEmpty()) { // return; // } // // CloseableHttpClient httpClient = HttpClients.custom().build(); // try { // alarmRulesWatcher.getWebHooks().forEach(url -> { // HttpPost post = new HttpPost(url); // post.setConfig(requestConfig); // post.setHeader(HttpHeaders.ACCEPT, HttpHeaderValues.APPLICATION_JSON.toString()); // post.setHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON.toString()); // // StringEntity entity; // CloseableHttpResponse httpResponse = null; // try { // entity = new StringEntity(gson.toJson(alarmMessage), StandardCharsets.UTF_8); // post.setEntity(entity); // httpResponse = httpClient.execute(post); // StatusLine statusLine = httpResponse.getStatusLine(); // if (statusLine != null && statusLine.getStatusCode() != HttpStatus.SC_OK) { // log.error("send alarm to " + url + " failure. Response code: " + statusLine.getStatusCode()); // } // } catch (UnsupportedEncodingException e) { // log.error("Alarm to JSON error, " + e.getMessage(), e); // } catch (IOException e) { // log.error("send alarm to " + url + " failure.", e); // } finally { // if (httpResponse != null) { // try { // httpResponse.close(); // } catch (IOException e) { // log.error(e.getMessage(), e); // } // // } // } // }); // } finally { // try { // httpClient.close(); // } catch (IOException e) { // log.error(e.getMessage(), e); // } // } // } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/WebhookCallback.java
Java
gpl-3.0
4,130
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zmops.iot.media.dingtalk; import com.zmops.iot.domain.alarm.AlarmMessage; import com.zmops.iot.media.AlarmCallback; import io.netty.handler.codec.http.HttpHeaderValues; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.List; @Slf4j @Service public class DingtalkHookCallback implements AlarmCallback { private static final int HTTP_CONNECT_TIMEOUT = 1000; private static final int HTTP_CONNECTION_REQUEST_TIMEOUT = 1000; private static final int HTTP_SOCKET_TIMEOUT = 10000; private RequestConfig requestConfig; @Autowired DingtalkSettingService dingtalkSettingService; public DingtalkHookCallback() { this.requestConfig = RequestConfig.custom() .setConnectTimeout(HTTP_CONNECT_TIMEOUT) .setConnectionRequestTimeout(HTTP_CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(HTTP_SOCKET_TIMEOUT) .build(); } /** * Send alarm message if the settings not empty */ @Override public void doAlarm(List<AlarmMessage> alarmMessages,Long tenantId) { DingtalkSettings dingtalkSettings = dingtalkSettingService.get(tenantId); if (dingtalkSettings == null || dingtalkSettings.getWebhooks().isEmpty()) { return; } try (CloseableHttpClient httpClient = HttpClients.custom().build()) { dingtalkSettings.getWebhooks().forEach(webHookUrl -> { String url = getUrl(webHookUrl); alarmMessages.forEach(alarmMessage -> { String requestBody = String.format( dingtalkSettings.getTextTemplate(), alarmMessage.getAlarmMessage() ); sendAlarmMessage(httpClient, url, requestBody); }); }); } catch (IOException e) { log.error(e.getMessage(), e); } } /** * Get webhook url, sign the url when secret is not empty. */ private String getUrl(DingtalkSettings.WebHookUrl webHookUrl) { if (StringUtils.isBlank(webHookUrl.getSecret())) { return webHookUrl.getUrl(); } return getSignUrl(webHookUrl); } /** * Sign webhook url using secret and timestamp */ private String getSignUrl(DingtalkSettings.WebHookUrl webHookUrl) { try { Long timestamp = System.currentTimeMillis(); return String.format("%s&timestamp=%s&sign=%s", webHookUrl.getUrl(), timestamp, sign(timestamp, webHookUrl.getSecret())); } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) { throw new RuntimeException(e); } } /** * Sign webhook url using HmacSHA256 algorithm */ private String sign(final Long timestamp, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { String stringToSign = timestamp + "\n" + secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); return URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), StandardCharsets.UTF_8.name()); } /** * Send alarm message to remote endpoint */ private void sendAlarmMessage(CloseableHttpClient httpClient, String url, String requestBody) { CloseableHttpResponse httpResponse = null; try { HttpPost post = new HttpPost(url); post.setConfig(requestConfig); post.setHeader(HttpHeaders.ACCEPT, HttpHeaderValues.APPLICATION_JSON.toString()); post.setHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON.toString()); StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); post.setEntity(entity); httpResponse = httpClient.execute(post); StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() != HttpStatus.SC_OK) { log.error("send dingtalk alarm to {} failure. Response code: {}, Response content: {}", url, statusLine.getStatusCode(), EntityUtils.toString(httpResponse.getEntity())); } } catch (Throwable e) { log.error("send dingtalk alarm to {} failure.", url, e); } finally { if (httpResponse != null) { try { httpResponse.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } } @Override public String getType() { return "dingtalk"; } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/dingtalk/DingtalkHookCallback.java
Java
gpl-3.0
6,623
package com.zmops.iot.media.dingtalk; import com.alibaba.fastjson.JSONObject; import com.zmops.iot.domain.alarm.MediaTypeSetting; import com.zmops.iot.domain.alarm.query.QMediaTypeSetting; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** * @author yefei **/ @Service public class DingtalkSettingService { private volatile DingtalkSettings instance; private volatile Map<Long, DingtalkSettings> instanceMap = new ConcurrentHashMap<>(); public DingtalkSettings get(Long tenantId) { if (null == tenantId) { return getOne(); } else { return getFromMap(tenantId); } } private DingtalkSettings getFromMap(Long tenantId) { if (instanceMap.get(tenantId) != null) { return instanceMap.get(tenantId); } MediaTypeSetting setting = new QMediaTypeSetting().type.eq("dingtalk").tenantId.eq(tenantId).findOne(); DingtalkSettings instance = buildDingdingSetting(setting); instanceMap.put(tenantId,instance); return instance; } private DingtalkSettings getOne() { if (instance != null) { return instance; } MediaTypeSetting setting = new QMediaTypeSetting().type.eq("dingtalk").tenantId.isNull().findOne(); return instance = buildDingdingSetting(setting); } private DingtalkSettings buildDingdingSetting(MediaTypeSetting setting) { JSONObject jsonObject = JSONObject.parseObject(setting.getWebhooks()); String secret = Optional.ofNullable(jsonObject.getString("secret")).orElse(""); String url = Optional.ofNullable(jsonObject.getString("url")).orElse(""); return DingtalkSettings.builder().textTemplate(setting.getTemplate()) .webhooks(Arrays.asList(new DingtalkSettings.WebHookUrl(secret, url))).build(); } public void test() { } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/dingtalk/DingtalkSettingService.java
Java
gpl-3.0
2,004
package com.zmops.iot.media.dingtalk; import lombok.*; import java.util.ArrayList; import java.util.List; @Builder @NoArgsConstructor @AllArgsConstructor @ToString @Data public class DingtalkSettings { private String textTemplate; @Builder.Default private List<WebHookUrl> webhooks = new ArrayList<>(); @AllArgsConstructor @ToString @Data public static class WebHookUrl { private final String secret; private final String url; } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/dingtalk/DingtalkSettings.java
Java
gpl-3.0
484
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zmops.iot.media.feishu; import com.alibaba.fastjson.JSONObject; import com.zmops.iot.domain.alarm.AlarmMessage; import com.zmops.iot.media.AlarmCallback; import com.zmops.iot.util.ToolUtil; import io.netty.handler.codec.http.HttpHeaderValues; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Slf4j @Service public class FeishuHookCallback implements AlarmCallback { private static final int HTTP_CONNECT_TIMEOUT = 1000; private static final int HTTP_CONNECTION_REQUEST_TIMEOUT = 1000; private static final int HTTP_SOCKET_TIMEOUT = 10000; @Autowired FeishuSettingService feishuSettingService; @Override public String getType() { return "feishu"; } private RequestConfig requestConfig; public FeishuHookCallback() { this.requestConfig = RequestConfig.custom() .setConnectTimeout(HTTP_CONNECT_TIMEOUT) .setConnectionRequestTimeout(HTTP_CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(HTTP_SOCKET_TIMEOUT) .build(); } /** * Send alarm message if the settings not empty */ @Override public void doAlarm(List<AlarmMessage> alarmMessages,Long tenantId) { FeishuSettings feishuSettings = feishuSettingService.get(tenantId); if (feishuSettings == null || feishuSettings.getWebhooks().isEmpty()) { return; } CloseableHttpClient httpClient = HttpClients.custom().build(); try { feishuSettings.getWebhooks().forEach(webHookUrl -> { alarmMessages.forEach(alarmMessage -> { String requestBody = String.format( feishuSettings.getTextTemplate(), alarmMessage.getAlarmMessage() ); requestBody = getRequestBody(webHookUrl, alarmMessage, requestBody); sendAlarmMessage(httpClient, webHookUrl.getUrl(), requestBody); }); }); } finally { try { httpClient.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } /** * deal requestBody,if has sign set the sign */ private String getRequestBody(FeishuSettings.WebHookUrl webHookUrl, AlarmMessage alarmMessage, String requestBody) { JSONObject jsonObject = JSONObject.parseObject(requestBody); Map<String, Object> content = buildContent(jsonObject); if (ToolUtil.isNotEmpty(webHookUrl.getSecret())) { Long timestamp = System.currentTimeMillis() / 1000; content.put("timestamp", timestamp); try { content.put("sign", sign(timestamp, webHookUrl.getSecret())); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } } return JSONObject.toJSONString(content); } /** * build content,if has ats someone set the ats */ private Map<String, Object> buildContent(JSONObject jsonObject) { Map<String, Object> content = new HashMap<>(); content.put("msg_type", jsonObject.getString("msg_type")); if (jsonObject.get("ats") != null) { String ats = jsonObject.getString("ats"); String text = jsonObject.getJSONObject("content").getString("text"); List<String> collect = Arrays.stream(ats.split(",")) .map(String::trim).collect(Collectors.toList()); for (String userId : collect) { text += "<at user_id=\"" + userId + "\"></at>"; } jsonObject.getJSONObject("content").put("text", text); } content.put("content", jsonObject.getJSONObject("content")); return content; } /** * Sign webhook url using HmacSHA256 algorithm */ private String sign(final Long timestamp, String secret) throws NoSuchAlgorithmException, InvalidKeyException { String stringToSign = timestamp + "\n" + secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(stringToSign.getBytes(), "HmacSHA256")); byte[] signData = mac.doFinal(); return Base64.encodeBase64String(signData); } /** * Send alarm message to remote endpoint */ private void sendAlarmMessage(CloseableHttpClient httpClient, String url, String requestBody) { CloseableHttpResponse httpResponse = null; try { HttpPost post = new HttpPost(url); // post.setConfig(requestConfig); post.setHeader(HttpHeaders.ACCEPT, HttpHeaderValues.APPLICATION_JSON.toString()); post.setHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON.toString()); StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); post.setEntity(entity); httpResponse = httpClient.execute(post); StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() != HttpStatus.SC_OK) { log.error("send feishu alarm to {} failure. Response code: {}, Response content: {}", url, statusLine.getStatusCode(), EntityUtils.toString(httpResponse.getEntity())); } } catch (Throwable e) { log.error("send feishu alarm to {} failure.", url, e); } finally { if (httpResponse != null) { try { httpResponse.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/feishu/FeishuHookCallback.java
Java
gpl-3.0
7,504
package com.zmops.iot.media.feishu; import com.alibaba.fastjson.JSONObject; import com.zmops.iot.domain.alarm.MediaTypeSetting; import com.zmops.iot.domain.alarm.query.QMediaTypeSetting; import com.zmops.iot.media.dingtalk.DingtalkSettings; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** * @author yefei **/ @Service public class FeishuSettingService { private volatile FeishuSettings instance; private volatile Map<Long, FeishuSettings> instanceMap = new ConcurrentHashMap<>(); public FeishuSettings get(Long tenantId) { if (null == tenantId) { return getOne(); } else { return getFromMap(tenantId); } } private FeishuSettings getFromMap(Long tenantId) { if (instanceMap.get(tenantId) != null) { return instanceMap.get(tenantId); } MediaTypeSetting setting = new QMediaTypeSetting().type.eq("feishu").tenantId.eq(tenantId).findOne(); FeishuSettings instance = buildFeishuSetting(setting); instanceMap.put(tenantId,instance); return instance; } private FeishuSettings getOne() { if (instance != null) { return instance; } MediaTypeSetting setting = new QMediaTypeSetting().type.eq("feishu").tenantId.isNull().findOne(); return instance = buildFeishuSetting(setting); } private FeishuSettings buildFeishuSetting(MediaTypeSetting setting) { JSONObject jsonObject = JSONObject.parseObject(setting.getWebhooks()); String secret = Optional.ofNullable(jsonObject.getString("secret")).orElse(""); String url = Optional.ofNullable(jsonObject.getString("url")).orElse(""); return FeishuSettings.builder().textTemplate(setting.getTemplate()) .webhooks(Arrays.asList(new FeishuSettings.WebHookUrl(secret, url))).build(); } public void test() { } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/feishu/FeishuSettingService.java
Java
gpl-3.0
2,024
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zmops.iot.media.feishu; import lombok.*; import java.util.ArrayList; import java.util.List; @Builder @NoArgsConstructor @AllArgsConstructor @Setter @Getter @ToString public class FeishuSettings { private String textTemplate; @Builder.Default private List<WebHookUrl> webhooks = new ArrayList<>(); @AllArgsConstructor @Setter @Getter @ToString public static class WebHookUrl { private final String secret; private final String url; } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/feishu/FeishuSettings.java
Java
gpl-3.0
1,310
package com.zmops.iot.media.mail; import lombok.Data; import lombok.NoArgsConstructor; /** * 邮件内容 * @author yefei * **/ @Data @NoArgsConstructor public class MailMessage { /** * 收件人名称 */ private String user; /** * 告警信息 */ private String message; /** * 服务 */ private String server; /** * 对象类型 */ private String objectType; /** * 告警规则 */ private String alarmRule; /** * 告警等级 */ private String level; /** * 告警时间 */ private String time; /** * ip */ private String ip; /** * 指标值 */ private String table; }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/mail/MailMessage.java
Java
gpl-3.0
741
package com.zmops.iot.media.mail; import com.zmops.iot.domain.messages.MailSetting; import com.zmops.iot.domain.messages.NoticeResult; import com.zmops.iot.media.Notice; public interface MailNotice extends Notice { NoticeResult test(MailSetting setting, String receiver); }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/mail/MailNotice.java
Java
gpl-3.0
282
package com.zmops.iot.media.mail; import com.zmops.iot.domain.messages.MailSetting; import com.zmops.iot.domain.messages.NoticeResult; import com.zmops.iot.domain.sys.SysUser; import com.zmops.iot.util.ToolUtil; import freemarker.template.Template; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * @author yefei **/ @Service public class MailNoticer implements MailNotice { @Autowired MailSettingService mailSettingService; @Autowired private FreeMarkerConfigurer configurer; @Override public NoticeResult test(MailSetting setting, String receiver) { return MailUtils.test(setting, receiver); } @Override public NoticeResult send(SysUser receiver, Map<String, String> macroMap) { if (ToolUtil.isEmpty(receiver.getEmail())) { return NoticeResult.skipped(); } MailSetting setting = mailSettingService.get(); if (setting == null) { return NoticeResult.skipped(); } if (!setting.getSeverity().contains(macroMap.get("${severity}"))) { return NoticeResult.skipped(); } Integer problemId = Integer.parseInt(macroMap.get("${problemId}")); String alarmInfo = "【Zeus】 触发[${level}]告警“[${context}]”,[${time}]。请及时处理。"; for (Map.Entry<String, String> entry : macroMap.entrySet()) { String value = Optional.ofNullable(entry.getValue()).orElse(""); alarmInfo = alarmInfo.replace(entry.getKey(), value); } try { MailUtils.send(setting, mimeMessage -> { try { String subject = "触发${level}告警", content = "【Zeus】 触发[${level}]告警“[${context}]”,[${time}]。请及时处理。\n"; for (Map.Entry<String, String> entry : macroMap.entrySet()) { String value = Optional.ofNullable(entry.getValue()).orElse(""); subject = subject.replace(entry.getKey(), value); content = content.replace(entry.getKey(), value); } MailMessage message = new MailMessage(); message.setUser(receiver.getName()); message.setMessage(content); message.setAlarmRule(macroMap.get("${metricName}")); message.setLevel(macroMap.get("${level}")); message.setObjectType(macroMap.get("${typeName}")); message.setServer(macroMap.get("${topMoType}")); message.setTime(macroMap.get("${time}")); // message.setTable(values.toString()); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); helper.setFrom(setting.getSender());//发送者 helper.setTo(receiver.getEmail());//接收者 helper.setSubject(subject);//邮件标题 Map<String, Object> model = new HashMap<>(); model.put("params", message); Template template = configurer.getConfiguration().getTemplate("argusAlarmEmailTemplate.html", "UTF-8"); String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); helper.setText(text, true); } catch (Exception e) { e.printStackTrace(); } }); } catch (Exception e) { e.printStackTrace(); return NoticeResult.failed("发送失败: " + StringUtils.left(e.getMessage(), 100), alarmInfo, receiver.getEmail()); } return NoticeResult.success(alarmInfo, receiver.getEmail()); } @Override public int getType() { return email; } @Override public int getSilent() { MailSetting setting = mailSettingService.get(); return Optional.ofNullable(setting.getSilent()).orElse(3); } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/mail/MailNoticer.java
Java
gpl-3.0
4,422
package com.zmops.iot.media.mail; import com.zmops.iot.domain.messages.MailParam; import com.zmops.iot.domain.messages.MailSetting; import com.zmops.iot.domain.messages.NoticeResult; /** * @author yefei * @email yefei@zmops.com * @date Created in 2020/11/10 18:58 * @Description */ public interface MailSettingService { MailSetting get(); NoticeResult test(MailParam mailTestVo); Integer updateSettings(MailSetting mailTestVo); }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/mail/MailSettingService.java
Java
gpl-3.0
452
package com.zmops.iot.media.mail; import com.sun.mail.util.MailSSLSocketFactory; import com.zmops.iot.domain.messages.MailSetting; import com.zmops.iot.domain.messages.NoticeResult; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; import java.security.GeneralSecurityException; import java.util.Properties; import java.util.function.Consumer; /** * @author yefei * <p> * 邮件发送工具类 **/ public class MailUtils { public static void send(MailSetting setting, Consumer<MimeMessage> consumer) throws GeneralSecurityException, javax.mail.MessagingException { Properties prop = new Properties(); prop.setProperty("mail.smtp.host", setting.getHost()); prop.setProperty("mail.smtp.port", setting.getPort().toString()); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); prop.setProperty("mail.smtp.connectiontimeout", "2000"); prop.setProperty("mail.smtp.writetimeout", "5000"); if (setting.sslAvailable()) { MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); } if (setting.tlsAvailable()) { prop.put("mail.smtp.ssl.checkserveridentity", "false"); prop.put("mail.smtp.ssl.trust", setting.getHost()); prop.put("mail.smtp.host", setting.getHost()); prop.put("mail.smtp.starttls.enable", "true"); } Session session = Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.getAccount(), setting.getPassword()); } }); Transport transport = session.getTransport(); transport.connect(setting.getHost(), setting.getAccount(), setting.getPassword()); MimeMessage mimeMessage = new MimeMessage(session); consumer.accept(mimeMessage); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } /** * 仅限于页面测试功能调用 * * @param setting * @param receiver * @return */ public static NoticeResult test(MailSetting setting, String receiver) { try { send(setting, mimeMessage -> { try { MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(setting.getSender()); helper.setTo(receiver); helper.setSubject("Zesu-iot邮件测试"); helper.setText("这是一封Zesu-iot测试邮件,请不要回复。", false); } catch (javax.mail.MessagingException e) { e.printStackTrace(); } }); return NoticeResult.success(); } catch (Exception e) { e.printStackTrace(); return NoticeResult.failed(e.getMessage()); } } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/mail/MailUtils.java
Java
gpl-3.0
3,356
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zmops.iot.media.wechat; import com.zmops.iot.domain.alarm.AlarmMessage; import com.zmops.iot.media.AlarmCallback; import io.netty.handler.codec.http.HttpHeaderValues; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.List; @Slf4j @Service public class WechatHookCallback implements AlarmCallback { private static final int HTTP_CONNECT_TIMEOUT = 1000; private static final int HTTP_CONNECTION_REQUEST_TIMEOUT = 1000; private static final int HTTP_SOCKET_TIMEOUT = 10000; private RequestConfig requestConfig; @Autowired WechatSettingService wechatSettingService; @Override public String getType() { return "wechat"; } public WechatHookCallback() { this.requestConfig = RequestConfig.custom() .setConnectTimeout(HTTP_CONNECT_TIMEOUT) .setConnectionRequestTimeout(HTTP_CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(HTTP_SOCKET_TIMEOUT) .build(); } @Override public void doAlarm(List<AlarmMessage> alarmMessages,Long tenantId) { // WechatSettings wechatSettings = wechatSettingService.get(tenantId); // if (wechatSettings == null || wechatSettings.getWebhooks().isEmpty()) { // return; // } // CloseableHttpClient httpClient = HttpClients.custom().build(); // try { // wechatSettings.getWebhooks().forEach(url -> { // alarmMessages.forEach(alarmMessage -> { // String requestBody = String.format( // wechatSettings.getTextTemplate(), alarmMessage.getAlarmMessage() // ); // sendAlarmMessage(httpClient, url, requestBody); // }); // }); // } finally { // try { // httpClient.close(); // } catch (IOException e) { // log.error(e.getMessage(), e); // } // } } private void sendAlarmMessage(CloseableHttpClient httpClient, String url, String requestBody) { CloseableHttpResponse httpResponse = null; try { HttpPost post = new HttpPost(url); post.setConfig(requestConfig); post.setHeader(HttpHeaders.ACCEPT, HttpHeaderValues.APPLICATION_JSON.toString()); post.setHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON.toString()); StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); post.setEntity(entity); httpResponse = httpClient.execute(post); StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() != HttpStatus.SC_OK) { log.error("send wechat alarm to {} failure. Response code: {} ", url, statusLine.getStatusCode()); } } catch (Throwable e) { log.error("send wechat alarm to {} failure.", url, e); } finally { if (httpResponse != null) { try { httpResponse.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/wechat/WechatHookCallback.java
Java
gpl-3.0
4,605
package com.zmops.iot.media.wechat; import com.alibaba.fastjson.JSONObject; import com.zmops.iot.domain.alarm.MediaTypeSetting; import com.zmops.iot.domain.alarm.query.QMediaTypeSetting; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author yefei **/ @Service public class WechatSettingService { private volatile WechatSettings instance; private volatile Map<Long, WechatSettings> instanceMap = new ConcurrentHashMap<>(); public WechatSettings get(Long tenantId) { if (null == tenantId) { return getOne(); } else { return getFromMap(tenantId); } } private WechatSettings getFromMap(Long tenantId) { if (instanceMap.get(tenantId) != null) { return instanceMap.get(tenantId); } MediaTypeSetting setting = new QMediaTypeSetting().type.eq("wechat").tenantId.eq(tenantId).findOne(); WechatSettings instance = buildWechatSetting(setting); instanceMap.put(tenantId, instance); return instance; } private WechatSettings getOne() { if (instance != null) { return instance; } MediaTypeSetting setting = new QMediaTypeSetting().type.eq("wechat").findOne(); return instance = buildWechatSetting(setting); } private WechatSettings buildWechatSetting(MediaTypeSetting setting) { JSONObject jsonObject = JSONObject.parseObject(setting.getWebhooks()); // String secret = Optional.ofNullable(jsonObject.getString("secret")).orElse(""); // String url = Optional.ofNullable(jsonObject.getString("url")).orElse(""); return WechatSettings.builder().textTemplate(setting.getTemplate()) .webhooks(Arrays.asList("")).build(); } public void test() { } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/wechat/WechatSettingService.java
Java
gpl-3.0
1,913
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zmops.iot.media.wechat; import lombok.*; import java.util.ArrayList; import java.util.List; @Builder @NoArgsConstructor @AllArgsConstructor @Data @ToString public class WechatSettings { private String textTemplate; @Builder.Default private List<String> webhooks = new ArrayList<>(); }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/wechat/WechatSettings.java
Java
gpl-3.0
1,120
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zmops.iot.media.welink; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.zmops.iot.domain.alarm.AlarmMessage; import com.zmops.iot.media.AlarmCallback; import io.netty.handler.codec.http.HttpHeaderValues; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; @Slf4j @Service public class WeLinkHookCallback implements AlarmCallback { @Autowired WeLinkSettingService weLinkSettingService; private static final int HTTP_CONNECT_TIMEOUT = 1000; private static final int HTTP_CONNECTION_REQUEST_TIMEOUT = 1000; private static final int HTTP_SOCKET_TIMEOUT = 10000; private final RequestConfig requestConfig; public WeLinkHookCallback() { this.requestConfig = RequestConfig.custom() .setConnectTimeout(HTTP_CONNECT_TIMEOUT) .setConnectionRequestTimeout(HTTP_CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(HTTP_SOCKET_TIMEOUT) .build(); } /** * Send alarm message if the settings not empty */ @Override public void doAlarm(List<AlarmMessage> alarmMessages,Long tenantId) { // WeLinkSettings weLinkSettings = weLinkSettingService.get(tenantId); // if (weLinkSettings == null || weLinkSettings.getWebhooks().isEmpty()) { // return; // } // weLinkSettings.getWebhooks().forEach(webHookUrl -> { // String accessToken = getAccessToken(webHookUrl); // alarmMessages.forEach(alarmMessage -> { // String content = String.format( // Locale.US, // weLinkSettings.getTextTemplate(), // alarmMessage.getAlarmMessage() // ); // sendAlarmMessage(webHookUrl, accessToken, content); // }); // }); } /** * Send alarm message to remote endpoint */ private void sendAlarmMessage(WeLinkSettings.WebHookUrl webHookUrl, String accessToken, String content) { JSONObject appServiceInfo = new JSONObject(); appServiceInfo.put("app_service_id", "1"); appServiceInfo.put("app_service_name", webHookUrl.getRobotName()); JSONArray groupIds = new JSONArray(); Arrays.stream(webHookUrl.getGroupIds().split(",")).forEach(groupIds::add); JSONObject body = new JSONObject(); body.put("app_service_info", appServiceInfo); body.put("app_msg_id", UUID.randomUUID().toString()); body.put("group_id", groupIds); body.put("content", String.format( Locale.US, "<r><n></n><g>0</g><c>&lt;imbody&gt;&lt;imagelist/&gt;" + "&lt;html&gt;&lt;![CDATA[&lt;DIV&gt;%s&lt;/DIV&gt;]]&gt;&lt;/html&gt;&lt;content&gt;&lt;![CDATA[%s]]&gt;&lt;/content&gt;&lt;/imbody&gt;</c></r>", content, content )); body.put("content_type", 0); body.put("client_app_id", "1"); sendPostRequest( webHookUrl.getMessageUrl(), Collections.singletonMap("x-wlk-Authorization", accessToken), body.toString()); } /** * Get access token from remote endpoint */ private String getAccessToken(WeLinkSettings.WebHookUrl webHookUrl) { String accessTokenUrl = webHookUrl.getAccessTokenUrl(); String clientId = webHookUrl.getClientId(); String clientSecret = webHookUrl.getClientSecret(); String response = sendPostRequest( accessTokenUrl, Collections.emptyMap(), String.format(Locale.US, "{\"client_id\":%s,\"client_secret\":%s}", clientId, clientSecret) ); JSONObject responseJson = JSONObject.parseObject(response); return Optional.ofNullable(responseJson) .map(r -> r.getString("access_token")) .orElse(""); } /** * Post rest invoke */ private String sendPostRequest(String url, Map<String, String> headers, String requestBody) { String response = ""; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost post = new HttpPost(url); post.setConfig(requestConfig); post.setHeader(HttpHeaders.ACCEPT, HttpHeaderValues.APPLICATION_JSON.toString()); post.setHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON.toString()); headers.forEach(post::setHeader); StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); post.setEntity(entity); try (CloseableHttpResponse httpResponse = httpClient.execute(post)) { StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine != null) { if (statusLine.getStatusCode() != HttpStatus.SC_OK) { log.error("send to {} failure. Response code: {}, Response content: {}", url, statusLine.getStatusCode(), EntityUtils.toString(httpResponse.getEntity()) ); } else { response = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8); } } } catch (IOException e) { log.error(e.getMessage(), e); } } catch (IOException e) { log.error(e.getMessage(), e); } return response; } @Override public String getType() { return "welink"; } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/welink/WeLinkHookCallback.java
Java
gpl-3.0
7,051
package com.zmops.iot.media.welink; import com.alibaba.fastjson.JSONObject; import com.zmops.iot.domain.alarm.MediaTypeSetting; import com.zmops.iot.domain.alarm.query.QMediaTypeSetting; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Map; /** * @author yefei **/ @Service public class WeLinkSettingService { private volatile WeLinkSettings instance; public WeLinkSettings get(Long tenantId) { return getOne(); } private WeLinkSettings getOne() { if (instance != null) { return instance; } MediaTypeSetting setting = new QMediaTypeSetting().type.eq("welink").findOne(); return instance = buildWeLinkSetting(setting); } private WeLinkSettings buildWeLinkSetting(MediaTypeSetting setting) { Map map = JSONObject.parseObject(setting.getWebhooks(), Map.class); // String clientId = Optional.ofNullable(jsonObject.getString("clientId")).orElse(""); // String clientSecret = Optional.ofNullable(jsonObject.getString("clientSecret")).orElse(""); // String accessTokenUrl = Optional.ofNullable(jsonObject.getString("accessTokenUrl")).orElse(""); // String messageUrl = Optional.ofNullable(jsonObject.getString("messageUrl")).orElse(""); return WeLinkSettings.builder().textTemplate(setting.getTemplate()) .webhooks(Arrays.asList(WeLinkSettings.WebHookUrl.generateFromMap(map))).build(); } public void updateSettings(MediaTypeSetting WechatSetting) { } public void test() { } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/welink/WeLinkSettingService.java
Java
gpl-3.0
1,623
package com.zmops.iot.media.welink; import lombok.*; import java.util.ArrayList; import java.util.List; import java.util.Map; @Builder @NoArgsConstructor @AllArgsConstructor @Data @ToString public class WeLinkSettings { private String textTemplate; @Builder.Default private List<WebHookUrl> webhooks = new ArrayList<>(); @AllArgsConstructor @Data @ToString public static class WebHookUrl { // The unique identity of the application, used for interface authentication to obtain access_token private final String clientId; // The application key is used for interface authentication to obtain access_token private final String clientSecret; // The url get access token private final String accessTokenUrl; // The url to send message private final String messageUrl; // Name display in group private final String robotName; // The groupIds message to send private final String groupIds; public static WebHookUrl generateFromMap(Map<String, String> params) { String clientId = params.get("clientId"); String clientSecret = params.get("clientSecret"); String accessTokenUrl = params.get("accessTokenUrl"); String messageUrl = params.get("messageUrl"); String groupIds = params.get("groupIds"); String robotName = params.getOrDefault("robotName", "robot"); return new WebHookUrl(clientId, clientSecret, accessTokenUrl, messageUrl, robotName, groupIds ); } } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/media/welink/WeLinkSettings.java
Java
gpl-3.0
1,620
package com.zmops.iot.message.config; /** * @author nantian created at 2021/9/26 23:15 */ public interface Event { /** * 聊天事件 */ String CHAT = "chat"; /** * 广播消息 */ String BROADCAST = "broadcast"; /** * 群聊 */ String GROUP = "group"; /** * 加入群聊 */ String JOIN = "join"; }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/config/Event.java
Java
gpl-3.0
378
package com.zmops.iot.message.config; import cn.hutool.core.util.StrUtil; import com.corundumstudio.socketio.SocketConfig; import com.corundumstudio.socketio.SocketIOServer; import com.corundumstudio.socketio.annotation.SpringAnnotationScanner; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author nantian created at 2021/9/26 22:39 */ @Configuration @EnableConfigurationProperties({SocketIoConfig.class}) public class MessageServerConfig { @Bean public SocketIOServer server(SocketIoConfig socketIoConfig) { com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); SocketConfig socketConfig = new SocketConfig(); socketConfig.setReuseAddress(true); config.setSocketConfig(socketConfig); config.setHostname(socketIoConfig.getHost()); config.setPort(socketIoConfig.getPort()); config.setAuthorizationListener(data -> { String token = data.getSingleUrlParam("token"); return StrUtil.isNotBlank(token); }); return new SocketIOServer(config); } /** * Spring 扫描自定义注解 */ @Bean public SpringAnnotationScanner springAnnotationScanner(SocketIOServer server) { return new SpringAnnotationScanner(server); } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/config/MessageServerConfig.java
Java
gpl-3.0
1,466
package com.zmops.iot.message.config; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author nantian created at 2021/9/26 22:47 */ @Getter @Setter @ConfigurationProperties(prefix = "socketio.server") public class SocketIoConfig { /** * 端口号 */ private Integer port; /** * host */ private String host; }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/config/SocketIoConfig.java
Java
gpl-3.0
429
package com.zmops.iot.message.config; import cn.hutool.core.collection.CollUtil; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @Component public class UserClientMap { public static final ConcurrentHashMap<String, UUID> DB = new ConcurrentHashMap<>(); public List<UUID> findAll() { return CollUtil.newArrayList(DB.values()); } public Optional<UUID> findByUserId(String userId) { return Optional.ofNullable(DB.get(userId)); } public void save(String userId, UUID sessionId) { DB.put(userId, sessionId); } public void deleteByUserId(String userId) { DB.remove(userId); } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/config/UserClientMap.java
Java
gpl-3.0
773
package com.zmops.iot.message.controller; import com.zmops.iot.message.handler.MessageEventHandler; import com.zmops.iot.message.payload.BroadcastMessageRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * @author nantian created at 2021/9/27 0:16 */ @Slf4j @RestController @RequestMapping("/send") public class SocketIoController { @Autowired private MessageEventHandler messageHandler; /** * just for test * * @param message */ @PostMapping("/broadcast") public void broadcast(@RequestBody BroadcastMessageRequest message) { messageHandler.sendToBroadcast(message); } @PostMapping("/sendToUser") public void sendToUser(@RequestParam("userId") String userId,@RequestParam("msg") String msg) { messageHandler.sendToUser(userId,msg); } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/controller/SocketIoController.java
Java
gpl-3.0
926
package com.zmops.iot.message.handler; import com.corundumstudio.socketio.AckRequest; import com.corundumstudio.socketio.SocketIOClient; import com.corundumstudio.socketio.SocketIOServer; import com.corundumstudio.socketio.annotation.OnConnect; import com.corundumstudio.socketio.annotation.OnDisconnect; import com.corundumstudio.socketio.annotation.OnEvent; import com.zmops.iot.message.config.Event; import com.zmops.iot.message.config.UserClientMap; import com.zmops.iot.message.payload.BroadcastMessageRequest; import com.zmops.iot.message.payload.GroupMessageRequest; import com.zmops.iot.message.payload.JoinRequest; import com.zmops.iot.message.payload.SingleMessageRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.UUID; /** * @author nantian created at 2021/9/26 23:13 */ @Slf4j @Component public class MessageEventHandler { @Autowired private SocketIOServer server; @Autowired private UserClientMap userClient; @OnConnect public void onConnect(SocketIOClient client) { if (client != null) { String token = client.getHandshakeData().getSingleUrlParam("token"); String userId = client.getHandshakeData().getSingleUrlParam("userId"); UUID sessionId = client.getSessionId(); userClient.save(userId, sessionId); log.info("socketio connect successfully,【token】= {},【sessionId】= {}", token, sessionId); } } @OnDisconnect public void onDisconnect(SocketIOClient client) { if (client != null) { String userId = client.getHandshakeData().getSingleUrlParam("token"); userClient.deleteByUserId(userId); client.disconnect(); } } @OnEvent(value = Event.JOIN) public void onJoinEvent(SocketIOClient client, AckRequest request, JoinRequest data) { log.info("user:{} has join group chat:{}", data.getUserId(), data.getGroupId()); client.joinRoom(data.getGroupId()); server.getRoomOperations(data.getGroupId()).sendEvent(Event.JOIN, data); } @OnEvent(value = Event.CHAT) public void onChatEvent(SocketIOClient client, AckRequest request, SingleMessageRequest data) { System.out.println(data.getMessage()); } @OnEvent(value = Event.GROUP) public void onGroupEvent(SocketIOClient client, AckRequest request, GroupMessageRequest data) { Collection<SocketIOClient> clients = server.getRoomOperations(data.getGroupId()).getClients(); } public void sendDisconnectMsg(String userId) { if (userClient.findByUserId(userId).isPresent()) { UUID uuid = userClient.findByUserId(userId).get(); if (null != server.getClient(uuid)) { BroadcastMessageRequest message = new BroadcastMessageRequest(); message.setMessage("disconnect"); server.getClient(uuid).sendEvent(Event.BROADCAST, message); } } } public void sendToUser(String userId, String msg) { if (userClient.findByUserId(userId).isPresent()) { UUID uuid = userClient.findByUserId(userId).get(); if (null != server.getClient(uuid)) { BroadcastMessageRequest message = new BroadcastMessageRequest(); message.setMessage(msg); server.getClient(uuid).sendEvent(Event.BROADCAST, message); } } } public void sendToBroadcast(BroadcastMessageRequest message) { for (UUID clientId : userClient.findAll()) { if (server.getClient(clientId) == null) { continue; } server.getClient(clientId).sendEvent(Event.BROADCAST, message); } } public void sendToGroup(GroupMessageRequest message) { server.getRoomOperations(message.getGroupId()).sendEvent(Event.GROUP, message); } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/handler/MessageEventHandler.java
Java
gpl-3.0
4,034
package com.zmops.iot.message.payload; import lombok.Data; /** * @author nantian created at 2021/9/26 23:16 */ @Data public class BroadcastMessageRequest { /** * 消息内容 */ private String message; }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/payload/BroadcastMessageRequest.java
Java
gpl-3.0
227
package com.zmops.iot.message.payload; import lombok.Data; /** * @author nantian created at 2021/9/26 23:16 */ @Data public class GroupMessageRequest { /** * 消息发送方用户id */ private String fromUid; /** * 群组id */ private String groupId; /** * 消息内容 */ private String message; }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/payload/GroupMessageRequest.java
Java
gpl-3.0
359
package com.zmops.iot.message.payload; import lombok.Data; /** * @author nantian created at 2021/9/26 23:16 */ @Data public class JoinRequest { /** * 用户id */ private String userId; /** * 群名称 */ private String groupId; }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/payload/JoinRequest.java
Java
gpl-3.0
271
package com.zmops.iot.message.payload; import lombok.Data; /** * @author nantian created at 2021/9/26 23:16 */ @Data public class SingleMessageRequest { /** * 消息发送方用户id */ private String fromUid; /** * 消息接收方用户id */ private String toUid; /** * 消息内容 */ private String message; }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/payload/SingleMessageRequest.java
Java
gpl-3.0
373
package com.zmops.iot.message.server; import com.corundumstudio.socketio.SocketIOServer; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; /** * @author nantian created at 2021/9/26 23:21 */ @Slf4j @Component public class SocketIoServer implements CommandLineRunner { @Autowired private SocketIOServer server; @Override public void run(String... args) throws Exception { server.start(); } /** * 退出时 销毁 SocketIOServer * * @throws Exception */ @PreDestroy public void stop() throws Exception { server.stop(); } }
2301_81045437/zeus-iot
zeus-message/src/main/java/com/zmops/iot/message/server/SocketIoServer.java
Java
gpl-3.0
786
package com.zmops.iot.rest.controller; import com.zmops.iot.model.response.ResponseData; import com.zmops.iot.web.device.dto.param.DeviceParams; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author yefei * <p> * 告警记录接口 **/ @RestController @RequestMapping("/rest/alarm") public class AlarmRestController { /** * 告警列表 * * @return */ @PostMapping("/list") public ResponseData deviceList(@RequestBody DeviceParams deviceParams) { return ResponseData.success(); } }
2301_81045437/zeus-iot
zeus-rest/src/main/java/com/zmops/iot/rest/controller/AlarmRestController.java
Java
gpl-3.0
741