From 9eb699ea3b82c1474d8bbfb0a7a7832fb4482093 Mon Sep 17 00:00:00 2001 From: Alex Ling Date: Mon, 7 Jun 2021 07:04:49 +0000 Subject: [PATCH] Add plugin subscription types --- src/plugin/plugin.cr | 18 ++++++++ src/plugin/subscriptions.cr | 87 +++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 src/plugin/subscriptions.cr diff --git a/src/plugin/plugin.cr b/src/plugin/plugin.cr index be08d6f..f6fd2a7 100644 --- a/src/plugin/plugin.cr +++ b/src/plugin/plugin.cr @@ -2,6 +2,8 @@ require "duktape/runtime" require "myhtml" require "xml" +require "./subscriptions" + class Plugin class Error < ::Exception end @@ -131,6 +133,22 @@ class Plugin @info.not_nil! end + def subscribe(subscription : Subscription) + list = SubscriptionList.new info.dir + list << subscription + list.save + end + + def list_subscriptions + SubscriptionList.new(info.dir).ary + end + + def unsubscribe(id : String) + list = SubscriptionList.new info.dir + list.reject &.id.== id + list.save + end + def initialize(id : String) Plugin.build_info_ary diff --git a/src/plugin/subscriptions.cr b/src/plugin/subscriptions.cr new file mode 100644 index 0000000..daca785 --- /dev/null +++ b/src/plugin/subscriptions.cr @@ -0,0 +1,87 @@ +require "uuid" + +enum FilterType + String + NumMin + NumMax + DateMin + DateMax + Array + + def self.from_string(str) + case str + when "string" + String + when "number-min" + NumMin + when "number-max" + NumMax + when "date-min" + DateMin + when "date-max" + DateMax + when "array" + Array + else + raise "Unknown filter type with string #{str}" + end + end +end + +struct Filter + include JSON::Serializable + + property key : String + property value : String | Int32 | Int64 | Float32 | Nil + property type : FilterType + + def initialize(@key, @value, @type) + end + + def self.from_json(str) : Filter + json = JSON.parse str + key = json["key"].as_s + type = FilterType.from_string json["type"].as_s + _value = json["value"] + value = _value.as_s? || _value.as_i32? || _value.as_i64? || + _value.as_f32? || nil + self.new key, value, type + end +end + +struct Subscription + include JSON::Serializable + + property id : String + property plugin_id : String + property name : String + property created_at : Int64 + property last_checked : Int64 + property filters = [] of Filter + + def initialize(@plugin_id, @name) + @id = UUID.random.to_s + @created_at = Time.utc.to_unix + @last_checked = Time.utc.to_unix + end +end + +struct SubscriptionList + @dir : String + @path : String + + getter ary = [] of Subscription + + forward_missing_to @ary + + def initialize(@dir) + @path = Path[@dir, "subscriptions.json"] + if File.exists? @path + @ary = Array(Subscription).from_json File.read @path + end + end + + def save + File.write @path, @ary.to_json + end +end