announced.lua 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. local announce = require 'gluon.announce'
  2. local deflate = require 'deflate'
  3. local json = require 'luci.jsonc'
  4. local util = require 'luci.util'
  5. local nixio = require 'nixio'
  6. local fs = require 'nixio.fs'
  7. local memoize = {}
  8. nixio.chdir('/lib/gluon/announce/')
  9. for dir in fs.glob('*.d') do
  10. local name = dir:sub(1, -3)
  11. memoize[name] = {
  12. collect = announce.collect(dir),
  13. -- tonumber will return 0 for invalid inputs
  14. cache_time = tonumber(util.trim(fs.readfile(name .. '.cache') or ''))
  15. }
  16. end
  17. local function collect(type, timestamp)
  18. local c = memoize[type]
  19. if not c then
  20. return nil
  21. end
  22. if c.cache_timeout and timestamp < c.cache_timeout then
  23. return c.cache
  24. else
  25. local ret = c.collect()
  26. if c.cache_time then
  27. c.cache = ret
  28. c.cache_timeout = timestamp + c.cache_time
  29. end
  30. return ret
  31. end
  32. end
  33. module('gluon.announced', package.seeall)
  34. function handle_request(query, timestamp)
  35. collectgarbage()
  36. local m = query:match('^GET ([a-z ]+)$')
  37. local ret
  38. if m then
  39. local data = {}
  40. for q in m:gmatch('([a-z]+)') do
  41. local ok, val = pcall(collect, q, timestamp)
  42. if ok then
  43. data[q] = val
  44. end
  45. end
  46. if next(data) then
  47. ret = deflate.compress(json.stringify(data))
  48. end
  49. elseif query:match('^[a-z]+$') then
  50. local ok, data = pcall(collect, query, timestamp)
  51. if ok then
  52. ret = json.stringify(data)
  53. end
  54. end
  55. collectgarbage()
  56. return ret
  57. end