repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/hooks.rb
lib/tmuxinator/hooks.rb
# frozen_string_literal: true module Tmuxinator module Hooks module_function def commands_from(project, hook_name) hook_config = project.yaml[hook_name] if hook_config.is_a?(Array) hook_config.join("; ") else hook_config end end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/window.rb
lib/tmuxinator/window.rb
# frozen_string_literal: true module Tmuxinator class Window include Tmuxinator::Util attr_reader :commands, :index, :name, :project def initialize(window_yaml, index, project) first_key = window_yaml.keys.first @name = first_key.to_s.shellescape unless first_key.nil? @yaml = window_yaml.values.first @project = project @index = index @commands = build_commands(tmux_window_command_prefix, @yaml) end def panes build_panes(yaml["panes"]) || [] end def _hashed? @yaml.is_a?(Hash) end def yaml _hashed? ? @yaml : {} end def layout yaml["layout"]&.shellescape end def synchronize yaml["synchronize"] || false end # The expanded, joined window root path # Relative paths are joined to the project root def root return _project_root unless _yaml_root File.expand_path(_yaml_root, _project_root).shellescape end def _yaml_root yaml["root"] end def _project_root project.root if project.root? end def build_panes(panes_yml) return if panes_yml.nil? Array(panes_yml).map.with_index do |pane_yml, index| commands, title = case pane_yml when Hash [pane_yml.values.first, pane_yml.keys.first] when Array [pane_yml, nil] else [pane_yml, nil] end Tmuxinator::Pane.new(index, project, self, *commands, title: title) end.flatten end def build_commands(_prefix, command_yml) if command_yml.is_a?(Array) command_yml.map do |command| "#{tmux_window_command_prefix} #{command.shellescape} C-m" if command end.compact elsif command_yml.is_a?(String) && !command_yml.empty? ["#{tmux_window_command_prefix} #{command_yml.shellescape} C-m"] else [] end end def pre _pre = yaml["pre"] if _pre.is_a?(Array) _pre.join(" && ") elsif _pre.is_a?(String) _pre end end def root? !root.nil? end def panes? panes.any? end def tmux_window_target "#{project.name}:#{index + project.base_index}" end def tmux_pre_window_command return unless project.pre_window "#{project.tmux} send-keys -t #{tmux_window_target} #{project.pre_window.shellescape} C-m" end def tmux_window_command_prefix "#{project.tmux} send-keys -t #{project.name}:#{index + project.base_index}" end def tmux_window_name_option name ? "-n #{name}" : "" end def tmux_new_window_command path = root? ? "#{Tmuxinator::Config.default_path_option} #{root}" : nil "#{project.tmux} new-window #{path} -k -t #{tmux_window_target} #{tmux_window_name_option}" end def tmux_tiled_layout_command "#{project.tmux} select-layout -t #{tmux_window_target} tiled" end def tmux_synchronize_panes "#{project.tmux} set-window-option -t #{tmux_window_target} synchronize-panes on" end def tmux_layout_command "#{project.tmux} select-layout -t #{tmux_window_target} #{layout}" end def tmux_select_first_pane "#{project.tmux} select-pane -t #{tmux_window_target}.#{panes.first.index + project.pane_base_index}" end def synchronize_before? [true, "before"].include?(synchronize) end def synchronize_after? synchronize == "after" end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/deprecations.rb
lib/tmuxinator/deprecations.rb
# frozen_string_literal: true module Tmuxinator module Deprecations def rvm? yaml["rvm"] end def rbenv? yaml["rbenv"] end def pre_tab? yaml["pre_tab"] end def cli_args? yaml["cli_args"] end def pre? yaml["pre"] end def post? yaml["post"] end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/cli.rb
lib/tmuxinator/cli.rb
# frozen_string_literal: true require "open3" module Tmuxinator class Cli < Thor # By default, Thor returns exit(0) when an error occurs. # Please see: https://github.com/tmuxinator/tmuxinator/issues/192 def self.exit_on_failure? true end include Tmuxinator::Util COMMANDS = { commands: "Lists commands available in tmuxinator", completions: "Used for shell completion", copy: %w{ Copy an existing project to a new project and open it in your editor }.join(" "), debug: "Output the shell commands that are generated by tmuxinator", delete: "Deletes given project", doctor: "Look for problems in your configuration", edit: "Alias of new", help: "Shows help for a specific command", implode: "Deletes all tmuxinator projects", local: "Start a tmux session using ./.tmuxinator.y[a]ml", list: "Lists all tmuxinator projects", new: "Create a new project file and open it in your editor", open: "Alias of new", start: %w{ Start a tmux session using a project's name (with an optional [ALIAS] for project reuse) or a path to a project config file (via the -p flag) }.join(" "), stop: "Stop a tmux session using a project's tmuxinator config", stop_all: "Stop all tmux sessions which are using tmuxinator projects", version: "Display installed tmuxinator version", }.freeze # For future reference: due to how tmuxinator currently consumes # command-line arguments (see ::bootstrap, below), invocations of Thor's # base commands (i.e. 'help', etc) can be instead routed to #start (rather # than to ::start). In order to prevent this, the THOR_COMMANDS and # RESERVED_COMMANDS constants have been introduced. The former enumerates # any/all Thor commands we want to insure get passed through to Thor.start. # The latter is the superset of the Thor commands and any tmuxinator # commands, defined in COMMANDS, above. THOR_COMMANDS = %w[-v help].freeze RESERVED_COMMANDS = (COMMANDS.keys + THOR_COMMANDS).map(&:to_s).freeze package_name "tmuxinator" \ unless Gem::Version.create(Thor::VERSION) < Gem::Version.create("0.18") desc "commands", COMMANDS[:commands] def commands(shell = nil) out = if shell == "zsh" COMMANDS.map do |command, desc| "#{command}:#{desc}" end.join("\n") else COMMANDS.keys.join("\n") end say out end desc "completions [arg1 arg2]", COMMANDS[:completions] def completions(arg) if %w(start stop edit open copy delete).include?(arg) configs = Tmuxinator::Config.configs say configs.join("\n") end end desc "new [PROJECT] [SESSION]", COMMANDS[:new] map "open" => :new map "edit" => :new map "o" => :new map "e" => :new map "n" => :new method_option :local, type: :boolean, aliases: ["-l"], desc: "Create local project file at ./.tmuxinator.yml" method_option :help, type: :boolean, aliases: ["-h"], desc: "Display usage information" def new(name = nil, session = nil) if options[:help] || name.nil? invoke :help, ["new"] return end if session new_project_with_session(name, session) else new_project(name) end end no_commands do def new_project(name) project_file = find_project_file(name, local: options[:local]) Kernel.system("$EDITOR #{project_file}") || doctor end def new_project_with_session(name, session) if Tmuxinator::Config.version < 1.6 raise "Creating projects from sessions is unsupported\ for tmux version 1.5 or lower." end windows, _, s0 = Open3.capture3(<<-CMD) tmux list-windows -t #{session}\ -F "#W \#{window_layout} \#{window_active} \#{pane_current_path}" CMD panes, _, s1 = Open3.capture3(<<-CMD) tmux list-panes -s -t #{session} -F "#W \#{pane_current_path}" CMD tmux_options, _, s2 = Open3.capture3(<<-CMD) tmux show-options -t #{session} CMD project_root = tmux_options[/^default-path "(.+)"$/, 1] unless [s0, s1, s2].all?(&:success?) raise "Session '#{session}' doesn't exist." end panes = panes.each_line.map(&:split).group_by(&:first) windows = windows.each_line.map do |line| window_name, layout, active, path = line.split(" ") project_root ||= path if active.to_i == 1 [ window_name, layout, Array(panes[window_name]).map do |_, pane_path| "cd #{pane_path}" end ] end yaml = { "name" => name, "project_root" => project_root, "windows" => windows.map do |window_name, layout, window_panes| { window_name => { "layout" => layout, "panes" => window_panes } } end } path = config_path(name, local: options[:local]) File.open(path, "w") do |f| f.write(YAML.dump(yaml)) end end def find_project_file(name, local: false) path = config_path(name, local: local) if File.exist?(path) path else generate_project_file(name, path) end end def config_path(name, local: false) if local Tmuxinator::Config::LOCAL_DEFAULTS[0] else Tmuxinator::Config.default_project(name) end end def generate_project_file(name, path) config = Tmuxinator::Config.default_or_sample erb = Tmuxinator::Project.render_template(config, binding) File.open(path, "w") { |f| f.write(erb) } path end def create_project(project_options = {}) Tmuxinator::Config.validate(project_create_options(project_options)) rescue StandardError => e exit! e.message end def project_create_options(project_options) { args: project_options[:args], custom_name: project_options[:custom_name], force_attach: project_options[:attach] == true, force_detach: project_options[:attach] == false, name: project_options[:name], project_config: project_options[:project_config], append: project_options[:append], no_pre_window: project_options[:no_pre_window], } end def render_project(project) if project.deprecations.any? project.deprecations.each { |deprecation| say deprecation, :red } show_continuation_prompt end Kernel.exec(project.render) end def version_warning?(suppress_flag) !Tmuxinator::TmuxVersion.supported? && !suppress_flag end def show_version_warning say Tmuxinator::TmuxVersion::UNSUPPORTED_VERSION_MSG, :red show_continuation_prompt end def show_continuation_prompt say print "Press ENTER to continue." $stdin.getc end def kill_project(project) Kernel.exec(project.kill) end def start_params(name = nil, *args) # project-config takes precedence over a named project in the case that # both are provided. if options["project-config"] args.unshift name if name name = nil end { args: args, attach: options[:attach], custom_name: options[:name], name: name, project_config: options["project-config"], append: options["append"], no_pre_window: options["no-pre-window"], } end end desc "start [PROJECT] [ARGS]", COMMANDS[:start] map "s" => :start method_option :attach, type: :boolean, aliases: "-a", desc: "Attach to tmux session after creation." method_option :name, aliases: "-n", desc: "Give the session a different name" method_option "project-config", aliases: "-p", desc: "Path to project config file" method_option "suppress-tmux-version-warning", desc: "Don't show a warning for unsupported tmux versions" method_option :append, type: :boolean, desc: "Appends the project windows and panes in " \ "the current session" method_option "no-pre-window", type: :boolean, default: false, desc: "Skip pre_window commands" method_option :help, type: :boolean, aliases: "-h", desc: "Display usage information" def start(name = nil, *args) if options[:help] invoke :help, ["start"] return end params = start_params(name, *args) show_version_warning if version_warning?( options["suppress-tmux-version-warning"] ) project = create_project(params) render_project(project) end desc "stop [PROJECT] [ARGS]", COMMANDS[:stop] map "st" => :stop method_option "project-config", aliases: "-p", desc: "Path to project config file" method_option "suppress-tmux-version-warning", desc: "Don't show a warning for unsupported tmux versions" method_option :help, type: :boolean, aliases: "-h", desc: "Display usage information" def stop(name = nil) if options[:help] invoke :help, ["stop"] return end # project-config takes precedence over a named project in the case that # both are provided. if options["project-config"] name = nil end params = { name: name, project_config: options["project-config"] } show_version_warning if version_warning?( options["suppress-tmux-version-warning"] ) project = create_project(params) kill_project(project) end desc "stop-all", COMMANDS[:stop_all] method_option :noconfirm, type: :boolean, default: false, aliases: "-y", desc: "Skip confirmation" def stop_all # We only need to stop active projects configs = Tmuxinator::Config.configs(active: true) unless options[:noconfirm] say "Stop all active projects:\n\n", :yellow say configs.join("\n") say "\n" return unless yes?("Are you sure? (n/y)") end Project.stop_all end desc "local", COMMANDS[:local] map "." => :local method_option "suppress-tmux-version-warning", desc: "Don't show a warning for unsupported tmux versions" def local show_version_warning if version_warning?( options["suppress-tmux-version-warning"] ) render_project(create_project(attach: options[:attach])) end desc "debug [PROJECT] [ARGS]", COMMANDS[:debug] method_option :attach, type: :boolean, aliases: "-a", desc: "Attach to tmux session after creation." method_option :name, aliases: "-n", desc: "Give the session a different name" method_option "project-config", aliases: "-p", desc: "Path to project config file" method_option :append, type: :boolean, desc: "Appends the project windows and panes in " \ "the current session" method_option "no-pre-window", type: :boolean, default: false, desc: "Skip pre_window commands" method_option :help, type: :boolean, aliases: "-h", desc: "Display usage information" def debug(name = nil, *args) if options[:help] invoke :help, ["debug"] return end params = start_params(name, *args) project = create_project(params) say project.render end desc "copy [EXISTING] [NEW]", COMMANDS[:copy] map "c" => :copy map "cp" => :copy method_option :help, type: :boolean, aliases: "-h", desc: "Display usage information" def copy(existing = nil, new = nil) if options[:help] || existing.nil? || new.nil? invoke :help, ["copy"] return end existing_config_path = Tmuxinator::Config.project(existing) new_config_path = Tmuxinator::Config.project(new) exit!("Project #{existing} doesn't exist!") \ unless Tmuxinator::Config.exist?(name: existing) new_exists = Tmuxinator::Config.exist?(name: new) question = "#{new} already exists, would you like to overwrite it?" if !new_exists || yes?(question, :red) say "Overwriting #{new}" if Tmuxinator::Config.exist?(name: new) FileUtils.copy_file(existing_config_path, new_config_path) end Kernel.system("$EDITOR #{new_config_path}") end desc "delete [PROJECT1] [PROJECT2] ...", COMMANDS[:delete] map "d" => :delete map "rm" => :delete method_option :help, type: :boolean, aliases: "-h", desc: "Display usage information" def delete(*projects) if options[:help] || projects.empty? invoke :help, ["delete"] return end delete_projects(*projects) end no_commands do def delete_projects(*projects) projects.each do |project| if Tmuxinator::Config.exist?(name: project) config = Tmuxinator::Config.project(project) if yes?("Are you sure you want to delete #{project}?(y/n)", :red) FileUtils.rm(config) say "Deleted #{project}" end else say "#{project} does not exist!" end end end end desc "implode", COMMANDS[:implode] map "i" => :implode def implode if yes?("Are you sure you want to delete all tmuxinator configs?", :red) Tmuxinator::Config.directories.each do |directory| FileUtils.remove_dir(directory) end say "Deleted all tmuxinator projects." end end desc "list", COMMANDS[:list] map "l" => :list map "ls" => :list method_option :newline, type: :boolean, aliases: ["-n"], desc: "Force output to be one entry per line." method_option :active, type: :boolean, aliases: ["-a"], desc: "Filter output by active project sessions." method_option :help, type: :boolean, aliases: ["-h"], desc: "Display usage information" def list if options[:help] invoke :help, ["list"] return end say "tmuxinator projects:" configs = Tmuxinator::Config.configs(active: options[:active]) if options[:newline] say configs.join("\n") else print_in_columns configs end end desc "version", COMMANDS[:version] map "-v" => :version def version say "tmuxinator #{Tmuxinator::VERSION}" end desc "doctor", COMMANDS[:doctor] def doctor say "Checking if tmux is installed ==> " yes_no Tmuxinator::Doctor.installed? say "Checking if $EDITOR is set ==> " yes_no Tmuxinator::Doctor.editor? say "Checking if $SHELL is set ==> " yes_no Tmuxinator::Doctor.shell? end # This method was defined as something of a workaround... Previously # the conditional contained within was in the executable (i.e. # bin/tmuxinator). It has been moved here so as to be testable. A couple # of notes: # - ::start (defined in Thor::Base) expects the first argument to be an # array or ARGV, not a varargs. Perhaps ::bootstrap should as well? # - ::start has a different purpose from #start and hence a different # signature def self.bootstrap(args = []) name = args[0] || nil if args.empty? && Tmuxinator::Config.local? Tmuxinator::Cli.new.local elsif name && !Tmuxinator::Cli::RESERVED_COMMANDS.include?(name) && Tmuxinator::Config.exist?(name: name) Tmuxinator::Cli.start([:start, *args]) else Tmuxinator::Cli.start(args) end end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/config.rb
lib/tmuxinator/config.rb
# frozen_string_literal: true module Tmuxinator class Config LOCAL_DEFAULTS = ["./.tmuxinator.yml", "./.tmuxinator.yaml"].freeze NO_LOCAL_FILE_MSG = "Project file at ./.tmuxinator.yml doesn't exist." NO_PROJECT_FOUND_MSG = "Project could not be found." TMUX_MASTER_VERSION = Float::INFINITY class << self # The directory (created if needed) in which to store new projects def directory return environment if environment? return xdg if xdg? return home if home? # No project directory specified or existent, default to XDG: FileUtils::mkdir_p(xdg) xdg end def home "#{ENV['HOME']}/.tmuxinator" end def home? File.directory?(home) end # ~/.config/tmuxinator unless $XDG_CONFIG_HOME has been configured to use # a custom value. (e.g. if $XDG_CONFIG_HOME is set to ~/my-config, the # return value will be ~/my-config/tmuxinator) def xdg xdg_config_directory = ENV.fetch("XDG_CONFIG_HOME", "~/.config") config_home = File.expand_path(xdg_config_directory) File.join(config_home, "tmuxinator") end def xdg? File.directory?(xdg) end # $TMUXINATOR_CONFIG (and create directory) or "". def environment environment = ENV["TMUXINATOR_CONFIG"] return "" if environment.to_s.empty? # variable is unset (nil) or blank FileUtils::mkdir_p(environment) unless File.directory?(environment) environment end def environment? File.directory?(environment) end def default_or_sample default? ? default : sample end def sample asset_path "sample.yml" end def default "#{directory}/default.yml" end def default? exist?(name: "default") end def version if Tmuxinator::Doctor.installed? tmux_version = `tmux -V`.split(" ")[1] if tmux_version == "master" TMUX_MASTER_VERSION else tmux_version.to_s[/\d+(?:\.\d+)?/, 0].to_f end end end def default_path_option version && version < 1.8 ? "default-path" : "-c" end def exist?(name: nil, path: nil) return File.exist?(path) if path return File.exist?(project(name)) if name false end def local? local_project end # Pathname of given project searching only global directories def global_project(name) project_in(environment, name) || project_in(xdg, name) || project_in(home, name) end def local_project LOCAL_DEFAULTS.detect { |f| File.exist?(f) } end def default_project(name) "#{directory}/#{name}.yml" end # Pathname of the given project def project(name) global_project(name) || local_project || default_project(name) end def template asset_path "template.erb" end def stop_template asset_path "template-stop.erb" end def wemux_template asset_path "wemux_template.erb" end # List of all active tmux sessions def active_sessions `tmux list-sessions -F "#S"`.split("\n") end # Sorted list of all project file basenames, including duplicates. # # @param active filter configs by active project sessions # @return [Array<String>] list of project names def configs(active: nil) configs = config_file_basenames if active == true configs &= active_sessions elsif active == false configs -= active_sessions end configs end # List the names of all config files relative to the config directory. # # If sub-folders are used, those are part of the name too. # # Example: # $CONFIG_DIR/project.yml -> project # $CONFIG_DIR/sub/project.yml -> sub/project # $HOME_CONFIG_DIR/project.yml -> project # # @return [Array<String] a list of config file names def config_file_basenames directories.flat_map do |directory| Dir["#{directory}/**/*.yml"].map do |path| path.gsub("#{directory}/", "").gsub(".yml", "") end end.sort end # Existent directories which may contain project files # Listed in search order # Used by `implode` and `list` commands def directories if environment? [environment] else [xdg, home].select { |d| File.directory? d } end end def valid_project_config?(project_config) return false unless project_config unless exist?(path: project_config) raise "Project config (#{project_config}) doesn't exist." end true end def valid_local_project?(name) return false if name raise NO_LOCAL_FILE_MSG unless local? true end def valid_standard_project?(name) return false unless name raise "Project #{name} doesn't exist." unless exist?(name: name) true end def validate(options = {}) name = options[:name] options[:force_attach] ||= false options[:force_detach] ||= false project_config = options.fetch(:project_config, false) project_file = if valid_project_config?(project_config) project_config elsif valid_local_project?(name) local_project elsif valid_standard_project?(name) project(name) else # This branch should never be reached, # but just in case ... raise NO_PROJECT_FOUND_MSG end Tmuxinator::Project.load(project_file, options).validate! end # Deprecated methods: ignore the 1st, use the 2nd alias :root :directory alias :project_in_root :global_project alias :project_in_local :local_project private def asset_path(asset) "#{File.dirname(__FILE__)}/assets/#{asset}" end # The first pathname of the project named 'name' found while # recursively searching 'directory' def project_in(directory, name) return nil if String(directory).empty? projects = Dir.glob("#{directory}/**/*.{yml,yaml}").sort projects.detect { |project| File.basename(project, ".*") == name } end end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/wemux_support.rb
lib/tmuxinator/wemux_support.rb
# frozen_string_literal: true module Tmuxinator module WemuxSupport def render Tmuxinator::Project.render_template( Tmuxinator::Config.wemux_template, binding ) end %i(name tmux).each do |m| define_method(m) { "wemux" } end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/pane.rb
lib/tmuxinator/pane.rb
# frozen_string_literal: true module Tmuxinator class Pane attr_reader :commands, :project, :index, :tab, :title def initialize(index, project, tab, *commands, title: nil) @commands = commands @index = index @project = project @tab = tab @title = title.to_s.shellescape unless title.nil? end def tmux_window_and_pane_target "#{project.name}:#{window_index}.#{pane_index}" end def tmux_pre_command _send_target(tab.pre.shellescape) if tab.pre end def tmux_pre_window_command _send_target(project.pre_window.shellescape) if project.pre_window end def tmux_main_command(command) if command _send_target(command.shellescape) else "" end end def tmux_set_title unless title.nil? _set_title(title) end end def name project.name end def window_index tab.index + project.base_index end def pane_index index + tab.project.pane_base_index end def tmux_split_command path = if tab.root? "#{Tmuxinator::Config.default_path_option} #{tab.root}" end "#{project.tmux} splitw #{path} -t #{tab.tmux_window_target}" end def last? index == tab.panes.length - 1 end private def _send_target(keys) _send_keys(tmux_window_and_pane_target, keys) end def _send_keys(target, keys) "#{project.tmux} send-keys -t #{target} #{keys} C-m" end def _set_title(title) target = tmux_window_and_pane_target "#{project.tmux} select-pane -t #{target} -T #{title}" end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/util.rb
lib/tmuxinator/util.rb
# frozen_string_literal: true module Tmuxinator module Util include Thor::Actions def exit!(msg) puts msg Kernel.exit(1) end def yes_no(condition) condition ? say("Yes", :green) : say("No", :red) end def current_session_name `[[ -n "${TMUX+set}" ]] && tmux display-message -p "#S"`.strip end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/tmux_version.rb
lib/tmuxinator/tmux_version.rb
# frozen_string_literal: true module Tmuxinator module TmuxVersion SUPPORTED_TMUX_VERSIONS = [ "3.6a", 3.6, "3.5a", 3.5, 3.4, "3.3a", 3.3, "3.2a", 3.2, "3.1c", "3.1b", "3.1a", 3.1, "3.0a", 3.0, "2.9a", 2.9, 2.8, 2.7, 2.6, 2.5, 2.4, 2.3, 2.2, 2.1, 2.0, 1.9, 1.8, 1.7, 1.6, 1.5, ].freeze UNSUPPORTED_VERSION_MSG = <<-MSG WARNING: You are running tmuxinator with an unsupported version of tmux. Please consider using a supported version: (#{SUPPORTED_TMUX_VERSIONS.join(', ')}) MSG def self.supported?(version = Tmuxinator::Config.version) SUPPORTED_TMUX_VERSIONS.include?(version) end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
tmuxinator/tmuxinator
https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/hooks/project.rb
lib/tmuxinator/hooks/project.rb
# frozen_string_literal: true module Tmuxinator module Hooks module Project module_function # Commands specified in this hook run when "tmuxinator start project" # command is issued def hook_on_project_start # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_start" end # Commands specified in this hook run when "tmuxinator start project" # command is issued and there is no tmux session available named "project" def hook_on_project_first_start # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_first_start" end # Commands specified in this hook run when "tmuxinator start project" # command is issued and there is no tmux session available named "project" def hook_on_project_restart # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_restart" end # Commands specified in this hook run when you exit from a project ( aka # detach from a tmux session ) def hook_on_project_exit # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_exit" end # Command specified in this hook run when "tmuxinator stop project" # command is issued def hook_on_project_stop # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_stop" end end end end
ruby
MIT
8f8a4687c229b4d0ed725451057b32f14b476ebd
2026-01-04T15:37:31.204874Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/jobs/agent_reemit_job.rb
app/jobs/agent_reemit_job.rb
class AgentReemitJob < ActiveJob::Base # Given an Agent, re-emit all of agent's events up to (and including) `most_recent_event_id` def perform(agent, most_recent_event_id, delete_old_events = false) # `find_each` orders by PK, so events get re-created in the same order agent.events.where("id <= ?", most_recent_event_id).find_each do |event| event.reemit! event.destroy if delete_old_events end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/jobs/agent_propagate_job.rb
app/jobs/agent_propagate_job.rb
class AgentPropagateJob < ActiveJob::Base queue_as :propagation def perform Agent.receive! end def self.can_enqueue? case queue_adapter.class.name # not using class since it would load adapter dependent gems when 'ActiveJob::QueueAdapters::DelayedJobAdapter' return Delayed::Job.where(failed_at: nil, queue: 'propagation').count == 0 when 'ActiveJob::QueueAdapters::ResqueAdapter' return Resque.size('propagation') == 0 && Resque.workers.select { |w| w.job && w.job['queue'] && w.job['queue']['propagation'] }.count == 0 else raise NotImplementedError, "unsupported adapter: #{queue_adapter}" end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/jobs/agent_cleanup_expired_job.rb
app/jobs/agent_cleanup_expired_job.rb
class AgentCleanupExpiredJob < ActiveJob::Base queue_as :default def perform Event.cleanup_expired! end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/jobs/agent_run_schedule_job.rb
app/jobs/agent_run_schedule_job.rb
class AgentRunScheduleJob < ActiveJob::Base queue_as :default def perform(time) Agent.run_schedule(time) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/jobs/agent_check_job.rb
app/jobs/agent_check_job.rb
class AgentCheckJob < ActiveJob::Base # Given an Agent id, load the Agent, call #check on it, and then save it with an updated `last_check_at` timestamp. def perform(agent_id) agent = Agent.find(agent_id) begin return if agent.unavailable? agent.check agent.last_check_at = Time.now agent.save! rescue => e agent.error "Exception during check. #{e.message}: #{e.backtrace.join("\n")}" raise end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/jobs/agent_receive_job.rb
app/jobs/agent_receive_job.rb
class AgentReceiveJob < ActiveJob::Base # Given an Agent id and an array of Event ids, load the Agent, call #receive on it with the Event objects, and then # save it with an updated `last_receive_at` timestamp. def perform(agent_id, event_ids) agent = Agent.find(agent_id) begin return if agent.unavailable? agent.receive(Event.where(:id => event_ids).order(:id)) agent.last_receive_at = Time.now agent.save! rescue => e agent.error "Exception during receive. #{e.message}: #{e.backtrace.join("\n")}" raise end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/markdown_class_attributes.rb
app/concerns/markdown_class_attributes.rb
module MarkdownClassAttributes extend ActiveSupport::Concern module ClassMethods def markdown_class_attributes(*attributes) attributes.each do |attribute| class_eval <<-RUBY def html_#{attribute} Kramdown::Document.new(#{attribute}, auto_ids: false).to_html.html_safe end def #{attribute} if self.class.#{attribute}.is_a?(Proc) Utils.unindent(self.instance_eval(&self.class.#{attribute}) || "No #{attribute} has been set.") else Utils.unindent(self.class.#{attribute} || "No #{attribute} has been set.") end end def self.#{attribute}(value = nil, &block) if block @#{attribute} = block elsif value @#{attribute} = value end @#{attribute} end RUBY end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/assignable_types.rb
app/concerns/assignable_types.rb
module AssignableTypes extend ActiveSupport::Concern included do validate :validate_type end def short_type @short_type ||= type.split("::").pop end def validate_type errors.add(:type, "cannot be changed once an instance has been created") if type_changed? && !new_record? errors.add(:type, "is not a valid type") unless self.class.valid_type?(type) end module ClassMethods def load_types_in(module_name, my_name = module_name.singularize) const_set(:MODULE_NAME, module_name) const_set(:BASE_CLASS_NAME, my_name) const_set(:TYPES, Dir[Rails.root.join("app", "models", module_name.underscore, "*.rb")].map { |path| module_name + "::" + File.basename(path, ".rb").camelize }) end def types const_get(:TYPES).map(&:constantize) end def valid_type?(type) const_get(:TYPES).include?(type) end def build_for_type(type, user, attributes = {}) attributes.delete(:type) if valid_type?(type) type.constantize.new(attributes).tap do |instance| instance.user = user if instance.respond_to?(:user=) end else const_get(:BASE_CLASS_NAME).constantize.new(attributes).tap do |instance| instance.type = type instance.user = user if instance.respond_to?(:user=) end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/oauthable.rb
app/concerns/oauthable.rb
module Oauthable extend ActiveSupport::Concern included do |base| @valid_oauth_providers = :all validate :validate_service end def oauthable? true end def validate_service if !service errors.add(:service, :blank) end end def valid_services_for(user) if valid_oauth_providers == :all user.available_services else user.available_services.where(provider: valid_oauth_providers) end end def valid_oauth_providers self.class.valid_oauth_providers end module ClassMethods def valid_oauth_providers(*providers) return @valid_oauth_providers if providers == [] @valid_oauth_providers = providers end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/liquid_interpolatable.rb
app/concerns/liquid_interpolatable.rb
# :markup: markdown module LiquidInterpolatable extend ActiveSupport::Concern included do validate :validate_interpolation end def valid?(context = nil) super rescue Liquid::Error errors.empty? end def validate_interpolation interpolated rescue Liquid::ZeroDivisionError => e # Ignore error (likely due to possibly missing variables on "divided_by") rescue Liquid::Error => e errors.add(:options, "has an error with Liquid templating: #{e.message}") rescue StandardError # Calling `interpolated` without an incoming may naturally fail # with various errors when an agent expects one. end # Return the current interpolation context. Use this in your Agent # class to manipulate interpolation context for user. # # For example, to provide local variables: # # # Create a new scope to define variables in: # interpolation_context.stack { # interpolation_context['_something_'] = 42 # # And user can say "{{_something_}}" in their options. # value = interpolated['some_key'] # } # def interpolation_context @interpolation_context ||= Context.new(self) end # Take the given object as "self" in the current interpolation # context while running a given block. # # The most typical use case for this is to evaluate options for each # received event like this: # # def receive(incoming_events) # incoming_events.each do |event| # interpolate_with(event) do # # Handle each event based on "interpolated" options. # end # end # end def interpolate_with(self_object) case self_object when nil yield else context = interpolation_context begin context.environments.unshift(self_object.to_liquid) yield ensure context.environments.shift end end end def interpolate_with_each(array) array.each do |object| interpolate_with(object) do self.current_event = object yield object end end end def interpolate_options(options, self_object = nil) interpolate_with(self_object) do case options when String interpolate_string(options) when ActiveSupport::HashWithIndifferentAccess, Hash options.each_with_object(ActiveSupport::HashWithIndifferentAccess.new) { |(key, value), memo| memo[key] = interpolate_options(value) } when Array options.map { |value| interpolate_options(value) } else options end end end def interpolated(self_object = nil) interpolate_with(self_object) do (@interpolated_cache ||= {})[[options, interpolation_context].hash] ||= interpolate_options(options) end end def interpolate_string(string, self_object = nil) interpolate_with(self_object) do catch :as_object do Liquid::Template.parse(string).render!(interpolation_context) end end end class Context < Liquid::Context def initialize(agent) outer_scope = { '_agent_' => agent } Agents::KeyValueStoreAgent.merge(agent.controllers).find_each do |kvs| outer_scope[kvs.options[:variable]] = kvs.memory end super({}, outer_scope, { agent: }, true) end def hash [@environments, @scopes, @registers].hash end def eql?(other) other.environments == @environments && other.scopes == @scopes && other.registers == @registers end end require 'uri' module Filters # Percent encoding for URI conforming to RFC 3986. # Ref: http://tools.ietf.org/html/rfc3986#page-12 def uri_escape(string) CGI.escape(string) rescue StandardError string end # Parse an input into a URI object, optionally resolving it # against a base URI if given. # # A URI object will have the following properties: scheme, # userinfo, host, port, registry, path, opaque, query, and # fragment. def to_uri(uri, base_uri = nil) case base_uri when nil, '' Utils.normalize_uri(uri.to_s) else Utils.normalize_uri(base_uri) + Utils.normalize_uri(uri.to_s) end rescue URI::Error nil end # Get the destination URL of a given URL by recursively following # redirects, up to 5 times in a row. If a given string is not a # valid absolute HTTP URL or in case of too many redirects, the # original string is returned. If any network/protocol error # occurs while following redirects, the last URL followed is # returned. def uri_expand(url, limit = 5) case url when URI uri = url else url = url.to_s begin uri = Utils.normalize_uri(url) rescue URI::Error return url end end http = Faraday.new do |builder| builder.adapter :net_http # The follow_redirects middleware does not handle non-HTTP URLs. end limit.times do begin case uri when URI::HTTP return uri.to_s unless uri.host response = http.head(uri) case response.status when 301, 302, 303, 307 if location = response['location'] uri += Utils.normalize_uri(location) next end end end rescue URI::Error, Faraday::Error, SystemCallError => e logger.error "#{e.class} in #{__method__}(#{url.inspect}) [uri=#{uri.to_s.inspect}]: #{e.message}:\n#{e.backtrace.join("\n")}" end return uri.to_s end logger.error "Too many rediretions in #{__method__}(#{url.inspect}) [uri=#{uri.to_s.inspect}]" url end # Rebase URIs contained in attributes in a given HTML fragment def rebase_hrefs(input, base_uri) Utils.rebase_hrefs(input, base_uri) rescue StandardError input end # Unescape (basic) HTML entities in a string # # This currently decodes the following entities only: "&apos;", # "&quot;", "&lt;", "&gt;", "&amp;", "&#dd;" and "&#xhh;". def unescape(input) CGI.unescapeHTML(input) rescue StandardError input end # Escape a string for use in XPath expression def to_xpath(string) subs = string.to_s.scan(/\G(?:\A\z|[^"]+|[^']+)/).map { |x| case x when /"/ %('#{x}') else %("#{x}") end } if subs.size == 1 subs.first else 'concat(' << subs.join(', ') << ')' end end def regex_extract(input, regex, index = 0) input.to_s[Regexp.new(regex), index] rescue IndexError nil end def regex_replace(input, regex, replacement = nil) input.to_s.gsub(Regexp.new(regex), unescape_replacement(replacement.to_s)) end def regex_replace_first(input, regex, replacement = nil) input.to_s.sub(Regexp.new(regex), unescape_replacement(replacement.to_s)) end # Serializes data as JSON def json(input) JSON.dump(input) end def fromjson(input) JSON.parse(input.to_s) rescue StandardError nil end def hex_encode(input) input.to_s.unpack1('H*') end def hex_decode(input) [input.to_s].pack('H*') end def md5(input) Digest::MD5.hexdigest(input.to_s) end def sha1(input) Digest::SHA1.hexdigest(input.to_s) end def sha256(input) Digest::SHA256.hexdigest(input.to_s) end def hmac_sha1(input, key) OpenSSL::HMAC.hexdigest('sha1', key.to_s, input.to_s) end def hmac_sha256(input, key) OpenSSL::HMAC.hexdigest('sha256', key.to_s, input.to_s) end # Returns a Ruby object # # It can be used as a JSONPath replacement for Agents that only support Liquid: # # Event: {"something": {"nested": {"data": 1}}} # Liquid: {{something.nested | as_object}} # Returns: {"data": 1} # # Splitting up a string with Liquid filters and return the Array: # # Event: {"data": "A,B,C"}} # Liquid: {{data | split: ',' | as_object}} # Returns: ['A', 'B', 'C'] # # as_object ALWAYS has be the last filter in a Liquid expression! def as_object(object) throw :as_object, object.as_json end # Group an array of items by a property # # Example usage: # # {% assign posts_by_author = site.posts | group_by: "author" %} # {% for author in posts_by_author %} # <dt>{{author.name}}</dt> # {% for post in author.items %} # <dd><a href="{{post.url}}">{{post.title}}</a></dd> # {% endfor %} # {% endfor %} def group_by(input, property) if input.respond_to?(:group_by) input.group_by { |item| item[property] }.map do |value, items| { 'name' => value, 'items' => items } end else input end end private def logger @@logger ||= if defined?(Rails) Rails.logger else require 'logger' Logger.new(STDERR) end end BACKSLASH = "\\".freeze UNESCAPE = { "a" => "\a", "b" => "\b", "e" => "\e", "f" => "\f", "n" => "\n", "r" => "\r", "s" => " ", "t" => "\t", "v" => "\v", } # Unescape a replacement text for use in the second argument of # gsub/sub. The following escape sequences are recognized: # # - "\\" (backslash itself) # - "\a" (alert) # - "\b" (backspace) # - "\e" (escape) # - "\f" (form feed) # - "\n" (new line) # - "\r" (carriage return) # - "\s" (space) # - "\t" (horizontal tab) # - "\u{XXXX}" (unicode codepoint) # - "\v" (vertical tab) # - "\xXX" (hexadecimal character) # - "\1".."\9" (numbered capture groups) # - "\+" (last capture group) # - "\k<name>" (named capture group) # - "\&" or "\0" (complete matched text) # - "\`" (string before match) # - "\'" (string after match) # # Octal escape sequences are deliberately unsupported to avoid # conflict with numbered capture groups. Rather obscure Emacs # style character codes ("\C-x", "\M-\C-x" etc.) are also omitted # from this implementation. def unescape_replacement(s) s.gsub(/\\(?:([\d+&`'\\]|k<\w+>)|u\{([[:xdigit:]]+)\}|x([[:xdigit:]]{2})|(.))/) { if c = $1 BACKSLASH + c elsif c = ($2 && [$2.to_i(16)].pack('U')) || ($3 && [$3.to_i(16)].pack('C')) if c == BACKSLASH BACKSLASH + c else c end else UNESCAPE[$4] || $4 end } end end Liquid::Environment.default.register_filter(LiquidInterpolatable::Filters) module Tags class Credential < Liquid::Tag def initialize(tag_name, name, tokens) super @credential_name = name.strip end def render(context) context.registers[:agent].credential(@credential_name) || "" end end class LineBreak < Liquid::Tag def render(context) "\n" end end class Uuidv4 < Liquid::Tag def render(context) SecureRandom.uuid end end end Liquid::Environment.default.register_tag('credential', LiquidInterpolatable::Tags::Credential) Liquid::Environment.default.register_tag('line_break', LiquidInterpolatable::Tags::LineBreak) Liquid::Environment.default.register_tag('uuidv4', LiquidInterpolatable::Tags::Uuidv4) module Blocks # Replace every occurrence of a given regex pattern in the first # "in" block with the result of the "with" block in which the # variable `match` is set for each iteration, which can be used as # follows: # # - `match[0]` or just `match`: the whole matching string # - `match[1]`..`match[n]`: strings matching the numbered capture groups # - `match.size`: total number of the elements above (n+1) # - `match.names`: array of names of named capture groups # - `match[name]`..: strings matching the named capture groups # - `match.pre_match`: string preceding the match # - `match.post_match`: string following the match # - `match.***`: equivalent to `match['***']` unless it conflicts with the existing methods above # # If named captures (`(?<name>...)`) are used in the pattern, they # are also made accessible as variables. Note that if numbered # captures are used mixed with named captures, you could get # unexpected results. # # Example usage: # # {% regex_replace "\w+" in %}Use me like this.{% with %}{{ match | capitalize }}{% endregex_replace %} # {% assign fullname = "Doe, John A." %} # {% regex_replace_first "\A(?<name1>.+), (?<name2>.+)\z" in %}{{ fullname }}{% with %}{{ name2 }} {{ name1 }}{% endregex_replace_first %} # # Use Me Like This. # # John A. Doe # class RegexReplace < Liquid::Block Syntax = /\A\s*(#{Liquid::QuotedFragment})(?:\s+in)?\s*\z/ def initialize(tag_name, markup, tokens) super case markup when Syntax @regexp = $1 else raise Liquid::SyntaxError, 'Syntax Error in regex_replace tag - Valid syntax: regex_replace pattern in' end @in_block = Liquid::BlockBody.new @with_block = nil end def parse(tokens) if more = parse_body(@in_block, tokens) @with_block = Liquid::BlockBody.new parse_body(@with_block, tokens) end end def nodelist if @with_block [@in_block, @with_block] else [@in_block] end end def unknown_tag(tag, markup, tokens) return super unless tag == 'with'.freeze @with_block = Liquid::BlockBody.new end def render(context) begin regexp = Regexp.new(context[@regexp].to_s) rescue ::SyntaxError => e raise Liquid::SyntaxError, "Syntax Error in regex_replace tag - #{e.message}" end subject = @in_block.render(context) subject.send(first? ? :sub : :gsub, regexp) { next '' unless @with_block m = Regexp.last_match context.stack do m.names.each do |name| context[name] = m[name] end context['match'.freeze] = m @with_block.render(context) end } end def first? @tag_name.end_with?('_first'.freeze) end end end Liquid::Environment.default.register_tag('regex_replace', LiquidInterpolatable::Blocks::RegexReplace) Liquid::Environment.default.register_tag('regex_replace_first', LiquidInterpolatable::Blocks::RegexReplace) end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/json_serialized_field.rb
app/concerns/json_serialized_field.rb
require 'json_with_indifferent_access' module JsonSerializedField extend ActiveSupport::Concern module ClassMethods def json_serialize(*fields) fields.each do |field| class_eval <<-CODE serialize :#{field}, JsonWithIndifferentAccess validate :#{field}_has_no_errors def #{field}=(input) @#{field}_assignment_error = false case input when String if input.strip.length == 0 self[:#{field}] = ActiveSupport::HashWithIndifferentAccess.new else json = JSON.parse(input) rescue nil if json self[:#{field}] = ActiveSupport::HashWithIndifferentAccess.new(json) else @#{field}_assignment_error = "was assigned invalid JSON" end end when Hash self[:#{field}] = ActiveSupport::HashWithIndifferentAccess.new(input) else @#{field}_assignment_error = "cannot be set to an instance of \#{input.class}" end end def #{field}_has_no_errors errors.add(:#{field}, @#{field}_assignment_error) if @#{field}_assignment_error end CODE end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/has_guid.rb
app/concerns/has_guid.rb
module HasGuid extend ActiveSupport::Concern included do before_save :make_guid end protected def make_guid self.guid = SecureRandom.hex unless guid.present? end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/agent_controller_concern.rb
app/concerns/agent_controller_concern.rb
module AgentControllerConcern extend ActiveSupport::Concern included do can_control_other_agents! validate :validate_control_action end def default_options { 'action' => 'run' } end def control_action interpolated['action'] end def validate_control_action case options['action'] when 'run' control_targets.each { |target| if target.cannot_be_scheduled? errors.add(:base, "#{target.name} cannot be scheduled") end } when 'configure' if !options['configure_options'].is_a?(Hash) || options['configure_options'].empty? errors.add(:base, "A non-empty hash must be specified in the 'configure_options' option when using the 'configure' action.") end when 'enable', 'disable' when nil errors.add(:base, "action must be specified") when /\{[%{]/ # Liquid template else errors.add(:base, 'invalid action') end end def control! control_targets.each do |target| interpolate_with('target' => target) do case action = control_action when 'run' case when target.cannot_be_scheduled? error "'#{target.name}' cannot run without an incoming event" when target.disabled? log "Agent run ignored for disabled Agent '#{target.name}'" else Agent.async_check(target.id) log "Agent run queued for '#{target.name}'" end when 'enable' case when target.disabled? if boolify(interpolated['drop_pending_events']) target.drop_pending_events = true end target.update!(disabled: false) log "Agent '#{target.name}' is enabled" else log "Agent '#{target.name}' is already enabled" end when 'disable' case when target.disabled? log "Agent '#{target.name}' is alread disabled" else target.update!(disabled: true) log "Agent '#{target.name}' is disabled" end when 'configure' target.update! options: target.options.deep_merge(interpolated['configure_options']) log "Agent '#{target.name}' is configured with #{interpolated['configure_options'].inspect}" when '' log 'No action is performed.' else error "Unsupported action '#{action}' ignored for '#{target.name}'" end rescue StandardError => e error "Failed to #{action} '#{target.name}': #{e.message}" end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/dry_runnable.rb
app/concerns/dry_runnable.rb
module DryRunnable extend ActiveSupport::Concern def dry_run!(event = nil) @dry_run = true log = StringIO.new @dry_run_started_at = Time.zone.now @dry_run_logger = Logger.new(log).tap { |logger| logger.formatter = proc { |severity, datetime, progname, message| elapsed_time = '%02d:%02d:%02d' % 2.times.inject([datetime - @dry_run_started_at]) { |(x, *xs)| [*x.divmod(60), *xs] } "[#{elapsed_time}] #{severity} -- #{progname}: #{message}\n" } } @dry_run_results = { events: [], } begin raise "#{short_type} does not support dry-run" unless can_dry_run? readonly! @dry_run_started_at = Time.zone.now @dry_run_logger.info('Dry Run started') if event raise "This agent cannot receive an event!" unless can_receive_events? receive([event]) else check end @dry_run_logger.info('Dry Run finished') rescue StandardError => e @dry_run_logger.info('Dry Run failed') error "Exception during dry-run. #{e.message}: #{e.backtrace.join("\n")}" end @dry_run_results.update( memory:, log: log.string, ) ensure @dry_run = false end def dry_run? !!@dry_run end included do prepend Wrapper end module Wrapper attr_accessor :results def logger return super unless dry_run? @dry_run_logger end def save(**options) return super unless dry_run? perform_validations(options) end def save!(**options) return super unless dry_run? save(**options) or raise_record_invalid end def log(message, options = {}) return super unless dry_run? sev = case options[:level] || 3 when 0..2 Logger::DEBUG when 3 Logger::INFO else Logger::ERROR end logger.log(sev, message) end def create_event(event) return super unless dry_run? if can_create_events? event = build_event(event) @dry_run_results[:events] << event.payload event else error "This Agent cannot create events!" end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/web_request_concern.rb
app/concerns/web_request_concern.rb
require 'faraday' module WebRequestConcern module DoNotEncoder def self.encode(params) params.map do |key, value| value.nil? ? "#{key}" : "#{key}=#{value}" end.join('&') end def self.decode(val) [val] end end class CharacterEncoding < Faraday::Middleware def initialize(app, options = {}) super(app) @force_encoding = options[:force_encoding] @default_encoding = options[:default_encoding] @unzip = options[:unzip] end def call(env) @app.call(env).on_complete do |env| body = env[:body] if @unzip == 'gzip' begin body.replace(ActiveSupport::Gzip.decompress(body)) rescue Zlib::GzipFile::Error => e log e.message end end case when @force_encoding encoding = @force_encoding when body.encoding == Encoding::ASCII_8BIT # Not all Faraday adapters support automatic charset # detection, so we do that. case env[:response_headers][:content_type] when /;\s*charset\s*=\s*([^()<>@,;:\\"\/\[\]?={}\s]+)/i encoding = begin Encoding.find($1) rescue StandardError @default_encoding end when /\A\s*(?:text\/[^\s;]+|application\/(?:[^\s;]+\+)?(?:xml|json))\s*(?:;|\z)/i encoding = @default_encoding else # Never try to transcode a binary content next end # Return body as binary if default_encoding is nil next if encoding.nil? end body.encode!(Encoding::UTF_8, encoding, invalid: :replace, undef: :replace) end end end Faraday::Response.register_middleware character_encoding: CharacterEncoding extend ActiveSupport::Concern def validate_web_request_options! if options['user_agent'].present? errors.add(:base, "user_agent must be a string") unless options['user_agent'].is_a?(String) end if options['proxy'].present? errors.add(:base, "proxy must be a string") unless options['proxy'].is_a?(String) end if options['disable_ssl_verification'].present? && boolify(options['disable_ssl_verification']).nil? errors.add(:base, "if provided, disable_ssl_verification must be true or false") end unless headers(options['headers']).is_a?(Hash) errors.add(:base, "if provided, headers must be a hash") end begin basic_auth_credentials(options['basic_auth']) rescue ArgumentError => e errors.add(:base, e.message) end if (encoding = options['force_encoding']).present? case encoding when String begin Encoding.find(encoding) rescue ArgumentError errors.add(:base, "Unknown encoding: #{encoding.inspect}") end else errors.add(:base, "force_encoding must be a string") end end end # The default encoding for a text content with no `charset` # specified in the Content-Type header. Override this and make it # return nil if you want to detect the encoding on your own. def default_encoding Encoding::UTF_8 end def parse_body? false end def faraday faraday_options = { ssl: { verify: !boolify(options['disable_ssl_verification']) } } @faraday ||= Faraday.new(faraday_options) { |builder| if parse_body? builder.response :json end builder.response :character_encoding, force_encoding: interpolated['force_encoding'].presence, default_encoding:, unzip: interpolated['unzip'].presence builder.headers = headers if headers.length > 0 builder.headers[:user_agent] = user_agent builder.proxy = interpolated['proxy'].presence unless boolify(interpolated['disable_redirect_follow']) require 'faraday/follow_redirects' builder.response :follow_redirects end builder.request :multipart builder.request :url_encoded if boolify(interpolated['disable_url_encoding']) builder.options.params_encoder = DoNotEncoder end builder.options.timeout = (Delayed::Worker.max_run_time.seconds - 2).to_i if userinfo = basic_auth_credentials builder.request :authorization, :basic, *userinfo end builder.request :gzip case backend = faraday_backend when :typhoeus require "faraday/#{backend}" builder.adapter backend, accept_encoding: nil when :httpclient, :em_http require "faraday/#{backend}" builder.adapter backend end } end def headers(value = interpolated['headers']) value.presence || {} end def basic_auth_credentials(value = interpolated['basic_auth']) case value when nil, '' return nil when Array return value if value.size == 2 when /:/ return value.split(/:/, 2) end raise ArgumentError.new("bad value for basic_auth: #{value.inspect}") end def faraday_backend ENV.fetch('FARADAY_HTTP_BACKEND') { case interpolated['backend'] in 'typhoeus' | 'net_http' | 'httpclient' | 'em_http' => backend backend else 'typhoeus' end }.to_sym end def user_agent interpolated['user_agent'].presence || self.class.default_user_agent end module ClassMethods def default_user_agent ENV.fetch('DEFAULT_HTTP_USER_AGENT', "Huginn - https://github.com/huginn/huginn") end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/form_configurable.rb
app/concerns/form_configurable.rb
module FormConfigurable extend ActiveSupport::Concern included do class_attribute :_form_configurable_fields self._form_configurable_fields = HashWithIndifferentAccess.new { |h, k| h[k] = [] } end delegate :form_configurable_attributes, to: :class delegate :form_configurable_fields, to: :class def is_form_configurable? true end def validate_option(method) if self.respond_to? "validate_#{method}".to_sym self.send("validate_#{method}".to_sym) else false end end def complete_option(method) if self.respond_to? "complete_#{method}".to_sym self.send("complete_#{method}".to_sym) end end module ClassMethods def form_configurable(name, *args) options = args.extract_options!.reverse_merge(roles: [], type: :string) if args.all?(Symbol) options.assert_valid_keys([:type, :roles, :values, :ace, :cache_response, :html_options]) end if options[:type] == :array && (options[:values].blank? || !options[:values].is_a?(Array)) raise ArgumentError.new('When using :array as :type you need to provide the :values as an Array') end if options[:roles].is_a?(Symbol) options[:roles] = [options[:roles]] end case options[:type] when :array options[:roles] << :completable class_eval <<-EOF, __FILE__, __LINE__ + 1 def complete_#{name} #{options[:values]}.map { |v| {text: v, id: v} } end EOF when :json class_eval <<-EOF, __FILE__, __LINE__ + 1 before_validation :decode_#{name}_json private def decode_#{name}_json case value = options[:#{name}] when String options[:#{name}] = begin JSON.parse(value) rescue StandardError value end end end EOF end _form_configurable_fields[name] = options end def form_configurable_fields self._form_configurable_fields end def form_configurable_attributes form_configurable_fields.keys end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/file_handling.rb
app/concerns/file_handling.rb
module FileHandling extend ActiveSupport::Concern def get_file_pointer(file) { file_pointer: { file: file, agent_id: id } } end def has_file_pointer?(event) event.payload['file_pointer'] && event.payload['file_pointer']['file'] && event.payload['file_pointer']['agent_id'] end def get_io(event) return nil unless has_file_pointer?(event) event.user.agents.find(event.payload['file_pointer']['agent_id']).get_io(event.payload['file_pointer']['file']) end def get_upload_io(event) Faraday::UploadIO.new(get_io(event), MIME::Types.type_for(File.basename(event.payload['file_pointer']['file'])).first.try(:content_type)) end def emitting_file_handling_agent_description @emitting_file_handling_agent_description ||= "This agent only emits a 'file pointer', not the data inside the files, the following agents can consume the created events: `#{receiving_file_handling_agents.join('`, `')}`. Read more about the concept in the [wiki](https://github.com/huginn/huginn/wiki/How-Huginn-works-with-files)." end def receiving_file_handling_agent_description @receiving_file_handling_agent_description ||= "This agent can consume a 'file pointer' event from the following agents with no additional configuration: `#{emitting_file_handling_agents.join('`, `')}`. Read more about the concept in the [wiki](https://github.com/huginn/huginn/wiki/How-Huginn-works-with-files)." end private def emitting_file_handling_agents emitting_file_handling_agents = file_handling_agents.select { |a| a.emits_file_pointer? } emitting_file_handling_agents.map { |a| a.to_s.demodulize } end def receiving_file_handling_agents receiving_file_handling_agents = file_handling_agents.select { |a| a.consumes_file_pointer? } receiving_file_handling_agents.map { |a| a.to_s.demodulize } end def file_handling_agents @file_handling_agents ||= Agent.types.select{ |c| c.included_modules.include?(FileHandling) }.map { |d| d.name.constantize } end module ClassMethods def emits_file_pointer! @emits_file_pointer = true end def emits_file_pointer? !!@emits_file_pointer end def consumes_file_pointer! @consumes_file_pointer = true end def consumes_file_pointer? !!@consumes_file_pointer end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/liquid_droppable.rb
app/concerns/liquid_droppable.rb
# frozen_string_literal: true module LiquidDroppable class Drop < Liquid::Drop def initialize(object) @object = object end def to_s @object.to_s end def each (public_instance_methods - Drop.public_instance_methods).each { |name| yield [name, __send__(name)] } end def as_json return {} unless defined?(self.class::METHODS) self.class::METHODS.to_h { |m| [m, send(m).as_json] } end end class MatchDataDrop < Drop METHODS = %w[pre_match post_match names size] METHODS.each { |attr| define_method(attr) { @object.__send__(attr) } } def to_s @object[0] end def liquid_method_missing(method) @object[method] rescue IndexError nil end end class ::MatchData def to_liquid MatchDataDrop.new(self) end end require 'uri' class URIDrop < Drop METHODS = URI::Generic::COMPONENT METHODS.each { |attr| define_method(attr) { @object.__send__(attr) } } end class ::URI::Generic def to_liquid URIDrop.new(self) end end class ActiveRecordCollectionDrop < Drop include Enumerable def each(&block) @object.each(&block) end # required for variable indexing as array def [](i) case i when Integer @object[i] when 'size', 'first', 'last' __send__(i) end end # required for variable indexing as array def fetch(i, &block) @object.fetch(i, &block) end # compatibility with array; also required by the `size` filter def size @object.count end # compatibility with array def first @object.first end # compatibility with array def last @object.last end # This drop currently does not support the `slice` filter. end class ::ActiveRecord::Associations::CollectionProxy def to_liquid ActiveRecordCollectionDrop.new(self) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/weibo_concern.rb
app/concerns/weibo_concern.rb
module WeiboConcern extend ActiveSupport::Concern included do gem_dependency_check { defined?(WeiboOAuth2) } self.validate :validate_weibo_options end def validate_weibo_options unless options['app_key'].present? && options['app_secret'].present? && options['access_token'].present? errors.add(:base, "app_key, app_secret and access_token are required") end end def weibo_client unless @weibo_client WeiboOAuth2::Config.api_key = options['app_key'] # WEIBO_APP_KEY WeiboOAuth2::Config.api_secret = options['app_secret'] # WEIBO_APP_SECRET @weibo_client = WeiboOAuth2::Client.new @weibo_client.get_token_from_hash :access_token => options['access_token'] end @weibo_client end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/event_headers_concern.rb
app/concerns/event_headers_concern.rb
# frozen_string_literal: true module EventHeadersConcern private def validate_event_headers_options! event_headers_payload({}) rescue ArgumentError => e errors.add(:base, e.message) rescue Liquid::Error => e errors.add(:base, "has an error with Liquid templating: #{e.message}") end def event_headers_normalizer case interpolated['event_headers_style'] when nil, '', 'capitalized' ->(name) { name.gsub(/[^-]+/, &:capitalize) } when 'downcased' :downcase.to_proc when 'snakecased' ->(name) { name.tr('A-Z-', 'a-z_') } when 'raw' :itself.to_proc else raise ArgumentError, "if provided, event_headers_style must be 'capitalized', 'downcased', 'snakecased' or 'raw'" end end def event_headers_key case key = interpolated['event_headers_key'] when nil, String key.presence else raise ArgumentError, "if provided, event_headers_key must be a string" end end def event_headers_payload(headers) key = event_headers_key or return {} normalize = event_headers_normalizer hash = headers.transform_keys(&normalize) names = case event_headers = interpolated['event_headers'] when Array event_headers.map(&:to_s) when String event_headers.split(',') when nil nil else raise ArgumentError, "if provided, event_headers must be an array of strings or a comma separated string" end { key => names ? hash.slice(*names.map(&normalize)) : hash } end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/working_helpers.rb
app/concerns/working_helpers.rb
module WorkingHelpers extend ActiveSupport::Concern def event_created_within?(days) last_event_at && last_event_at > days.to_i.days.ago end def recent_error_logs? last_event_at && last_error_log_at && last_error_log_at > (last_event_at - 2.minutes) end def received_event_without_error? (last_receive_at.present? && last_error_log_at.blank?) || (last_receive_at.present? && last_error_log_at.present? && last_receive_at > last_error_log_at) end def checked_without_error? (last_check_at.present? && last_error_log_at.nil?) || (last_check_at.present? && last_error_log_at.present? && last_check_at > last_error_log_at) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/long_runnable.rb
app/concerns/long_runnable.rb
=begin Usage Example: class Agents::ExampleAgent < Agent include LongRunnable # Optional # Override this method if you need to group multiple agents based on an API key, # or server they connect to. # Have a look at the TwitterStreamAgent for an example. def self.setup_worker; end class Worker < LongRunnable::Worker # Optional # Called after initialization of the Worker class, use this method as an initializer. def setup; end # Required # Put your agent logic in here, it must not return. If it does your agent will be restarted. def run; end # Optional # Use this method the gracefully stop your agent but make sure the run method return, or # terminate the thread. def stop; end end end =end module LongRunnable extend ActiveSupport::Concern included do |base| AgentRunner.register(base) end def start_worker? true end def worker_id(config = nil) "#{self.class.to_s}-#{id}-#{Digest::SHA1.hexdigest((config.presence || options).to_json)}" end module ClassMethods def setup_worker active.map do |agent| next unless agent.start_worker? self::Worker.new(id: agent.worker_id, agent: agent) end.compact end end class Worker attr_reader :thread, :id, :agent, :config, :mutex, :scheduler, :restarting def initialize(options = {}) @id = options[:id] @agent = options[:agent] @config = options[:config] @restarting = false end def run raise StandardError, 'Override LongRunnable::Worker#run in your agent Worker subclass.' end def run! @thread = Thread.new do Thread.current[:name] = "#{id}-#{Time.now}" begin run rescue SignalException, SystemExit stop! rescue StandardError => e message = "#{id} Exception #{e.message}:\n#{e.backtrace.first(10).join("\n")}" AgentRunner.with_connection do agent.error(message) end end end end def setup!(scheduler, mutex) @scheduler = scheduler @mutex = mutex setup if respond_to?(:setup) end def stop! @scheduler.jobs(tag: id).each(&:unschedule) if respond_to?(:stop) stop else terminate_thread! end end def terminate_thread! if thread thread.instance_eval { ActiveRecord::Base.connection_pool.release_connection } thread.wakeup if thread.status == 'sleep' thread.terminate end end def restart! without_alive_check do puts "--> Restarting #{id} at #{Time.now} <--" stop! setup!(scheduler, mutex) run! end end def every(*args, &blk) schedule(:every, args, &blk) end def cron(*args, &blk) schedule(:cron, args, &blk) end def schedule_in(*args, &blk) schedule(:schedule_in, args, &blk) end def boolify(value) agent.send(:boolify, value) end private def schedule(method, args, &blk) @scheduler.send(method, *args, tag: id, &blk) end def without_alive_check(&blk) @restarting = true yield ensure @restarting = false end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/google_oauth2_concern.rb
app/concerns/google_oauth2_concern.rb
module GoogleOauth2Concern extend ActiveSupport::Concern included do include Oauthable valid_oauth_providers :google end private def google_oauth2_client_id (config = Devise.omniauth_configs[:google]) && config.strategy.client_id end def google_oauth2_client_secret (config = Devise.omniauth_configs[:google]) && config.strategy.client_secret end def google_oauth2_email if service service.options[:email] end end def google_oauth2_access_token if service service.prepare_request service.token end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/dropbox_concern.rb
app/concerns/dropbox_concern.rb
module DropboxConcern extend ActiveSupport::Concern included do include Oauthable valid_oauth_providers :dropbox_oauth2 gem_dependency_check { defined?(Dropbox) && Devise.omniauth_providers.include?(:dropbox) } end def dropbox Dropbox::API::Config.app_key = consumer_key Dropbox::API::Config.app_secret = consumer_secret Dropbox::API::Config.mode = 'dropbox' Dropbox::API::Client.new(token: oauth_token, secret: oauth_token_secret) end private def consumer_key (config = Devise.omniauth_configs[:dropbox]) && config.strategy.client_id end def consumer_secret (config = Devise.omniauth_configs[:dropbox]) && config.strategy.client_secret end def oauth_token service && service.token end def oauth_token_secret service && service.secret end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/inheritance_tracking.rb
app/concerns/inheritance_tracking.rb
module InheritanceTracking extend ActiveSupport::Concern module ClassMethods def inherited(subclass) @subclasses ||= [] @subclasses << subclass @subclasses.uniq! super end def subclasses @subclasses end def with_subclasses(*subclasses) original_subclasses = @subclasses @subclasses = subclasses.flatten yield ensure @subclasses = original_subclasses end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/twitter_concern.rb
app/concerns/twitter_concern.rb
module TwitterConcern extend ActiveSupport::Concern included do include Oauthable validate :validate_twitter_options valid_oauth_providers :twitter gem_dependency_check { defined?(Twitter) && Devise.omniauth_providers.include?(:twitter) && ENV['TWITTER_OAUTH_KEY'].present? && ENV['TWITTER_OAUTH_SECRET'].present? } end def validate_twitter_options unless twitter_consumer_key.present? && twitter_consumer_secret.present? && twitter_oauth_token.present? && twitter_oauth_token_secret.present? errors.add( :base, "Twitter consumer_key, consumer_secret, oauth_token, and oauth_token_secret are required to authenticate with the Twitter API. You can provide these as options to this Agent, or as Credentials with the same names, but starting with 'twitter_'." ) end end def twitter_consumer_key (config = Devise.omniauth_configs[:twitter]) && config.strategy.consumer_key end def twitter_consumer_secret (config = Devise.omniauth_configs[:twitter]) && config.strategy.consumer_secret end def twitter_oauth_token service && service.token end def twitter_oauth_token_secret service && service.secret end def twitter @twitter ||= Twitter::REST::Client.new do |config| config.consumer_key = twitter_consumer_key config.consumer_secret = twitter_consumer_secret config.access_token = twitter_oauth_token config.access_token_secret = twitter_oauth_token_secret end end HTML_ENTITIES = { '&amp;' => '&', '&lt;' => '<', '&gt;' => '>', } RE_HTML_ENTITIES = Regexp.union(HTML_ENTITIES.keys) def format_tweet(tweet) attrs = case tweet when Twitter::Tweet tweet.attrs when Hash if tweet.key?(:id) tweet else tweet.deep_symbolize_keys end else raise TypeError, "Unexpected tweet type: #{tweet.class}" end text = (attrs[:full_text] || attrs[:text])&.dup or return attrs expanded_text = text.dup.tap { |text| attrs.dig(:entities, :urls)&.reverse_each do |entity| from, to = entity[:indices] text[from...to] = entity[:expanded_url] end } text.gsub!(RE_HTML_ENTITIES, HTML_ENTITIES) expanded_text.gsub!(RE_HTML_ENTITIES, HTML_ENTITIES) attrs[:text] &&= text attrs[:full_text] &&= text attrs.update(expanded_text:) end module_function :format_tweet module ClassMethods def twitter_dependencies_missing if ENV['TWITTER_OAUTH_KEY'].blank? || ENV['TWITTER_OAUTH_SECRET'].blank? "## Set TWITTER_OAUTH_KEY and TWITTER_OAUTH_SECRET in your environment to use Twitter Agents." elsif !defined?(Twitter) || !Devise.omniauth_providers.include?(:twitter) "## Include the `twitter`, `omniauth-twitter`, and `cantino-twitter-stream` gems in your Gemfile to use Twitter Agents." end end def tweet_event_description(text_key, extra_fields = nil) <<~MD.indent(4) { #{extra_fields&.indent(2)}// ... every Tweet field, including ... // Huginn automatically decodes "&lt;", "&gt;", and "&amp;" to "<", ">", and "&". "#{text_key}": "something https://t.co/XXXX", "user": { "name": "Mr. Someone", "screen_name": "Someone", "location": "Vancouver BC Canada", "description": "...", "followers_count": 486, "friends_count": 1983, "created_at": "Mon Aug 29 23:38:14 +0000 2011", "time_zone": "Pacific Time (US & Canada)", "statuses_count": 3807, "lang": "en" }, "retweet_count": 0, "entities": ... "lang": "en", // Huginn adds this field, expanding all shortened t.co URLs in "#{text_key}". "expanded_text": "something https://example.org/foo/bar" } MD end end end class Twitter::Error remove_const :FORBIDDEN_MESSAGES FORBIDDEN_MESSAGES = proc do |message| case message when /(?=.*status).*duplicate/i # - "Status is a duplicate." Twitter::Error::DuplicateStatus when /already favorited/i # - "You have already favorited this status." Twitter::Error::AlreadyFavorited when /already retweeted|Share validations failed/i # - "You have already retweeted this Tweet." (Nov 2017-) # - "You have already retweeted this tweet." (?-Nov 2017) # - "sharing is not permissible for this status (Share validations failed)" (-? 2017) Twitter::Error::AlreadyRetweeted end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/evernote_concern.rb
app/concerns/evernote_concern.rb
module EvernoteConcern extend ActiveSupport::Concern included do include Oauthable validate :validate_evernote_options valid_oauth_providers :evernote gem_dependency_check { defined?(EvernoteOAuth) && Devise.omniauth_providers.include?(:evernote) } end def evernote_client EvernoteOAuth::Client.new( token: evernote_oauth_token, consumer_key: evernote_consumer_key, consumer_secret: evernote_consumer_secret, sandbox: use_sandbox? ) end private def use_sandbox? ENV["USE_EVERNOTE_SANDBOX"] == "true" end def validate_evernote_options unless evernote_consumer_key.present? && evernote_consumer_secret.present? && evernote_oauth_token.present? errors.add(:base, "Evernote ENV variables and a Service are required") end end def evernote_consumer_key (config = Devise.omniauth_configs[:evernote]) && config.strategy.consumer_key end def evernote_consumer_secret (config = Devise.omniauth_configs[:evernote]) && config.strategy.consumer_secret end def evernote_oauth_token service && service.token end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/tumblr_concern.rb
app/concerns/tumblr_concern.rb
module TumblrConcern extend ActiveSupport::Concern included do include Oauthable valid_oauth_providers :tumblr end def tumblr_consumer_key ENV['TUMBLR_OAUTH_KEY'] end def tumblr_consumer_secret ENV['TUMBLR_OAUTH_SECRET'] end def tumblr_oauth_token service.token end def tumblr_oauth_token_secret service.secret end def tumblr Tumblr.configure do |config| config.consumer_key = tumblr_consumer_key config.consumer_secret = tumblr_consumer_secret config.oauth_token = tumblr_oauth_token config.oauth_token_secret = tumblr_oauth_token_secret end Tumblr::Client.new end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/email_concern.rb
app/concerns/email_concern.rb
module EmailConcern extend ActiveSupport::Concern MAIN_KEYS = %w[title message text main value] included do self.validate :validate_email_options end def validate_email_options errors.add( :base, "subject and expected_receive_period_in_days are required" ) unless options['subject'].present? && options['expected_receive_period_in_days'].present? if options['recipients'].present? emails = options['recipients'] emails = [emails] if emails.is_a?(String) unless emails.all? { |email| Devise.email_regexp === email || /\{/ === email } errors.add(:base, "'when provided, 'recipients' should be an email address or an array of email addresses") end end end def recipients(payload = {}) emails = interpolated(payload)['recipients'] if emails.present? if emails.is_a?(String) [emails] else emails end else [user.email] end end def working? last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs? end def present(payload) if payload.is_a?(Hash) payload = ActiveSupport::HashWithIndifferentAccess.new(payload) MAIN_KEYS.each do |key| return { title: payload[key].to_s, entries: present_hash(payload, key) } if payload.has_key?(key) end { title: "Event", entries: present_hash(payload) } else { title: payload.to_s, entries: [] } end end def present_hash(hash, skip_key = nil) hash.to_a.sort_by { |a| a.first.to_s }.map { |k, v| "#{k}: #{v}" unless k.to_s == skip_key.to_s }.compact end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/concerns/sortable_events.rb
app/concerns/sortable_events.rb
module SortableEvents extend ActiveSupport::Concern included do validate :validate_events_order end EVENTS_ORDER_KEY = 'events_order'.freeze EVENTS_DESCRIPTION = 'events created in each run'.freeze def description_events_order(*args) self.class.description_events_order(*args) end module ClassMethods def can_order_created_events! raise 'Cannot order events for agent that cannot create events' if cannot_create_events? prepend AutomaticSorter end def can_order_created_events? include? AutomaticSorter end def cannot_order_created_events? !can_order_created_events? end def description_events_order(events = EVENTS_DESCRIPTION, events_order_key = EVENTS_ORDER_KEY) <<~MD To specify the order of #{events}, set `#{events_order_key}` to an array of sort keys, each of which looks like either `expression` or `[expression, type, descending]`, as described as follows: * _expression_ is a Liquid template to generate a string to be used as sort key. * _type_ (optional) is one of `string` (default), `number` and `time`, which specifies how to evaluate _expression_ for comparison. * _descending_ (optional) is a boolean value to determine if comparison should be done in descending (reverse) order, which defaults to `false`. Sort keys listed earlier take precedence over ones listed later. For example, if you want to sort articles by the date and then by the author, specify `[["{{date}}", "time"], "{{author}}"]`. Sorting is done stably, so even if all events have the same set of sort key values the original order is retained. Also, a special Liquid variable `_index_` is provided, which contains the zero-based index number of each event, which means you can exactly reverse the order of events by specifying `[["{{_index_}}", "number", true]]`. #{description_include_sort_info if events == EVENTS_DESCRIPTION} MD end def description_include_sort_info <<-MD.lstrip If the `include_sort_info` option is set, each created event will have a `sort_info` key whose value is a hash containing the following keys: * `position`: 1-based index of each event after the sort * `count`: Total number of events sorted MD end end def can_order_created_events? self.class.can_order_created_events? end def cannot_order_created_events? self.class.cannot_order_created_events? end def events_order(key = EVENTS_ORDER_KEY) options[key] end def include_sort_info? boolify(interpolated['include_sort_info']) end def create_events(events) if include_sort_info? count = events.count events.each.with_index(1) do |event, position| event.payload[:sort_info] = { position:, count: } create_event(event) end else events.each do |event| create_event(event) end end end module AutomaticSorter def check return super unless events_order || include_sort_info? sorting_events do super end end def receive(incoming_events) return super unless events_order || include_sort_info? # incoming events should be processed sequentially incoming_events.each do |event| sorting_events do super([event]) end end end def create_event(event) if @sortable_events event = build_event(event) @sortable_events << event event else super end end private def sorting_events(&block) @sortable_events = [] yield ensure events = sort_events(@sortable_events) @sortable_events = nil create_events(events) end end private EXPRESSION_PARSER = { 'string' => ->(string) { string }, 'number' => ->(string) { string.to_f }, 'time' => ->(string) { Time.zone.parse(string) }, } EXPRESSION_TYPES = EXPRESSION_PARSER.keys.freeze def validate_events_order(events_order_key = EVENTS_ORDER_KEY) case order_by = events_order(events_order_key) when nil when Array # Each tuple may be either [expression, type, desc] or just # expression. order_by.each do |expression, type, desc| case expression when String # ok else errors.add(:base, "first element of each #{events_order_key} tuple must be a Liquid template") break end case type when nil, *EXPRESSION_TYPES # ok else errors.add(:base, "second element of each #{events_order_key} tuple must be #{EXPRESSION_TYPES.to_sentence(last_word_connector: ' or ')}") break end if !desc.nil? && boolify(desc).nil? errors.add(:base, "third element of each #{events_order_key} tuple must be a boolean value") break end end else errors.add(:base, "#{events_order_key} must be an array of arrays") end end # Sort given events in order specified by the "events_order" option def sort_events(events, events_order_key = EVENTS_ORDER_KEY) order_by = events_order(events_order_key).presence or return events orders = order_by.map { |_, _, desc = false| boolify(desc) } Utils.sort_tuples!( events.map.with_index { |event, index| interpolate_with(event) { interpolation_context['_index_'] = index order_by.map { |expression, type, _| string = interpolate_string(expression) begin EXPRESSION_PARSER[type || 'string'.freeze][string] rescue StandardError error "Cannot parse #{string.inspect} as #{type}; treating it as string" string end } } << index << event # index is to make sorting stable }, orders ).collect!(&:last) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/presenters/form_configurable_agent_presenter.rb
app/presenters/form_configurable_agent_presenter.rb
require 'delegate' class Decorator < SimpleDelegator def class __getobj__.class end end class FormConfigurableAgentPresenter < Decorator def initialize(agent, view) @agent = agent @view = view super(agent) end def option_field_for(attribute) data = @agent.form_configurable_fields[attribute] value = @agent.options[attribute.to_s] || @agent.default_options[attribute.to_s] html_options = data.fetch(:html_options, {}).deep_merge({ role: (data[:roles] + ['form-configurable']).join(' '), data: { attribute: }, }) case data[:type] when :text @view.content_tag 'div' do @view.concat @view.text_area_tag("agent[options][#{attribute}]", value, html_options.merge(class: 'form-control', rows: 3)) if data[:ace].present? ace_options = { source: "[name='agent[options][#{attribute}]']", mode: '', theme: '' }.deep_symbolize_keys! ace_options.deep_merge!(data[:ace].deep_symbolize_keys) if data[:ace].is_a?(Hash) @view.concat @view.content_tag('div', '', class: 'ace-editor', data: ace_options) end end when :boolean @view.content_tag 'div' do @view.concat(@view.content_tag('label', class: 'radio-inline') do @view.concat @view.radio_button_tag "agent[options][#{attribute}_radio]", 'true', @agent.send(:boolify, value) == true, html_options @view.concat "True" end) @view.concat(@view.content_tag('label', class: 'radio-inline') do @view.concat @view.radio_button_tag "agent[options][#{attribute}_radio]", 'false', @agent.send(:boolify, value) == false, html_options @view.concat "False" end) @view.concat(@view.content_tag('label', class: 'radio-inline') do @view.concat @view.radio_button_tag "agent[options][#{attribute}_radio]", 'manual', @agent.send(:boolify, value).nil?, html_options @view.concat "Manual Input" end) @view.concat(@view.text_field_tag("agent[options][#{attribute}]", value, html_options.merge(class: "form-control #{@agent.send(:boolify, value) != nil ? 'hidden' : ''}"))) end when :array @view.select_tag "agent[options][#{attribute}]", nil, html_options.deep_merge(class: 'form-control', data: { value:, cache_response: data[:cache_response] != false }) when :string @view.text_field_tag "agent[options][#{attribute}]", value, html_options.deep_merge(class: 'form-control', data: { cache_response: data[:cache_response] != false }) when :number @view.number_field_tag "agent[options][#{attribute}]", value, html_options.deep_merge(class: 'form-control', data: { cache_response: data[:cache_response] != false }) when :json @view.text_area_tag "agent[options][#{attribute}]", value, html_options.deep_merge(class: 'form-control live-json-editor', rows: 10) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/helpers/scenario_helper.rb
app/helpers/scenario_helper.rb
module ScenarioHelper def style_colors(scenario) { color: scenario.tag_fg_color || default_scenario_fg_color, background_color: scenario.tag_bg_color || default_scenario_bg_color }.map { |key, value| "#{key.to_s.dasherize}:#{value}" }.join(';') end def scenario_label(scenario, text = nil) text ||= scenario.name content_tag :span, text, class: 'label scenario', style: style_colors(scenario) end def default_scenario_bg_color '#5BC0DE' end def default_scenario_fg_color '#FFFFFF' end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/helpers/jobs_helper.rb
app/helpers/jobs_helper.rb
module JobsHelper def status(job) case when job.failed_at content_tag :span, 'failed', class: 'label label-danger' when job.locked_at && job.locked_by content_tag :span, 'running', class: 'label label-info' else content_tag :span, 'queued', class: 'label label-warning' end end def relative_distance_of_time_in_words(time) if time < (now = Time.now) time_ago_in_words(time) + ' ago' else 'in ' + distance_of_time_in_words(time, now) end end # Given an queued job, parse the stored YAML to retrieve the ID of the Agent # meant to be ran. # # Can return nil, or an instance of Agent. def agent_from_job(job) data = YAML.unsafe_load(job.handler.to_s).try(:job_data) return false unless data case data['job_class'] when 'AgentCheckJob', 'AgentReceiveJob' Agent.find_by_id(data['arguments'][0]) when 'AgentRunScheduleJob' "Run Agent schedule '#{data['arguments'][0]}'" when 'AgentCleanupExpiredJob' 'Run Event cleanup' when 'AgentPropagateJob' 'Run Event propagation' else false end rescue ArgumentError # We can get to this point before all of the agents have loaded (usually, # in development) nil end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/helpers/agent_helper.rb
app/helpers/agent_helper.rb
module AgentHelper def agent_show_view(agent) path = File.join('agents', 'agent_views', @agent.short_type.underscore, 'show') return self.controller.template_exists?(path, [], true) ? path : nil end def toggle_disabled_text if cookies[:huginn_view_only_enabled_agents] " Show Disabled Agents" else " Hide Disabled Agents" end end def scenario_links(agent) agent.scenarios.map { |scenario| link_to(scenario.name, scenario, class: "label", style: style_colors(scenario)) }.join(" ").html_safe end def agent_show_class(agent) agent.short_type.underscore.dasherize end def agent_schedule(agent, delimiter = ', ') return 'n/a' unless agent.can_be_scheduled? case agent.schedule when nil, 'never' agent_controllers(agent, delimiter) || 'Never' else [ builtin_schedule_name(agent.schedule), *(agent_controllers(agent, delimiter)) ].join(delimiter).html_safe end end def builtin_schedule_name(schedule) AgentHelper.builtin_schedule_name(schedule) end def self.builtin_schedule_name(schedule) schedule == 'every_7d' ? 'Every Monday' : schedule.humanize.titleize end def agent_controllers(agent, delimiter = ', ') if agent.controllers.present? agent.controllers.map { |agent| link_to(agent.name, agent_path(agent)) }.join(delimiter).html_safe end end def agent_dry_run_with_event_mode(agent) case when agent.cannot_receive_events? 'no'.freeze when agent.cannot_be_scheduled? # incoming event is the only trigger for the agent 'yes'.freeze else 'maybe'.freeze end end def agent_type_icon(agent, agents) receiver_count = links_counter_cache(agents)[:links_as_receiver][agent.id] || 0 control_count = links_counter_cache(agents)[:control_links_as_controller][agent.id] || 0 source_count = links_counter_cache(agents)[:links_as_source][agent.id] || 0 if control_count > 0 && receiver_count > 0 content_tag('span') do concat icon_tag('glyphicon-arrow-right') concat tag('br') concat icon_tag('glyphicon-new-window', class: 'glyphicon-flipped') end elsif control_count > 0 && receiver_count == 0 icon_tag('glyphicon-new-window', class: 'glyphicon-flipped') elsif receiver_count > 0 && source_count == 0 icon_tag('glyphicon-arrow-right') elsif receiver_count == 0 && source_count > 0 icon_tag('glyphicon-arrow-left') elsif receiver_count > 0 && source_count > 0 icon_tag('glyphicon-transfer') else icon_tag('glyphicon-unchecked') end end def agent_type_select_options Rails.cache.fetch('agent_type_select_options') do types = Agent.types.map {|type| [agent_type_to_human(type.name), type, {title: h(Agent.build_for_type(type.name, User.new(id: 0), {}).html_description.lines.first.strip)}] } types.sort_by! { |t| t[0] } [['Select an Agent Type', 'Agent', {title: ''}]] + types end end private def links_counter_cache(agents) @counter_cache ||= {} @counter_cache[agents.__id__] ||= {}.tap do |cache| agent_ids = agents.map(&:id) cache[:links_as_receiver] = Hash[Link.where(receiver_id: agent_ids) .group(:receiver_id) .pluck(:receiver_id, Arel.sql('count(receiver_id) as id'))] cache[:links_as_source] = Hash[Link.where(source_id: agent_ids) .group(:source_id) .pluck(:source_id, Arel.sql('count(source_id) as id'))] cache[:control_links_as_controller] = Hash[ControlLink.where(controller_id: agent_ids) .group(:controller_id) .pluck(:controller_id, Arel.sql('count(controller_id) as id'))] end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/helpers/users_helper.rb
app/helpers/users_helper.rb
module UsersHelper def user_account_state(user) if !user.active? content_tag :span, 'inactive', class: 'label label-danger' elsif user.access_locked? content_tag :span, 'locked', class: 'label label-danger' elsif ENV['REQUIRE_CONFIRMED_EMAIL'] == 'true' && !user.confirmed? content_tag :span, 'unconfirmed', class: 'label label-warning' else content_tag :span, 'active', class: 'label label-success' end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/helpers/dot_helper.rb
app/helpers/dot_helper.rb
module DotHelper def render_agents_diagram(agents, layout: nil) if svg = dot_to_svg(agents_dot(agents, rich: true, layout:)) decorate_svg(svg, agents).html_safe else # Google chart request url faraday = Faraday.new { |builder| builder.request :url_encoded builder.adapter Faraday.default_adapter } response = faraday.post('https://chart.googleapis.com/chart', { cht: 'gv', chl: agents_dot(agents) }) case response.status when 200 # Display Base64-Encoded images tag('img', src: 'data:image/jpg;base64,' + Base64.encode64(response.body)) when 400 "The diagram can't be displayed because it has too many nodes. Max allowed is 80." when 413 "The diagram can't be displayed because it is too large." else "Unknow error. Response code is #{response.status}." end end end private def dot_to_svg(dot) command = ENV['USE_GRAPHVIZ_DOT'] or return nil IO.popen(%W[#{command} -Tsvg -q1 -o/dev/stdout /dev/stdin], 'w+') do |rw| rw.print dot rw.close_write rw.read rescue StandardError end end class DotDrawer def initialize(vars = {}) @dot = '' vars.each do |key, value| define_singleton_method(key) { value } end end def to_s @dot end def self.draw(*args, &block) drawer = new(*args) drawer.instance_exec(&block) drawer.to_s end def raw(string) @dot << string end ENDL = ';'.freeze def endl @dot << ENDL end def escape(string) # Backslash escaping seems to work for the backslash itself, # though it's not documented in the DOT language docs. string.gsub(/[\\"\n]/, "\\" => "\\\\", "\"" => "\\\"", "\n" => "\\n") end def id(value) case string = value.to_s when /\A(?!\d)\w+\z/, /\A(?:\.\d+|\d+(?:\.\d*)?)\z/ raw string else raw '"' raw escape(string) raw '"' end end def ids(values) values.each_with_index { |id, i| raw ' ' if i > 0 id id } end def attr_list(attrs = nil) return if attrs.nil? attrs = attrs.select { |_key, value| value.present? } return if attrs.empty? raw '[' attrs.each_with_index { |(key, value), i| raw ',' if i > 0 id key raw '=' id value } raw ']' end def node(id, attrs = nil) id id attr_list attrs endl end def edge(from, to, attrs = nil, op = '->') id from raw op id to attr_list attrs endl end def statement(ids, attrs = nil) ids Array(ids) attr_list attrs endl end def block(*ids, &block) ids ids raw '{' block.call raw '}' end end private def draw(vars = {}, &block) DotDrawer.draw(vars, &block) end def agents_dot(agents, rich: false, layout: nil) draw(agents:, agent_id: ->(agent) { 'a%d' % agent.id }, agent_label: ->(agent) { agent.name.gsub(/(.{20}\S*)\s+/) { # Fold after every 20+ characters $1 + "\n" } }, agent_url: ->(agent) { agent_path(agent.id) }, rich:) { @disabled = '#999999' def agent_node(agent) node(agent_id[agent], label: agent_label[agent], tooltip: (agent.short_type.titleize if rich), URL: (agent_url[agent] if rich), style: ('rounded,dashed' if agent.unavailable?), color: (@disabled if agent.unavailable?), fontcolor: (@disabled if agent.unavailable?)) end def agent_edge(agent, receiver) edge(agent_id[agent], agent_id[receiver], style: ('dashed' unless receiver.propagate_immediately?), label: (" #{agent.control_action.pluralize} " if agent.can_control_other_agents?), arrowhead: ('empty' if agent.can_control_other_agents?), color: (@disabled if agent.unavailable? || receiver.unavailable?)) end block('digraph', 'Agent Event Flow') { layout ||= ENV['DIAGRAM_DEFAULT_LAYOUT'].presence if rich && /\A[a-z]+\z/ === layout statement 'graph', layout:, overlap: 'false' end statement 'node', shape: 'box', style: 'rounded', target: '_blank', fontsize: 10, fontname: ('Helvetica' if rich) statement 'edge', fontsize: 10, fontname: ('Helvetica' if rich) agents.each.with_index { |agent, _index| agent_node(agent) [ *agent.receivers, *(agent.control_targets if agent.can_control_other_agents?) ].each { |receiver| agent_edge(agent, receiver) if agents.include?(receiver) } } } } end def decorate_svg(xml, agents) svg = Nokogiri::XML(xml).at('svg') Nokogiri::HTML::Document.new.tap { |doc| doc << root = Nokogiri::XML::Node.new('div', doc) { |div| div['class'] = 'agent-diagram' } svg['class'] = 'diagram' root << svg root << overlay_container = Nokogiri::XML::Node.new('div', doc) { |div| div['class'] = 'overlay-container' } overlay_container << overlay = Nokogiri::XML::Node.new('div', doc) { |div| div['class'] = 'overlay' } svg.xpath('//xmlns:g[@class="node"]', svg.namespaces).each { |node| agent_id = (node.xpath('./xmlns:title/text()', svg.namespaces).to_s[/\d+/] or next).to_i agent = agents.find { |a| a.id == agent_id } count = agent.events_count next unless count && count > 0 overlay << Nokogiri::XML::Node.new('a', doc) { |badge| badge['id'] = id = 'b%d' % agent_id badge['class'] = 'badge' badge['href'] = agent_events_path(agent) badge['target'] = '_blank' badge['title'] = "#{count} events created" badge.content = count.to_s node['data-badge-id'] = id badge << Nokogiri::XML::Node.new('span', doc) { |label| # a dummy label only to obtain the background color label['class'] = [ 'label', if agent.unavailable? 'label-warning' elsif agent.working? 'label-success' else 'label-danger' end ].join(' ') label['style'] = 'display: none' } } } # See also: app/assets/diagram.js }.at('div.agent-diagram').to_s end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/helpers/application_helper.rb
app/helpers/application_helper.rb
module ApplicationHelper def icon_tag(name, options = {}) dom_class = options[:class] case name when /\Aglyphicon-/ "<span class='glyphicon #{name}#{' ' if dom_class}#{dom_class}'></span>".html_safe when /\Afa-/ "<i class='#{'fa-solid ' unless /(?:\A| )fa-(?:solid|brands)(?: |\z)/.match?(dom_class)}#{name}#{' ' if dom_class}#{dom_class}'></i>".html_safe else raise "Unrecognized icon name: #{name}" end end def nav_link(name, path, options = {}, &block) content = link_to(name, path, options) active = current_page?(path) if block # Passing a block signifies that the link is a header of a hover # menu which contains what's in the block. begin @nav_in_menu = true @nav_link_active = active content += capture(&block) class_name = "dropdown dropdown-hover #{@nav_link_active ? 'active' : ''}" ensure @nav_in_menu = @nav_link_active = false end else # Mark the menu header active if it contains the current page @nav_link_active ||= active if @nav_in_menu # An "active" menu item may be an eyesore, hence `!@nav_in_menu &&`. class_name = !@nav_in_menu && active ? 'active' : '' end content_tag :li, content, class: class_name end def yes_no(bool) content_tag :span, bool ? 'Yes' : 'No', class: "label #{bool ? 'label-info' : 'label-default' }" end def working(agent) if agent.disabled? link_to 'Disabled', agent_path(agent), class: 'label label-warning' elsif agent.dependencies_missing? content_tag :span, 'Missing Gems', class: 'label label-danger' elsif agent.working? content_tag :span, 'Yes', class: 'label label-success' else link_to 'No', agent_path(agent, tab: (agent.recent_error_logs? ? 'logs' : 'details')), class: 'label label-danger' end end def omniauth_provider_icon(provider) case provider.to_sym when :twitter, :tumblr, :github, :dropbox, :google icon_tag("fa-#{provider}", class: 'fa-brands') else icon_tag("fa-lock") end end def omniauth_provider_name(provider) t("devise.omniauth_providers.#{provider}") end def omniauth_button(provider) link_to [ omniauth_provider_icon(provider), content_tag(:span, "Authenticate with #{omniauth_provider_name(provider)}") ].join.html_safe, user_omniauth_authorize_path(provider), class: "btn btn-default btn-service service-#{provider}" end def service_label_text(service) "#{omniauth_provider_name(service.provider)} - #{service.name}" end def service_label(service) return if service.nil? content_tag :span, [ omniauth_provider_icon(service.provider), service_label_text(service) ].join.html_safe, class: "label label-default label-service service-#{service.provider}" end def load_ace_editor! unless content_for?(:ace_editor_script) content_for :ace_editor_script, javascript_include_tag('ace') end end def highlighted?(id) @highlighted_ranges ||= case value = params[:hl].presence when String value.split(/,/).flat_map { |part| case part when /\A(\d+)\z/ (part.to_i)..(part.to_i) when /\A(\d+)?-(\d+)?\z/ ($1 ? $1.to_i : 1)..($2 ? $2.to_i : Float::INFINITY) else [] end } else [] end @highlighted_ranges.any? { |range| range.cover?(id) } end def agent_type_to_human(type) type.gsub(/^.*::/, '').underscore.humanize.titleize end private def user_omniauth_authorize_path(provider) send "user_#{provider}_omniauth_authorize_path" end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/helpers/markdown_helper.rb
app/helpers/markdown_helper.rb
module MarkdownHelper def markdown(text) Kramdown::Document.new(text, auto_ids: false).to_html.html_safe end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/helpers/logs_helper.rb
app/helpers/logs_helper.rb
module LogsHelper end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/importers/default_scenario_importer.rb
app/importers/default_scenario_importer.rb
require 'open-uri' class DefaultScenarioImporter def self.import(user) return unless ENV['IMPORT_DEFAULT_SCENARIO_FOR_ALL_USERS'] == 'true' seed(user) end def self.seed(user) scenario_import = ScenarioImport.new() scenario_import.set_user(user) scenario_file = ENV['DEFAULT_SCENARIO_FILE'].presence || File.join(Rails.root, "data", "default_scenario.json") begin scenario_import.file = open(scenario_file) raise "Import failed" unless scenario_import.valid? && scenario_import.import ensure scenario_import.file.close end return true end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/importers/scenario_import.rb
app/importers/scenario_import.rb
require 'ostruct' # This is a helper class for managing Scenario imports, used by the ScenarioImportsController. This class behaves much # like a normal ActiveRecord object, with validations and callbacks. However, it is never persisted to the database. class ScenarioImport include ActiveModel::Model include ActiveModel::Callbacks include ActiveModel::Validations::Callbacks DANGEROUS_AGENT_TYPES = %w[Agents::ShellCommandAgent] URL_REGEX = /\Ahttps?:\/\//i attr_accessor :file, :url, :data, :do_import, :merges attr_reader :user before_validation :parse_file before_validation :fetch_url validate :validate_presence_of_file_url_or_data validates_format_of :url, :with => URL_REGEX, :allow_nil => true, :allow_blank => true, :message => "appears to be invalid" validate :validate_data validate :generate_diff def step_one? data.blank? end def step_two? data.present? end def set_user(user) @user = user end def existing_scenario @existing_scenario ||= user.scenarios.find_by(:guid => parsed_data["guid"]) end def dangerous? (parsed_data['agents'] || []).any? { |agent| DANGEROUS_AGENT_TYPES.include?(agent['type']) } end def parsed_data @parsed_data ||= (data && JSON.parse(data) rescue {}) || {} end def agent_diffs @agent_diffs || generate_diff end def import_confirmed? do_import == "1" end def import(options = {}) success = true guid = parsed_data['guid'] description = parsed_data['description'] name = parsed_data['name'] links = parsed_data['links'] control_links = parsed_data['control_links'] || [] tag_fg_color = parsed_data['tag_fg_color'] tag_bg_color = parsed_data['tag_bg_color'] icon = parsed_data['icon'] source_url = parsed_data['source_url'].presence || nil @scenario = user.scenarios.where(:guid => guid).first_or_initialize @scenario.update!(name: name, description: description, source_url: source_url, public: false, tag_fg_color: tag_fg_color, tag_bg_color: tag_bg_color, icon: icon) unless options[:skip_agents] created_agents = agent_diffs.map do |agent_diff| agent = agent_diff.agent || Agent.build_for_type("Agents::" + agent_diff.type.incoming, user) agent.guid = agent_diff.guid.incoming agent.attributes = { :name => agent_diff.name.updated, :disabled => agent_diff.disabled.updated, # == "true" :options => agent_diff.options.updated, :scenario_ids => [@scenario.id] } agent.schedule = agent_diff.schedule.updated if agent_diff.schedule.present? agent.keep_events_for = agent_diff.keep_events_for.updated if agent_diff.keep_events_for.present? agent.propagate_immediately = agent_diff.propagate_immediately.updated if agent_diff.propagate_immediately.present? # == "true" agent.service_id = agent_diff.service_id.updated if agent_diff.service_id.present? unless agent.save success = false errors.add(:base, "Errors when saving '#{agent_diff.name.incoming}': #{agent.errors.full_messages.to_sentence}") end agent end if success links.each do |link| receiver = created_agents[link['receiver']] source = created_agents[link['source']] receiver.sources << source unless receiver.sources.include?(source) end control_links.each do |control_link| controller = created_agents[control_link['controller']] control_target = created_agents[control_link['control_target']] controller.control_targets << control_target unless controller.control_targets.include?(control_target) end end end success end def scenario @scenario || @existing_scenario end protected def parse_file if data.blank? && file.present? self.data = file.read.force_encoding(Encoding::UTF_8) end end def fetch_url if data.blank? && url.present? && url =~ URL_REGEX self.data = Faraday.get(url).body end end def validate_data if data.present? @parsed_data = JSON.parse(data) rescue {} if (%w[name guid agents] - @parsed_data.keys).length > 0 errors.add(:base, "The provided data does not appear to be a valid Scenario.") self.data = nil end else @parsed_data = nil end end def validate_presence_of_file_url_or_data unless file.present? || url.present? || data.present? errors.add(:base, "Please provide either a Scenario JSON File or a Public Scenario URL.") end end def generate_diff @agent_diffs = (parsed_data['agents'] || []).map.with_index do |agent_data, index| # AgentDiff is defined at the end of this file. agent_diff = AgentDiff.new(agent_data, parsed_data['schema_version']) if existing_scenario # If this Agent exists already, update the AgentDiff with the local version's information. agent_diff.diff_with! existing_scenario.agents.find_by(:guid => agent_data['guid']) begin # Update the AgentDiff with any hand-merged changes coming from the UI. This only happens when this # Agent already exists locally and has conflicting changes. agent_diff.update_from! merges[index.to_s] if merges rescue JSON::ParserError errors.add(:base, "Your updated options for '#{agent_data['name']}' were unparsable.") end end if agent_diff.requires_service? && merges.present? && merges[index.to_s].present? && merges[index.to_s]['service_id'].present? agent_diff.service_id = AgentDiff::FieldDiff.new(merges[index.to_s]['service_id'].to_i) end agent_diff end end # AgentDiff is a helper object that encapsulates an incoming Agent. All fields will be returned as an array # of either one or two values. The first value is the incoming value, the second is the existing value, if # it differs from the incoming value. class AgentDiff < OpenStruct class FieldDiff attr_accessor :incoming, :current, :updated def initialize(incoming) @incoming = incoming @updated = incoming end def set_current(current) @current = current @requires_merge = (incoming != current) end def requires_merge? @requires_merge end end def initialize(agent_data, schema_version) super() @schema_version = schema_version @requires_merge = false self.agent = nil store! agent_data end BASE_FIELDS = %w[name schedule keep_events_for propagate_immediately disabled guid] FIELDS_REQUIRING_TRANSLATION = %w[keep_events_for] def agent_exists? !!agent end def requires_merge? @requires_merge end def requires_service? !!agent_instance.try(:oauthable?) end def store!(agent_data) self.type = FieldDiff.new(agent_data["type"].split("::").pop) self.options = FieldDiff.new(agent_data['options'] || {}) BASE_FIELDS.each do |option| if agent_data.has_key?(option) value = agent_data[option] value = send(:"translate_#{option}", value) if option.in?(FIELDS_REQUIRING_TRANSLATION) self[option] = FieldDiff.new(value) end end end def translate_keep_events_for(old_value) if schema_version < 1 # Was stored in days, now is stored in seconds. old_value.to_i.days else old_value end end def schema_version (@schema_version || 0).to_i end def diff_with!(agent) return unless agent.present? self.agent = agent type.set_current(agent.short_type) options.set_current(agent.options || {}) @requires_merge ||= type.requires_merge? @requires_merge ||= options.requires_merge? BASE_FIELDS.each do |field| next unless self[field].present? self[field].set_current(agent.send(field)) @requires_merge ||= self[field].requires_merge? end end def update_from!(merges) each_field do |field, value, selection_options| value.updated = merges[field] end if options.requires_merge? options.updated = JSON.parse(merges['options']) end end def each_field boolean = [["True", "true"], ["False", "false"]] yield 'name', name if name.requires_merge? yield 'schedule', schedule, Agent::SCHEDULES.map {|s| [AgentHelper.builtin_schedule_name(s), s] } if self['schedule'].present? && schedule.requires_merge? yield 'keep_events_for', keep_events_for, Agent::EVENT_RETENTION_SCHEDULES if self['keep_events_for'].present? && keep_events_for.requires_merge? yield 'propagate_immediately', propagate_immediately, boolean if self['propagate_immediately'].present? && propagate_immediately.requires_merge? yield 'disabled', disabled, boolean if disabled.requires_merge? end def agent_instance "Agents::#{self.type.updated}".constantize.new end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/validators/owned_by_validator.rb
app/validators/owned_by_validator.rb
class OwnedByValidator < ActiveModel::EachValidator def validate_each(record, attribute, association) return if association.all? {|s| s[options[:with]] == record[options[:with]] } record.errors.add(attribute, "must be owned by you") end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/diagrams_controller.rb
app/controllers/diagrams_controller.rb
class DiagramsController < ApplicationController def show if params[:scenario_id].present? @scenario = current_user.scenarios.find(params[:scenario_id]) agents = @scenario.agents else agents = current_user.agents end @disabled_agents = agents.inactive agents = agents.active if params[:exclude_disabled].present? @agents = agents.includes(:receivers, :control_targets) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/scenarios_controller.rb
app/controllers/scenarios_controller.rb
require 'agents_exporter' class ScenariosController < ApplicationController include SortableTable skip_before_action :authenticate_user!, only: :export def index set_table_sort sorts: %w[name public], default: { name: :asc } @scenarios = current_user.scenarios.reorder(table_sort).page(params[:page]) respond_to do |format| format.html format.json { render json: @scenarios } end end def new @scenario = current_user.scenarios.build respond_to do |format| format.html format.json { render json: @scenario } end end def show @scenario = current_user.scenarios.find(params[:id]) set_table_sort sorts: %w[name last_check_at last_event_at last_receive_at], default: { name: :asc } @agents = @scenario.agents.preload(:scenarios, :controllers).reorder(table_sort).page(params[:page]) respond_to do |format| format.html format.json { render json: @scenario } end end def share @scenario = current_user.scenarios.find(params[:id]) respond_to do |format| format.html format.json { render json: @scenario } end end def export @scenario = Scenario.find(params[:id]) raise ActiveRecord::RecordNotFound unless @scenario.public? || (current_user && current_user.id == @scenario.user_id) @exporter = AgentsExporter.new(name: @scenario.name, description: @scenario.description, guid: @scenario.guid, tag_fg_color: @scenario.tag_fg_color, tag_bg_color: @scenario.tag_bg_color, icon: @scenario.icon, source_url: @scenario.public? && export_scenario_url(@scenario), agents: @scenario.agents) response.headers['Content-Disposition'] = 'attachment; filename="' + @exporter.filename + '"' render :json => JSON.pretty_generate(@exporter.as_json) end def edit @scenario = current_user.scenarios.find(params[:id]) respond_to do |format| format.html format.json { render json: @scenario } end end def create @scenario = current_user.scenarios.build(scenario_params) respond_to do |format| if @scenario.save format.html { redirect_to @scenario, notice: 'This Scenario was successfully created.' } format.json { render json: @scenario, status: :created, location: @scenario } else format.html { render action: "new" } format.json { render json: @scenario.errors, status: :unprocessable_entity } end end end def update @scenario = current_user.scenarios.find(params[:id]) respond_to do |format| if @scenario.update(scenario_params) format.html { redirect_to @scenario, notice: 'This Scenario was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @scenario.errors, status: :unprocessable_entity } end end end def enable_or_disable_all_agents @scenario = current_user.scenarios.find(params[:id]) @scenario.agents.update_all(disabled: params[:scenario][:disabled] == 'true') respond_to do |format| format.html { redirect_to @scenario, notice: 'The agents in this scenario have been successfully updated.' } format.json { head :no_content } end end def destroy @scenario = current_user.scenarios.find(params[:id]) @scenario.destroy_with_mode(params[:mode]) respond_to do |format| format.html { redirect_to scenarios_path } format.json { head :no_content } end end private def scenario_params params.require(:scenario).permit(:name, :description, :public, :source_url, :tag_fg_color, :tag_bg_color, :icon, agent_ids: []) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/jobs_controller.rb
app/controllers/jobs_controller.rb
class JobsController < ApplicationController before_action :authenticate_admin! def index @jobs = Delayed::Job.order(Arel.sql("coalesce(failed_at,'1000-01-01'), run_at asc")).page(params[:page]) respond_to do |format| format.html { render layout: !request.xhr? } format.json { render json: @jobs } end end def destroy @job = Delayed::Job.find(params[:id]) respond_to do |format| if !running? && @job.destroy format.html { redirect_to jobs_path, notice: "Job deleted." } format.json { head :no_content } else format.html { redirect_to jobs_path, alert: 'Can not delete a running job.' } format.json { render json: @job.errors, status: :unprocessable_entity } end end end def run @job = Delayed::Job.find(params[:id]) @job.last_error = nil respond_to do |format| if !running? && @job.update!(run_at: Time.now, failed_at: nil) format.html { redirect_to jobs_path, notice: "Job enqueued." } format.json { render json: @job, status: :ok } else format.html { redirect_to jobs_path, alert: 'Can not enqueue a running job.' } format.json { render json: @job.errors, status: :unprocessable_entity } end end end def retry_queued @jobs = Delayed::Job.awaiting_retry.update_all(run_at: Time.zone.now) respond_to do |format| format.html { redirect_to jobs_path, notice: "Queued jobs getting retried." } format.json { head :no_content } end end def destroy_failed Delayed::Job.where.not(failed_at: nil).delete_all respond_to do |format| format.html { redirect_to jobs_path, notice: "Failed jobs removed." } format.json { head :no_content } end end def destroy_all Delayed::Job.where(locked_at: nil).delete_all respond_to do |format| format.html { redirect_to jobs_path, notice: "All jobs removed." } format.json { head :no_content } end end private def running? (@job.locked_at || @job.locked_by) && @job.failed_at.nil? end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/web_requests_controller.rb
app/controllers/web_requests_controller.rb
# This controller is designed to allow your Agents to receive cross-site Webhooks (POSTs), or to output data streams. # When a POST or GET is received, your Agent will have #receive_web_request called on itself with the incoming params, # method, and requested content-type. # # Requests are routed as follows: # http://yourserver.com/users/:user_id/web_requests/:agent_id/:secret # where :user_id is a User's id, :agent_id is an Agent's id, and :secret is a token that should be user-specifiable in # an Agent that implements #receive_web_request. It is highly recommended that every Agent verify this token whenever # #receive_web_request is called. For example, one of your Agent's options could be :secret and you could compare this # value to params[:secret] whenever #receive_web_request is called on your Agent, rejecting invalid requests. # # Your Agent's #receive_web_request method should return an Array of json_or_string_response, status_code, # optional mime type, and optional hash of custom response headers. For example: # [{status: "success"}, 200] # or # ["not found", 404, 'text/plain'] # or # ["<status>success</status>", 200, 'text/xml', {"Access-Control-Allow-Origin" => "*"}] class WebRequestsController < ApplicationController skip_before_action :verify_authenticity_token skip_before_action :authenticate_user! wrap_parameters false def handle_request user = User.find_by_id(params[:user_id]) if user agent = user.agents.find_by_id(params[:agent_id]) if agent content, status, content_type, headers = agent.trigger_web_request(request) if headers.present? headers.each do |k, v| response.headers[k] = v end end status ||= 200 if status.to_s.in?(%w[301 302]) redirect_to(content, allow_other_host: true, status:) elsif content.is_a?(String) render plain: content, status:, content_type: content_type || 'text/plain' elsif content.is_a?(Hash) render(json: content, status:) else head(status) end else render plain: 'agent not found', status: 404 end else render plain: 'user not found', status: 404 end end # legacy def update_location if user = User.find_by_id(params[:user_id]) secret = params[:secret] user.agents.of_type(Agents::UserLocationAgent).each do |agent| agent.trigger_web_request(request) if agent.options[:secret] == secret end render plain: 'ok' else render plain: 'user not found', status: :not_found end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/home_controller.rb
app/controllers/home_controller.rb
class HomeController < ApplicationController skip_before_action :authenticate_user! before_action :upgrade_warning, only: :index def index end def about end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/omniauth_callbacks_controller.rb
app/controllers/omniauth_callbacks_controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController def action_missing(name) case name.to_sym when *Devise.omniauth_providers service = current_user.services.initialize_or_update_via_omniauth(request.env['omniauth.auth']) if service && service.save redirect_to services_path, notice: "The service was successfully created." else redirect_to services_path, error: "Error creating the service." end else raise ActionController::RoutingError, 'not found' end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/logs_controller.rb
app/controllers/logs_controller.rb
class LogsController < ApplicationController before_action :load_agent def index @logs = @agent.logs.all render :action => :index, :layout => false end def clear @agent.delete_logs! index end protected def load_agent @agent = current_user.agents.find(params[:agent_id]) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/user_credentials_controller.rb
app/controllers/user_credentials_controller.rb
class UserCredentialsController < ApplicationController include SortableTable def index set_table_sort sorts: %w[credential_name credential_value], default: { credential_name: :asc } @user_credentials = current_user.user_credentials.reorder(table_sort).page(params[:page]) respond_to do |format| format.html format.json { send_data Utils.pretty_jsonify(@user_credentials.limit(nil).as_json), disposition: 'attachment' } end end def import if params[:file] file = params[:file] content = JSON.parse(file.read) new_credentials = content.map do |hash| current_user.user_credentials.build(hash.slice("credential_name", "credential_value", "mode")) end respond_to do |format| if new_credentials.map(&:save).all? format.html { redirect_to user_credentials_path, notice: "The file was successfully uploaded."} else format.html { redirect_to user_credentials_path, notice: 'One or more of the uploaded credentials was not imported due to an error. Perhaps an existing credential had the same name?'} end end else redirect_to user_credentials_path, notice: "No file was chosen to be uploaded." end end def new @user_credential = current_user.user_credentials.build respond_to do |format| format.html format.json { render json: @user_credential } end end def edit @user_credential = current_user.user_credentials.find(params[:id]) end def create @user_credential = current_user.user_credentials.build(user_credential_params) respond_to do |format| if @user_credential.save format.html { redirect_to user_credentials_path, notice: 'Your credential was successfully created.' } format.json { render json: @user_credential, status: :created, location: @user_credential } else format.html { render action: "new" } format.json { render json: @user_credential.errors, status: :unprocessable_entity } end end end def update @user_credential = current_user.user_credentials.find(params[:id]) respond_to do |format| if @user_credential.update(user_credential_params) format.html { redirect_to user_credentials_path, notice: 'Your credential was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @user_credential.errors, status: :unprocessable_entity } end end end def destroy @user_credential = current_user.user_credentials.find(params[:id]) @user_credential.destroy respond_to do |format| format.html { redirect_to user_credentials_path } format.json { head :no_content } end end private def user_credential_params params.require(:user_credential).permit(:credential_name, :credential_value, :mode) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/scenario_imports_controller.rb
app/controllers/scenario_imports_controller.rb
class ScenarioImportsController < ApplicationController def new @scenario_import = ScenarioImport.new(:url => params[:url]) end def create @scenario_import = ScenarioImport.new(scenario_import_params) @scenario_import.set_user(current_user) if @scenario_import.valid? && @scenario_import.import_confirmed? && @scenario_import.import redirect_to @scenario_import.scenario, notice: "Import successful!" else render action: "new" end end private def scenario_import_params params.require(:scenario_import).permit(:url, :data, :file, :do_import, merges: {}) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/events_controller.rb
app/controllers/events_controller.rb
class EventsController < ApplicationController before_action :load_event, except: [:index, :show] def index if params[:agent_id] @agent = current_user.agents.find(params[:agent_id]) @events = @agent.events.page(params[:page]) else @events = current_user.events.preload(:agent).page(params[:page]) end respond_to do |format| format.html format.json { render json: @events } end end def show respond_to do |format| format.html do load_event rescue ActiveRecord::RecordNotFound return_to = params[:return] or raise redirect_to return_to, allow_other_host: false end format.json { render json: @event } end end def reemit @event.reemit! respond_to do |format| format.html { redirect_back event_path(@event), notice: 'Event re-emitted.' } end end def destroy @event.destroy respond_to do |format| format.html { redirect_back events_path, notice: 'Event deleted.' } format.json { head :no_content } end end private def load_event @event = current_user.events.find(params[:id]) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/agents_controller.rb
app/controllers/agents_controller.rb
class AgentsController < ApplicationController include DotHelper include ActionView::Helpers::TextHelper include SortableTable def index set_table_sort sorts: %w[name created_at last_check_at last_event_at last_receive_at], default: { created_at: :desc } @agents = current_user.agents.preload(:scenarios, :controllers).reorder(table_sort).page(params[:page]) if show_only_enabled_agents? @agents = @agents.where(disabled: false) end respond_to do |format| format.html format.json { render json: @agents } end end def toggle_visibility if show_only_enabled_agents? mark_all_agents_viewable else set_only_enabled_agents_as_viewable end redirect_to agents_path end def handle_details_post @agent = current_user.agents.find(params[:id]) if @agent.respond_to?(:handle_details_post) render :json => @agent.handle_details_post(params) || {} else @agent.error "#handle_details_post called on an instance of #{@agent.class} that does not define it." head 500 end end def run @agent = current_user.agents.find(params[:id]) Agent.async_check(@agent.id) respond_to do |format| format.html { redirect_back "Agent run queued for '#{@agent.name}'" } format.json { head :ok } end end def type_details @agent = Agent.build_for_type(params[:type], current_user, {}) initialize_presenter render json: { can_be_scheduled: @agent.can_be_scheduled?, default_schedule: @agent.default_schedule, can_receive_events: @agent.can_receive_events?, can_create_events: @agent.can_create_events?, can_control_other_agents: @agent.can_control_other_agents?, can_dry_run: @agent.can_dry_run?, options: @agent.default_options, description_html: @agent.html_description, oauthable: render_to_string(partial: 'oauth_dropdown', locals: { agent: @agent }), form_options: render_to_string(partial: 'options', locals: { agent: @agent }) } end def event_descriptions html = current_user.agents.find(params[:ids].split(",")).group_by(&:type).map { |type, agents| agents.map(&:html_event_description).uniq.map { |desc| "<p><strong>#{type}</strong><br />" + desc + "</p>" } }.flatten.join() render :json => { :description_html => html } end def reemit_events @agent = current_user.agents.find(params[:id]) AgentReemitJob.perform_later(@agent, @agent.most_recent_event.id, params[:delete_old_events] == '1') if @agent.most_recent_event respond_to do |format| format.html { redirect_back "Enqueued job to re-emit all events for '#{@agent.name}'" } format.json { head :ok } end end def remove_events @agent = current_user.agents.find(params[:id]) @agent.events.delete_all respond_to do |format| format.html { redirect_back "All emitted events removed for '#{@agent.name}'" } format.json { head :ok } end end def propagate respond_to do |format| if AgentPropagateJob.can_enqueue? details = Agent.receive! # Eventually this should probably be scoped to the current_user. format.html { redirect_back "Queued propagation calls for #{details[:event_count]} event(s) on #{details[:agent_count]} agent(s)" } format.json { head :ok } else format.html { redirect_back "Event propagation is already scheduled to run." } format.json { head :locked } end end end def destroy_memory @agent = current_user.agents.find(params[:id]) @agent.update!(memory: {}) respond_to do |format| format.html { redirect_back "Memory erased for '#{@agent.name}'" } format.json { head :ok } end end def show @agent = current_user.agents.find(params[:id]) respond_to do |format| format.html format.json { render json: @agent } end end def new agents = current_user.agents if id = params[:id] @agent = agents.build_clone(agents.find(id)) else @agent = agents.build end @agent.scenario_ids = [params[:scenario_id]] if params[:scenario_id] && current_user.scenarios.find_by(id: params[:scenario_id]) initialize_presenter respond_to do |format| format.html format.json { render json: @agent } end end def edit @agent = current_user.agents.find(params[:id]) initialize_presenter end def create build_agent respond_to do |format| if @agent.save format.html { redirect_back "'#{@agent.name}' was successfully created.", return: agents_path } format.json { render json: @agent, status: :ok, location: agent_path(@agent) } else initialize_presenter format.html { render action: "new" } format.json { render json: @agent.errors, status: :unprocessable_entity } end end end def update @agent = current_user.agents.find(params[:id]) respond_to do |format| if @agent.update(agent_params) format.html { redirect_back "'#{@agent.name}' was successfully updated.", return: agents_path } format.json { render json: @agent, status: :ok, location: agent_path(@agent) } else initialize_presenter format.html { render action: "edit" } format.json { render json: @agent.errors, status: :unprocessable_entity } end end end def leave_scenario @agent = current_user.agents.find(params[:id]) @scenario = current_user.scenarios.find(params[:scenario_id]) @agent.scenarios.destroy(@scenario) respond_to do |format| format.html { redirect_back "'#{@agent.name}' removed from '#{@scenario.name}'" } format.json { head :no_content } end end def destroy @agent = current_user.agents.find(params[:id]) @agent.destroy respond_to do |format| format.html { redirect_back "'#{@agent.name}' deleted" } format.json { head :no_content } end end def validate build_agent if @agent.validate_option(params[:attribute]) render plain: 'ok' else render plain: 'error', status: 403 end end def complete build_agent render json: @agent.complete_option(params[:attribute]) end def destroy_undefined current_user.undefined_agents.destroy_all redirect_back "All undefined Agents have been deleted." end protected # Sanitize params[:return] to prevent open redirect attacks, a common security issue. def redirect_back(message, options = {}) if path = filtered_agent_return_link(options) redirect_to path, notice: message else super agents_path, notice: message end end def build_agent @agent = Agent.build_for_type(agent_params[:type], current_user, agent_params.except(:type)) end def initialize_presenter if @agent.present? && @agent.is_form_configurable? @agent = FormConfigurableAgentPresenter.new(@agent, view_context) end end private def show_only_enabled_agents? !!cookies[:huginn_view_only_enabled_agents] end def set_only_enabled_agents_as_viewable cookies[:huginn_view_only_enabled_agents] = { value: "true", expires: 1.year.from_now } end def mark_all_agents_viewable cookies.delete(:huginn_view_only_enabled_agents) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/services_controller.rb
app/controllers/services_controller.rb
class ServicesController < ApplicationController include SortableTable before_action :upgrade_warning, only: :index def index set_table_sort sorts: %w[provider name global], default: { provider: :asc } @services = current_user.services.reorder(table_sort).page(params[:page]) respond_to do |format| format.html format.json { render json: @services } end end def destroy @services = current_user.services.find(params[:id]) @services.destroy respond_to do |format| format.html { redirect_to services_path } format.json { head :no_content } end end def toggle_availability @service = current_user.services.find(params[:id]) @service.toggle_availability! respond_to do |format| format.html { redirect_to services_path } format.json { render json: @service } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/worker_status_controller.rb
app/controllers/worker_status_controller.rb
class WorkerStatusController < ApplicationController def show start = Time.now events = current_user.events if params[:since_id].present? since_id = params[:since_id].to_i events = events.where('id > ?', since_id) end result = events.select('COUNT(id) AS count', 'MIN(id) AS min_id', 'MAX(id) AS max_id').reorder(Arel.sql('min(created_at)')).first count, min_id, max_id = result.count, result.min_id, result.max_id case max_id when nil when min_id events_url = events_path(hl: max_id) else events_url = events_path(hl: "#{min_id}-#{max_id}") end render json: { pending: Delayed::Job.pending.where("run_at <= ?", start).count, awaiting_retry: Delayed::Job.awaiting_retry.count, recent_failures: Delayed::Job.failed_jobs.where('failed_at > ?', 5.days.ago).count, event_count: count, max_id: max_id || 0, events_url: events_url, compute_time: Time.now - start } end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/application_controller.rb
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? helper :all rescue_from 'ActiveRecord::SubclassNotFound' do @undefined_agent_types = current_user.undefined_agent_types render template: 'application/undefined_agents' end def redirect_back(fallback_path, **args) super(fallback_location: fallback_path, allow_other_host: false, **args) end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :email, :password, :password_confirmation, :remember_me, :invitation_code]) devise_parameter_sanitizer.permit(:sign_in, keys: [:login, :username, :email, :password, :remember_me]) devise_parameter_sanitizer.permit(:account_update, keys: [:username, :email, :password, :password_confirmation, :current_password]) end def authenticate_admin! redirect_to(root_path, alert: 'Admin access required to view that page.') unless current_user && current_user.admin? end def upgrade_warning return unless current_user twitter_oauth_check outdated_docker_registry_check outdated_google_auth_check end def filtered_agent_return_link(options = {}) case ret = params[:return].presence || options[:return] when "show" if @agent && !@agent.destroyed? agent_path(@agent) else agents_path end when /\A#{(Regexp::escape scenarios_path)}/, /\A#{(Regexp::escape agents_path)}/, /\A#{(Regexp::escape events_path)}/ ret end end helper_method :filtered_agent_return_link private def twitter_oauth_check unless Devise.omniauth_providers.include?(:twitter) if @twitter_agent = current_user.agents.where("type like 'Agents::Twitter%'").first @twitter_oauth_key = @twitter_agent.options['consumer_key'].presence || @twitter_agent.credential('twitter_consumer_key') @twitter_oauth_secret = @twitter_agent.options['consumer_secret'].presence || @twitter_agent.credential('twitter_consumer_secret') end end end def outdated_docker_registry_check @outdated_docker_registry = ENV['OUTDATED_DOCKER_REGISTRY'] == 'true' end def outdated_google_auth_check @outdated_google_cal_agents = current_user.agents.of_type('Agents::GoogleCalendarPublishAgent').select do |agent| agent.options['google']['key_secret'].present? end end def agent_params return {} unless params[:agent] @agent_params ||= begin params[:agent].permit([:memory, :name, :type, :schedule, :disabled, :keep_events_for, :propagate_immediately, :drop_pending_events, :service_id, source_ids: [], receiver_ids: [], scenario_ids: [], controller_ids: [], control_target_ids: []] + agent_params_options) end end private def agent_params_options if params[:agent].fetch(:options, '').kind_of?(ActionController::Parameters) [options: {}] else [:options] end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/concerns/sortable_table.rb
app/controllers/concerns/sortable_table.rb
require 'active_support/concern' module SortableTable extend ActiveSupport::Concern included do helper SortableTableHelper end protected def table_sort raise("You must call set_table_sort in any action using table_sort.") unless @table_sort_info.present? @table_sort_info[:order] end def set_table_sort(sort_options) valid_sorts = sort_options[:sorts] or raise ArgumentError.new("You must specify :sorts as an array of valid sort attributes.") default = sort_options[:default] || { valid_sorts.first.to_sym => :desc } if params[:sort].present? attribute, direction = params[:sort].downcase.split('.') unless valid_sorts.include?(attribute) attribute, direction = default.to_a.first end else attribute, direction = default.to_a.first end direction = direction.to_s == 'desc' ? 'desc' : 'asc' @table_sort_info = { order: { attribute.to_sym => direction.to_sym }, attribute: attribute, direction: direction } end module SortableTableHelper # :call-seq: # sortable_column(attribute, default_direction = 'desc', name: attribute.humanize) def sortable_column(attribute, default_direction = nil, options = nil) if options.nil? && (options = Hash.try_convert(default_direction)) default_direction = nil end default_direction ||= 'desc' options ||= {} name = options[:name] || attribute.humanize selected = @table_sort_info[:attribute].to_s == attribute if selected direction = @table_sort_info[:direction] new_direction = direction.to_s == 'desc' ? 'asc' : 'desc' classes = "selected #{direction}" else classes = '' new_direction = default_direction end link_to(name, url_for(sort: "#{attribute}.#{new_direction}"), class: classes) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/agents/dry_runs_controller.rb
app/controllers/agents/dry_runs_controller.rb
module Agents class DryRunsController < ApplicationController include ActionView::Helpers::TextHelper def index @events = if params[:agent_id] current_user.agents.find_by(id: params[:agent_id]).received_events.limit(5) elsif params[:source_ids] Event.where(agent_id: current_user.agents.where(id: params[:source_ids]).pluck(:id)) .order("id DESC").limit(5) else [] end render layout: false end def create attrs = agent_params if agent = current_user.agents.find_by(id: params[:agent_id]) # POST /agents/:id/dry_run if attrs.present? attrs = attrs.merge(memory: agent.memory) type = agent.type agent = Agent.build_for_type(type, current_user, attrs) end else # POST /agents/dry_run type = attrs.delete(:type) agent = Agent.build_for_type(type, current_user, attrs) end agent.name ||= '(Untitled)' if agent.valid? if event_payload = params[:event] dummy_agent = Agent.build_for_type('ManualEventAgent', current_user, name: 'Dry-Runner') dummy_agent.readonly! event = dummy_agent.events.build(user: current_user, payload: event_payload, created_at: Time.now) end @results = agent.dry_run!(event) else @results = { events: [], memory: [], log: [ "#{pluralize(agent.errors.count, "error")} prohibited this Agent from being saved:", *agent.errors.full_messages ].join("\n- ") } end render layout: false end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/admin/users_controller.rb
app/controllers/admin/users_controller.rb
class Admin::UsersController < ApplicationController before_action :authenticate_admin!, except: [:switch_back] before_action :find_user, only: [:edit, :destroy, :update, :deactivate, :activate, :switch_to_user] helper_method :resource def index @users = User.reorder('created_at DESC').page(params[:page]) respond_to do |format| format.html format.json { render json: @users } end end def new @user = User.new end def create @user = User.new(user_params) @user.requires_no_invitation_code! respond_to do |format| if @user.save DefaultScenarioImporter.import(@user) format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was successfully created." } format.json { render json: @user, status: :ok, location: admin_users_path(@user) } else format.html { render action: 'new' } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def edit end def update params[:user].extract!(:password, :password_confirmation) if params[:user][:password].blank? @user.assign_attributes(user_params) respond_to do |format| if @user.save format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was successfully updated." } format.json { render json: @user, status: :ok, location: admin_users_path(@user) } else format.html { render action: 'edit' } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def destroy @user.destroy respond_to do |format| format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was deleted." } format.json { head :no_content } end end def deactivate @user.deactivate! respond_to do |format| format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was deactivated." } format.json { render json: @user, status: :ok, location: admin_users_path(@user) } end end def activate @user.activate! respond_to do |format| format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was activated." } format.json { render json: @user, status: :ok, location: admin_users_path(@user) } end end # allow an admin to sign-in as any other user def switch_to_user if current_user != @user old_user = current_user bypass_sign_in(@user) session[:original_admin_user_id] = old_user.id end redirect_to agents_path end def switch_back if session[:original_admin_user_id].present? bypass_sign_in(User.find(session[:original_admin_user_id])) session.delete(:original_admin_user_id) else redirect_to(root_path, alert: 'You must be an admin acting as a different user to do that.') and return end redirect_to admin_users_path end private def user_params params.require(:user).permit(:email, :username, :password, :password_confirmation, :admin) end def find_user @user = User.find(params[:id]) end def resource @user end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/controllers/users/registrations_controller.rb
app/controllers/users/registrations_controller.rb
module Users class RegistrationsController < Devise::RegistrationsController after_action :create_default_scenario, only: :create private def create_default_scenario DefaultScenarioImporter.import(@user) if @user.persisted? end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agent.rb
app/models/agent.rb
require 'utils' # Agent is the core class in Huginn, representing a configurable, schedulable, reactive system with memory that can # be sub-classed for many different purposes. Agents can emit Events, as well as receive them and react in many different ways. # The basic Agent API is detailed on the Huginn wiki: https://github.com/huginn/huginn/wiki/Creating-a-new-agent class Agent < ActiveRecord::Base include AssignableTypes include MarkdownClassAttributes include JsonSerializedField include RdbmsFunctions include WorkingHelpers include LiquidInterpolatable include HasGuid include DryRunnable include SortableEvents markdown_class_attributes :description, :event_description load_types_in "Agents" SCHEDULES = %w[ every_1m every_2m every_5m every_10m every_30m every_1h every_2h every_5h every_12h every_1d every_2d every_7d midnight 1am 2am 3am 4am 5am 6am 7am 8am 9am 10am 11am noon 1pm 2pm 3pm 4pm 5pm 6pm 7pm 8pm 9pm 10pm 11pm never ] EVENT_RETENTION_SCHEDULES = [ ["Forever", 0], ['1 hour', 1.hour], ['6 hours', 6.hours], ["1 day", 1.day], *( [2, 3, 4, 5, 7, 14, 21, 30, 45, 90, 180, 365].map { |n| ["#{n} days", n.days] } ) ] json_serialize :options, :memory validates_presence_of :name, :user validates_inclusion_of :keep_events_for, in: EVENT_RETENTION_SCHEDULES.map(&:last) validates :sources, owned_by: :user_id validates :receivers, owned_by: :user_id validates :controllers, owned_by: :user_id validates :control_targets, owned_by: :user_id validates :scenarios, owned_by: :user_id validate :validate_schedule validate :validate_options after_initialize :set_default_schedule before_validation :set_default_schedule before_validation :unschedule_if_cannot_schedule before_save :unschedule_if_cannot_schedule before_create :set_last_checked_event_id after_save :possibly_update_event_expirations belongs_to :user, inverse_of: :agents belongs_to :service, inverse_of: :agents, optional: true has_many :events, -> { order("events.id desc") }, dependent: :delete_all, inverse_of: :agent has_one :most_recent_event, -> { order("events.id desc") }, inverse_of: :agent, class_name: "Event" has_many :logs, -> { order("agent_logs.id desc") }, dependent: :delete_all, inverse_of: :agent, class_name: "AgentLog" has_many :links_as_source, dependent: :delete_all, foreign_key: "source_id", class_name: "Link", inverse_of: :source has_many :links_as_receiver, dependent: :delete_all, foreign_key: "receiver_id", class_name: "Link", inverse_of: :receiver has_many :sources, through: :links_as_receiver, class_name: "Agent", inverse_of: :receivers has_many :received_events, -> { order("events.id desc") }, through: :sources, class_name: "Event", source: :events has_many :receivers, through: :links_as_source, class_name: "Agent", inverse_of: :sources has_many :control_links_as_controller, dependent: :delete_all, foreign_key: 'controller_id', class_name: 'ControlLink', inverse_of: :controller has_many :control_links_as_control_target, dependent: :delete_all, foreign_key: 'control_target_id', class_name: 'ControlLink', inverse_of: :control_target has_many :controllers, through: :control_links_as_control_target, class_name: "Agent", inverse_of: :control_targets has_many :control_targets, through: :control_links_as_controller, class_name: "Agent", inverse_of: :controllers has_many :scenario_memberships, dependent: :destroy, inverse_of: :agent has_many :scenarios, through: :scenario_memberships, inverse_of: :agents scope :active, -> { where(disabled: false, deactivated: false) } scope :inactive, -> { where(disabled: true).or(where(deactivated: true)) } scope :of_type, ->(type) { case type when Agent where(type: type.class.to_s) else where(type: type.to_s) end } def short_type type.demodulize end def check # Implement me in your subclass of Agent. end def default_options # Implement me in your subclass of Agent. {} end def receive(events) # Implement me in your subclass of Agent. end def is_form_configurable? false end def receive_web_request(params, method, format) # Implement me in your subclass of Agent. ["not implemented", 404, "text/plain", {}] # last two elements in response array are optional end # alternate method signature for receive_web_request # def receive_web_request(request=ActionDispatch::Request.new( ... )) # end # Implement me in your subclass to decide if your Agent is working. def working? raise "Implement me in your subclass" end def build_event(event) event = events.build(event) if event.is_a?(Hash) event.agent = self event.user = user event.expires_at ||= new_event_expiration_date event end def create_event(event) if can_create_events? event = build_event(event) event.save! event else error "This Agent cannot create events!" end end def credential(name) @credential_cache ||= {} if @credential_cache.has_key?(name) @credential_cache[name] else @credential_cache[name] = user.user_credentials.where(credential_name: name).first.try(:credential_value) end end def reload(...) @credential_cache = {} super end def new_event_expiration_date keep_events_for > 0 ? keep_events_for.seconds.from_now : nil end def update_event_expirations! if keep_events_for == 0 events.update_all expires_at: nil else events.update_all "expires_at = " + rdbms_date_add("created_at", "SECOND", keep_events_for.to_i) end end def trigger_web_request(request) params = request.params.except(:action, :controller, :agent_id, :user_id, :format) if respond_to?(:receive_webhook) Rails.logger.warn "DEPRECATED: The .receive_webhook method is deprecated, please switch your Agent to use .receive_web_request." receive_webhook(params).tap do self.last_web_request_at = Time.now save! end else handled_request = if method(:receive_web_request).arity == 1 receive_web_request(request) else receive_web_request(params, request.method_symbol.to_s, request.format.to_s) end handled_request.tap do self.last_web_request_at = Time.now save! end end end def unavailable? disabled? || dependencies_missing? end def dependencies_missing? self.class.dependencies_missing? end def default_schedule self.class.default_schedule end def cannot_be_scheduled? self.class.cannot_be_scheduled? end def can_be_scheduled? !cannot_be_scheduled? end def cannot_receive_events? self.class.cannot_receive_events? end def can_receive_events? !cannot_receive_events? end def cannot_create_events? self.class.cannot_create_events? end def can_create_events? !cannot_create_events? end def can_control_other_agents? self.class.can_control_other_agents? end def can_dry_run? self.class.can_dry_run? end def no_bulk_receive? self.class.no_bulk_receive? end def log(message, options = {}) AgentLog.log_for_agent(self, message, options.merge(inbound_event: current_event)) end def error(message, options = {}) log(message, options.merge(level: 4)) end def delete_logs! logs.delete_all update_column :last_error_log_at, nil end def drop_pending_events false end def drop_pending_events=(bool) set_last_checked_event_id if bool end # Callbacks def set_default_schedule self.schedule = default_schedule unless schedule.present? || cannot_be_scheduled? end def unschedule_if_cannot_schedule self.schedule = nil if cannot_be_scheduled? end def set_last_checked_event_id if can_receive_events? && newest_event_id = Event.maximum(:id) self.last_checked_event_id = newest_event_id end end def possibly_update_event_expirations update_event_expirations! if saved_change_to_keep_events_for? end # Validation Methods private attr_accessor :current_event def validate_schedule unless cannot_be_scheduled? errors.add(:schedule, "is not a valid schedule") unless SCHEDULES.include?(schedule.to_s) end end def validate_options # Implement me in your subclass to test for valid options. end # Utility Methods def boolify(option_value) case option_value when true, 'true' true when false, 'false' false else nil end end def is_positive_integer?(value) Integer(value) >= 0 rescue StandardError false end # Class Methods class << self def build_clone(original) new(original.slice( :type, :options, :service_id, :schedule, :controller_ids, :control_target_ids, :source_ids, :receiver_ids, :keep_events_for, :propagate_immediately, :scenario_ids )) { |clone| # Give it a unique name 2.step do |i| name = '%s (%d)' % [original.name, i] unless exists?(name:) clone.name = name break end end } end def cannot_be_scheduled! @cannot_be_scheduled = true end def cannot_be_scheduled? !!@cannot_be_scheduled end def default_schedule(schedule = nil) @default_schedule = schedule unless schedule.nil? @default_schedule end def cannot_create_events! @cannot_create_events = true end def cannot_create_events? !!@cannot_create_events end def cannot_receive_events! @cannot_receive_events = true end def cannot_receive_events? !!@cannot_receive_events end def can_control_other_agents! @can_control_other_agents = true end def can_control_other_agents? !!@can_control_other_agents end def can_dry_run! @can_dry_run = true end def can_dry_run? !!@can_dry_run end def no_bulk_receive! @no_bulk_receive = true end def no_bulk_receive? !!@no_bulk_receive end def gem_dependency_check @gem_dependencies_checked = true @gem_dependencies_met = yield end def dependencies_missing? @gem_dependencies_checked && !@gem_dependencies_met end # Find all Agents that have received Events since the last execution of this method. Update those Agents with # their new `last_checked_event_id` and queue each of the Agents to be called with #receive using `async_receive`. # This is called by bin/schedule.rb periodically. def receive!(options = {}) Agent.transaction do scope = Agent .select("agents.id AS receiver_agent_id, sources.type AS source_agent_type, agents.type AS receiver_agent_type, events.id AS event_id") .joins("JOIN links ON (links.receiver_id = agents.id)") .joins("JOIN agents AS sources ON (links.source_id = sources.id)") .joins("JOIN events ON (events.agent_id = sources.id AND events.id > links.event_id_at_creation)") .where("NOT agents.disabled AND NOT agents.deactivated AND (agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id)") if options[:only_receivers].present? scope = scope.where("agents.id in (?)", options[:only_receivers]) end sql = scope.to_sql agents_to_events = {} Agent.connection.select_rows(sql).each do |receiver_agent_id, source_agent_type, receiver_agent_type, event_id| begin Object.const_get(source_agent_type) Object.const_get(receiver_agent_type) rescue NameError next end agents_to_events[receiver_agent_id.to_i] ||= [] agents_to_events[receiver_agent_id.to_i] << event_id end Agent.where(id: agents_to_events.keys).each do |agent| event_ids = agents_to_events[agent.id].uniq agent.update_attribute :last_checked_event_id, event_ids.max if agent.no_bulk_receive? event_ids.each { |event_id| Agent.async_receive(agent.id, [event_id]) } else Agent.async_receive(agent.id, event_ids) end end { agent_count: agents_to_events.keys.length, event_count: agents_to_events.values.flatten.uniq.compact.length } end end # This method will enqueue an AgentReceiveJob job. It accepts Agent and Event ids instead of a literal ActiveRecord # models because it is preferable to serialize jobs with ids. def async_receive(agent_id, event_ids) AgentReceiveJob.perform_later(agent_id, event_ids) end # Given a schedule name, run `check` via `bulk_check` on all Agents with that schedule. # This is called by bin/schedule.rb for each schedule in `SCHEDULES`. def run_schedule(schedule) return if schedule == 'never' types = where(schedule:).group(:type).pluck(:type) types.each do |type| next unless valid_type?(type) type.constantize.bulk_check(schedule) end end # Schedule `async_check`s for every Agent on the given schedule. This is normally called by `run_schedule` once # per type of agent, so you can override this to define custom bulk check behavior for your custom Agent type. def bulk_check(schedule) raise "Call #bulk_check on the appropriate subclass of Agent" if self == Agent where("NOT disabled AND NOT deactivated AND schedule = ?", schedule).pluck("agents.id").each do |agent_id| async_check(agent_id) end end # This method will enqueue an AgentCheckJob job. It accepts an Agent id instead of a literal Agent because it is # preferable to serialize job with ids, instead of with the full Agents. def async_check(agent_id) AgentCheckJob.perform_later(agent_id) end end public def to_liquid Drop.new(self) end class Drop < LiquidDroppable::Drop def type @object.short_type end METHODS = %i[ id name type options memory sources receivers schedule controllers control_targets disabled keep_events_for propagate_immediately ] METHODS.each { |attr| define_method(attr) { @object.__send__(attr) } unless method_defined?(attr) } def working @object.working? end def url Rails.application.routes.url_helpers.agent_url( @object, Rails.application.config.action_mailer.default_url_options ) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/event.rb
app/models/event.rb
require 'location' # Events are how Huginn Agents communicate and log information about the world. Events can be emitted and received by # Agents. They contain a serialized `payload` of arbitrary JSON data, as well as optional `lat`, `lng`, and `expires_at` # fields. class Event < ActiveRecord::Base include JsonSerializedField include LiquidDroppable acts_as_mappable json_serialize :payload belongs_to :user, optional: true belongs_to :agent, counter_cache: true has_many :agent_logs_as_inbound_event, class_name: "AgentLog", foreign_key: :inbound_event_id, dependent: :nullify has_many :agent_logs_as_outbound_event, class_name: "AgentLog", foreign_key: :outbound_event_id, dependent: :nullify scope :recent, lambda { |timespan = 12.hours.ago| where("events.created_at > ?", timespan) } after_create :update_agent_last_event_at after_create :possibly_propagate scope :expired, lambda { where("expires_at IS NOT NULL AND expires_at < ?", Time.now) } case ActiveRecord::Base.connection.adapter_name when /\Amysql/i # Protect the Event table from InnoDB's AUTO_INCREMENT Counter # Initialization by always keeping the latest event. scope :to_expire, -> { expired.where.not(id: maximum(:id)) } else scope :to_expire, -> { expired } end scope :with_location, -> { where.not(lat: nil).where.not(lng: nil) } def location @location ||= Location.new( # lat and lng are BigDecimal, but converted to Float by the Location class lat:, lng:, radius: if (h = payload[:horizontal_accuracy].presence) && (v = payload[:vertical_accuracy].presence) (h.to_f + v.to_f) / 2 else (h || v || payload[:accuracy]).to_f end, course: payload[:course], speed: payload[:speed].presence ) end def location=(location) case location when nil self.lat = self.lng = nil return when Location else location = Location.new(location) end self.lat = location.lat self.lng = location.lng location end # Emit this event again, as a new Event. def reemit! agent.create_event(payload:, lat:, lng:) end # Look for Events whose `expires_at` is present and in the past. Remove those events and then update affected Agents' # `events_counts` cache columns. This method is called by bin/schedule.rb periodically. def self.cleanup_expired! transaction do affected_agents = Event.expired.group("agent_id").pluck(:agent_id) Event.to_expire.delete_all Agent.where(id: affected_agents).update_all "events_count = (select count(*) from events where agent_id = agents.id)" end end protected def update_agent_last_event_at agent.touch :last_event_at end def possibly_propagate # immediately schedule agents that want immediate updates propagate_ids = agent.receivers.where(propagate_immediately: true).pluck(:id) Agent.receive!(only_receivers: propagate_ids) unless propagate_ids.empty? end public def to_liquid Drop.new(self) end class Drop < LiquidDroppable::Drop def initialize(object) @payload = object.payload super end def liquid_method_missing(key) @payload[key] end def each(&block) @payload.each(&block) end def agent @payload.fetch(__method__) { @object.agent } end def created_at @payload.fetch(__method__) { @object.created_at } end def _location_ @object.location end def as_json { location: _location_.as_json, agent: @object.agent.to_liquid.as_json, payload: @payload.as_json, created_at: created_at.as_json } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/scenario.rb
app/models/scenario.rb
class Scenario < ActiveRecord::Base include HasGuid belongs_to :user, counter_cache: :scenario_count, inverse_of: :scenarios has_many :scenario_memberships, dependent: :destroy, inverse_of: :scenario has_many :agents, through: :scenario_memberships, inverse_of: :scenarios validates_presence_of :name, :user validates_format_of :tag_fg_color, :tag_bg_color, # Regex adapted from: http://stackoverflow.com/a/1636354/3130625 with: /\A#(?:[0-9a-fA-F]{3}){1,2}\z/, allow_nil: true, message: "must be a valid hex color." validate :agents_are_owned def destroy_with_mode(mode) case mode when 'all_agents' Agent.destroy(agents.pluck(:id)) when 'unique_agents' Agent.destroy(unique_agent_ids) end destroy end def self.icons @icons ||= YAML.load_file(Rails.root.join('config/icons.yml')) end private def unique_agent_ids agents.joins(:scenario_memberships) .group('scenario_memberships.agent_id') .having('count(scenario_memberships.agent_id) = 1') .pluck('scenario_memberships.agent_id') end def agents_are_owned unless agents.all? { |s| s.user == user } errors.add(:agents, 'must be owned by you') end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/control_link.rb
app/models/control_link.rb
# A ControlLink connects Agents in a control flow from the `controller` to the `control_target`. class ControlLink < ActiveRecord::Base belongs_to :controller, class_name: 'Agent', inverse_of: :control_links_as_controller belongs_to :control_target, class_name: 'Agent', inverse_of: :control_links_as_control_target end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agent_log.rb
app/models/agent_log.rb
# AgentLogs are temporary records of Agent activity, intended for debugging and error tracking. They can be viewed # in Agents' detail pages. AgentLogs with a `level` of 4 or greater are considered "errors" and automatically update # Agents' `last_error_log_at` column. These are often used to determine if an Agent is `working?`. class AgentLog < ActiveRecord::Base belongs_to :agent belongs_to :inbound_event, class_name: "Event", optional: true belongs_to :outbound_event, class_name: "Event", optional: true validates_presence_of :message validates_numericality_of :level, only_integer: true, greater_than_or_equal_to: 0, less_than: 5 before_validation :scrub_message before_save :truncate_message def self.log_for_agent(agent, message, options = {}) puts "Agent##{agent.id}: #{message}" unless Rails.env.test? log = agent.logs.create! options.merge(message:) if agent.logs.count > log_length oldest_id_to_keep = agent.logs.limit(1).offset(log_length - 1).pluck("agent_logs.id") agent.logs.where("agent_logs.id < ?", oldest_id_to_keep).delete_all end agent.update_column :last_error_log_at, Time.now if log.level >= 4 log end def self.log_length ENV['AGENT_LOG_LENGTH'].present? ? ENV['AGENT_LOG_LENGTH'].to_i : 200 end protected def scrub_message if message_changed? && !message.nil? self.message = message.inspect unless message.is_a?(String) self.message.scrub! { |bytes| "<#{bytes.unpack1('H*')}>" } end true end def truncate_message self.message = message[0...10_000] if message.present? end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/link.rb
app/models/link.rb
# A Link connects Agents in a directed Event flow from the `source` to the `receiver`. class Link < ActiveRecord::Base belongs_to :source, class_name: "Agent", inverse_of: :links_as_source belongs_to :receiver, class_name: "Agent", inverse_of: :links_as_receiver before_create :store_event_id_at_creation def store_event_id_at_creation self.event_id_at_creation = source.events.limit(1).reorder("id desc").pluck(:id).first || 0 end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/user_credential.rb
app/models/user_credential.rb
class UserCredential < ActiveRecord::Base MODES = %w[text java_script] belongs_to :user validates :credential_name, presence: true, uniqueness: { case_sensitive: true, scope: :user_id } validates :credential_value, presence: true validates :mode, inclusion: { in: MODES } validates :user_id, presence: true before_validation :default_mode_to_text before_save :trim_fields protected def trim_fields credential_name.strip! credential_value.strip! end def default_mode_to_text self.mode = 'text' unless mode.present? end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/scenario_membership.rb
app/models/scenario_membership.rb
class ScenarioMembership < ActiveRecord::Base belongs_to :agent, inverse_of: :scenario_memberships belongs_to :scenario, inverse_of: :scenario_memberships end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/service.rb
app/models/service.rb
class Service < ActiveRecord::Base serialize :options, Hash belongs_to :user, inverse_of: :services has_many :agents, inverse_of: :service validates_presence_of :user_id, :provider, :name, :token before_destroy :disable_agents scope :available_to_user, lambda { |user| where("services.user_id = ? or services.global = true", user.id) } scope :by_name, lambda { |dir = 'desc'| order("services.name #{dir}") } def disable_agents(conditions = {}) agents.where.not(conditions[:where_not] || {}).each do |agent| agent.service_id = nil agent.disabled = true agent.save!(validate: false) end end def toggle_availability! disable_agents(where_not: { user_id: self.user_id }) if global self.global = !self.global self.save! end def prepare_request if expires_at && Time.now > expires_at refresh_token! end end def refresh_token_parameters { grant_type: 'refresh_token', client_id: oauth_key, client_secret: oauth_secret, refresh_token: } end def refresh_token! response = HTTParty.post(endpoint, query: refresh_token_parameters) data = JSON.parse(response.body) update(expires_at: Time.now + data['expires_in'], token: data['access_token'], refresh_token: data['refresh_token'].presence || refresh_token) end def endpoint client_options = Devise.omniauth_configs[provider.to_sym].strategy_class.default_options['client_options'] URI.join(client_options['site'], client_options['token_url']) end def oauth_key (config = Devise.omniauth_configs[provider.to_sym]) && config.args[0] end def oauth_secret (config = Devise.omniauth_configs[provider.to_sym]) && config.args[1] end def self.initialize_or_update_via_omniauth(omniauth) options = get_options(omniauth) find_or_initialize_by(provider: omniauth['provider'], uid: omniauth['uid'].to_s).tap do |service| service.attributes = { token: omniauth['credentials']['token'], secret: omniauth['credentials']['secret'], name: options[:name], refresh_token: omniauth['credentials']['refresh_token'], expires_at: omniauth['credentials']['expires_at'] && Time.at(omniauth['credentials']['expires_at']), options: } end end def self.register_options_provider(provider_name, &block) option_providers[provider_name] = block end def self.get_options(omniauth) option_providers.fetch(omniauth['provider'], option_providers['default']).call(omniauth) end @@option_providers = HashWithIndifferentAccess.new cattr_reader :option_providers register_options_provider('default') do |omniauth| { name: omniauth['info']['nickname'] || omniauth['info']['name'] } end register_options_provider('google') do |omniauth| { email: omniauth['info']['email'], name: "#{omniauth['info']['name']} <#{omniauth['info']['email']}>" } end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/user.rb
app/models/user.rb
# Huginn is designed to be a multi-User system. Users have many Agents (and Events created by those Agents). class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :lockable, :omniauthable, *(:confirmable if ENV['REQUIRE_CONFIRMED_EMAIL'] == 'true') INVITATION_CODES = [ENV['INVITATION_CODE'] || 'try-huginn'] # Virtual attribute for authenticating by either username or email # This is in addition to a real persisted field like 'username' attr_accessor :login validates :username, presence: true, uniqueness: { case_sensitive: false }, format: { with: /\A[a-zA-Z0-9_-]{3,190}\Z/, message: "can only contain letters, numbers, underscores, and dashes, and must be between 3 and 190 characters in length." } validates :invitation_code, inclusion: { in: INVITATION_CODES, message: "is not valid", }, if: -> { !requires_no_invitation_code? && User.using_invitation_code? }, on: :create has_many :user_credentials, dependent: :destroy, inverse_of: :user has_many :events, -> { order("events.created_at desc") }, dependent: :delete_all, inverse_of: :user has_many :agents, -> { order("agents.created_at desc") }, dependent: :destroy, inverse_of: :user has_many :logs, through: :agents, class_name: "AgentLog" has_many :scenarios, inverse_of: :user, dependent: :destroy has_many :services, -> { by_name('asc') }, dependent: :destroy def available_services Service.available_to_user(self).by_name end # Allow users to login via either email or username. def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions).where(["lower(username) = :value OR lower(email) = :value", { value: login.downcase }]).first else where(conditions).first end end def active? !deactivated_at end def deactivate! User.transaction do agents.update_all(deactivated: true) update_attribute(:deactivated_at, Time.now) end end def activate! User.transaction do agents.update_all(deactivated: false) update_attribute(:deactivated_at, nil) end end def active_for_authentication? super && active? end def inactive_message active? ? super : :deactivated_account end def self.using_invitation_code? ENV['SKIP_INVITATION_CODE'] != 'true' end def requires_no_invitation_code! @requires_no_invitation_code = true end def requires_no_invitation_code? !!@requires_no_invitation_code end def undefined_agent_types agents.reorder('').group(:type).pluck(:type).select do |type| type.constantize false rescue NameError true end end def undefined_agents agents.where(type: undefined_agent_types).select('id, schedule, events_count, type as undefined') end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/pushbullet_agent.rb
app/models/agents/pushbullet_agent.rb
module Agents class PushbulletAgent < Agent include FormConfigurable cannot_be_scheduled! cannot_create_events! no_bulk_receive! before_validation :create_device, on: :create API_BASE = 'https://api.pushbullet.com/v2/' TYPE_TO_ATTRIBUTES = { 'note' => [:title, :body], 'link' => [:title, :body, :url], 'address' => [:name, :address] } class Unauthorized < StandardError; end description <<~MD The Pushbullet agent sends pushes to a pushbullet device To authenticate you need to either the `api_key` or create a `pushbullet_api_key` credential, you can find yours at your account page: `https://www.pushbullet.com/account` If you do not select an existing device, Huginn will create a new one with the name 'Huginn'. To push to all of your devices, select `All Devices` from the devices list. You have to provide a message `type` which has to be `note`, `link`, or `address`. The message types `checklist`, and `file` are not supported at the moment. Depending on the message `type` you can use additional fields: * note: `title` and `body` * link: `title`, `body`, and `url` * address: `name`, and `address` In every value of the options hash you can use the liquid templating, learn more about it at the [Wiki](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid). MD def default_options { 'api_key' => '', 'device_id' => '', 'title' => "{{title}}", 'body' => '{{body}}', 'type' => 'note', } end form_configurable :api_key, roles: :validatable form_configurable :device_id, roles: :completable form_configurable :type, type: :array, values: ['note', 'link', 'address'] form_configurable :title form_configurable :body, type: :text form_configurable :url form_configurable :name form_configurable :address def validate_options errors.add(:base, "you need to specify a pushbullet api_key") if options['api_key'].blank? errors.add(:base, "you need to specify a device_id") if options['device_id'].blank? errors.add(:base, "you need to specify a valid message type") if options['type'].blank? || !['note', 'link', 'address'].include?(options['type']) TYPE_TO_ATTRIBUTES[options['type']].each do |attr| errors.add(:base, "you need to specify '#{attr}' for the type '#{options['type']}'") if options[attr].blank? end end def validate_api_key devices true rescue Unauthorized false end def complete_device_id devices .map { |d| { text: d['nickname'], id: d['iden'] } } .unshift(text: 'All Devices', id: '__ALL__') end def working? received_event_without_error? end def receive(incoming_events) incoming_events.each do |event| safely do response = request(:post, 'pushes', query_options(event)) end end end private def safely yield rescue Unauthorized => e error(e.message) end def request(http_method, method, options) response = JSON.parse(HTTParty.send(http_method, API_BASE + method, options).body) raise Unauthorized, response['error']['message'] if response['error'].present? response end def devices response = request(:get, 'devices', basic_auth) response['devices'].select { |d| d['pushable'] == true } rescue Unauthorized [] end def create_device return if options['device_id'].present? safely do response = request(:post, 'devices', basic_auth.merge(body: { nickname: 'Huginn', type: 'stream' })) self.options[:device_id] = response['iden'] end end def basic_auth { basic_auth: { username: interpolated[:api_key].presence || credential('pushbullet_api_key'), password: '' } } end def query_options(event) mo = interpolated(event) dev_ident = mo[:device_id] == "__ALL__" ? '' : mo[:device_id] basic_auth.merge(body: { device_iden: dev_ident, type: mo[:type] }.merge(payload(mo))) end def payload(mo) Hash[TYPE_TO_ATTRIBUTES[mo[:type]].map { |k| [k, mo[k]] }] end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/peak_detector_agent.rb
app/models/agents/peak_detector_agent.rb
module Agents class PeakDetectorAgent < Agent cannot_be_scheduled! DEFAULT_SEARCH_URL = 'https://twitter.com/search?q={q}' description <<~MD The Peak Detector Agent will watch for peaks in an event stream. When a peak is detected, the resulting Event will have a payload message of `message`. You can include extractions in the message, for example: `I saw a bar of: {{foo.bar}}`, have a look at the [Wiki](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) for details. The `value_path` value is a [JSONPath](http://goessner.net/articles/JsonPath/) to the value of interest. `group_by_path` is a JSONPath that will be used to group values, if present. Set `expected_receive_period_in_days` to the maximum amount of time that you'd expect to pass between Events being received by this Agent. You may set `window_duration_in_days` to change the default memory window length of `14` days, `min_peak_spacing_in_days` to change the default minimum peak spacing of `2` days (peaks closer together will be ignored), and `std_multiple` to change the default standard deviation threshold multiple of `3`. You may set `min_events` for the minimal number of accumulated events before the agent starts detecting. You may set `search_url` to point to something else than Twitter search, using the URI Template syntax defined in [RFC 6570](https://tools.ietf.org/html/rfc6570). Default value is `#{DEFAULT_SEARCH_URL}` where `{q}` will be replaced with group name. MD event_description <<~MD Events look like: { "message": "Your message", "peak": 6, "peak_time": 3456789242, "grouped_by": "something" } MD def validate_options unless options['expected_receive_period_in_days'].present? && options['message'].present? && options['value_path'].present? && options['min_events'].present? errors.add(:base, "expected_receive_period_in_days, value_path, min_events and message are required") end begin tmpl = search_url rescue StandardError => e errors.add(:base, "search_url must be a valid URI template: #{e.message}") else unless tmpl.keys.include?('q') errors.add(:base, "search_url must include a variable named 'q'") end end end def default_options { 'expected_receive_period_in_days' => "2", 'group_by_path' => "filter", 'value_path' => "count", 'message' => "A peak of {{count}} was found in {{filter}}", 'min_events' => '4', } end def working? last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs? end def receive(incoming_events) incoming_events.sort_by(&:created_at).each do |event| group = group_for(event) remember group, event check_for_peak group, event end end def search_url Addressable::Template.new(options[:search_url].presence || DEFAULT_SEARCH_URL) end private def check_for_peak(group, event) memory['peaks'] ||= {} memory['peaks'][group] ||= [] return if memory['data'][group].length <= options['min_events'].to_i if memory['peaks'][group].empty? || memory['peaks'][group].last < event.created_at.to_i - peak_spacing average_value, standard_deviation = stats_for(group, skip_last: 1) newest_value, newest_time = memory['data'][group][-1].map(&:to_f) if newest_value > average_value + std_multiple * standard_deviation memory['peaks'][group] << newest_time memory['peaks'][group].reject! { |p| p <= newest_time - window_duration } create_event payload: { 'message' => interpolated(event)['message'], 'peak' => newest_value, 'peak_time' => newest_time, 'grouped_by' => group.to_s } end end end def stats_for(group, options = {}) data = memory['data'][group].map { |d| d.first.to_f } data = data[0...(data.length - (options[:skip_last] || 0))] length = data.length.to_f mean = 0 mean_variance = 0 data.each do |value| mean += value end mean /= length data.each do |value| variance = (value - mean)**2 mean_variance += variance end mean_variance /= length standard_deviation = Math.sqrt(mean_variance) [mean, standard_deviation] end def window_duration if interpolated['window_duration'].present? # The older option interpolated['window_duration'].to_i else (interpolated['window_duration_in_days'] || 14).to_f.days end end def std_multiple (interpolated['std_multiple'] || 3).to_f end def peak_spacing if interpolated['peak_spacing'].present? # The older option interpolated['peak_spacing'].to_i else (interpolated['min_peak_spacing_in_days'] || 2).to_f.days end end def group_for(event) group_by_path = interpolated['group_by_path'].presence (group_by_path && Utils.value_at(event.payload, group_by_path)) || 'no_group' end def remember(group, event) memory['data'] ||= {} memory['data'][group] ||= [] memory['data'][group] << [Utils.value_at(event.payload, interpolated['value_path']).to_f, event.created_at.to_i] cleanup group end def cleanup(group) newest_time = memory['data'][group].last.last memory['data'][group].reject! { |_value, time| time <= newest_time - window_duration } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/slack_agent.rb
app/models/agents/slack_agent.rb
module Agents class SlackAgent < Agent DEFAULT_USERNAME = 'Huginn' ALLOWED_PARAMS = ['channel', 'username', 'unfurl_links', 'attachments', 'blocks'] can_dry_run! cannot_be_scheduled! cannot_create_events! no_bulk_receive! gem_dependency_check { defined?(Slack) } description <<~MD The Slack Agent lets you receive events and send notifications to [Slack](https://slack.com/). #{'## Include `slack-notifier` in your Gemfile to use this Agent!' if dependencies_missing?} To get started, you will first need to configure an incoming webhook. - Go to `https://my.slack.com/services/new/incoming-webhook`, choose a default channel and add the integration. Your webhook URL will look like: `https://hooks.slack.com/services/some/random/characters` Once the webhook has been configured, it can be used to post to other channels or direct to team members. To send a private message to team member, use their @username as the channel. Messages can be formatted using [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid). Finally, you can set a custom icon for this webhook in `icon`, either as [emoji](http://www.emoji-cheat-sheet.com) or an URL to an image. Leaving this field blank will use the default icon for a webhook. MD def default_options { 'webhook_url' => 'https://hooks.slack.com/services/...', 'channel' => '#general', 'username' => DEFAULT_USERNAME, 'message' => "Hey there, It's Huginn", 'icon' => '', } end def validate_options unless options['webhook_url'].present? || (options['auth_token'].present? && options['team_name'].present?) # compatibility errors.add(:base, "webhook_url is required") end errors.add(:base, "channel is required") unless options['channel'].present? end def working? received_event_without_error? end def webhook_url case when url = interpolated[:webhook_url].presence url when (team = interpolated[:team_name].presence) && (token = interpolated[:auth_token]) webhook = interpolated[:webhook].presence || 'incoming-webhook' # old style webhook URL "https://#{Rack::Utils.escape_path(team)}.slack.com/services/hooks/#{Rack::Utils.escape_path(webhook)}?token=#{Rack::Utils.escape(token)}" end end def username interpolated[:username].presence || DEFAULT_USERNAME end def slack_notifier @slack_notifier ||= Slack::Notifier.new(webhook_url, username:) end def filter_options(opts) opts.select { |key, _value| ALLOWED_PARAMS.include? key }.symbolize_keys end def receive(incoming_events) incoming_events.each do |event| opts = interpolated(event) slack_opts = filter_options(opts) if opts[:icon].present? if /^:/.match(opts[:icon]) slack_opts[:icon_emoji] = opts[:icon] else slack_opts[:icon_url] = opts[:icon] end end slack_notifier.ping opts[:message], slack_opts end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/local_file_agent.rb
app/models/agents/local_file_agent.rb
module Agents class LocalFileAgent < Agent include LongRunnable include FormConfigurable include FileHandling emits_file_pointer! default_schedule 'every_1h' def self.should_run? ENV['ENABLE_INSECURE_AGENTS'] == "true" end description do <<~MD The LocalFileAgent can watch a file/directory for changes or emit an event for every file in that directory. When receiving an event it writes the received data into a file. `mode` determines if the agent is emitting events for (changed) files or writing received event data to disk. ### Reading When `watch` is set to `true` the LocalFileAgent will watch the specified `path` for changes, the schedule is ignored and the file system is watched continuously. An event will be emitted for every detected change. When `watch` is set to `false` the agent will emit an event for every file in the directory on each scheduled run. #{emitting_file_handling_agent_description} ### Writing Every event will be writting into a file at `path`, Liquid interpolation is possible to change the path per event. When `append` is true the received data will be appended to the file. Use [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) templating in `data` to specify which part of the received event should be written. *Warning*: This type of Agent can read and write any file the user that runs the Huginn server has access to, and is #{Agents::LocalFileAgent.should_run? ? "**currently enabled**" : "**currently disabled**"}. Only enable this Agent if you trust everyone using your Huginn installation. You can enable this Agent in your .env file by setting `ENABLE_INSECURE_AGENTS` to `true`. MD end event_description do "Events will looks like this:\n\n " + if boolify(interpolated['watch']) Utils.pretty_print( "file_pointer" => { "file" => "/tmp/test/filename", "agent_id" => id }, "event_type" => "modified/added/removed" ) else Utils.pretty_print( "file_pointer" => { "file" => "/tmp/test/filename", "agent_id" => id } ) end end def default_options { 'mode' => 'read', 'watch' => 'true', 'append' => 'false', 'path' => "", 'data' => '{{ data }}' } end form_configurable :mode, type: :array, values: %w[read write] form_configurable :watch, type: :array, values: %w[true false] form_configurable :path, type: :string form_configurable :append, type: :boolean form_configurable :data, type: :string def validate_options if options['mode'].blank? || !['read', 'write'].include?(options['mode']) errors.add(:base, "The 'mode' option is required and must be set to 'read' or 'write'") end if options['watch'].blank? || ![true, false].include?(boolify(options['watch'])) errors.add(:base, "The 'watch' option is required and must be set to 'true' or 'false'") end if options['append'].blank? || ![true, false].include?(boolify(options['append'])) errors.add(:base, "The 'append' option is required and must be set to 'true' or 'false'") end if options['path'].blank? errors.add(:base, "The 'path' option is required.") end end def working? should_run?(false) && ((interpolated['mode'] == 'read' && check_path_existance && checked_without_error?) || (interpolated['mode'] == 'write' && received_event_without_error?)) end def check return if interpolated['mode'] != 'read' || boolify(interpolated['watch']) || !should_run? return unless check_path_existance(true) if File.directory?(expanded_path) Dir.glob(File.join(expanded_path, '*')).select { |f| File.file?(f) } else [expanded_path] end.each do |file| create_event payload: get_file_pointer(file) end end def receive(incoming_events) return if interpolated['mode'] != 'write' || !should_run? incoming_events.each do |event| mo = interpolated(event) expanded_path = File.expand_path(mo['path']) File.open(expanded_path, boolify(mo['append']) ? 'a' : 'w') do |file| file.write(mo['data']) end create_event payload: get_file_pointer(expanded_path) end end def start_worker? interpolated['mode'] == 'read' && boolify(interpolated['watch']) && should_run? && check_path_existance end def check_path_existance(log = true) if !File.exist?(expanded_path) error("File or directory '#{expanded_path}' does not exist") if log return false end true end def get_io(file) File.open(file, 'r') end def expanded_path @expanded_path ||= File.expand_path(interpolated['path']) end private def should_run?(log = true) if self.class.should_run? true else error("Unable to run because insecure agents are not enabled. Set ENABLE_INSECURE_AGENTS to true in the Huginn .env configuration.") if log false end end class Worker < LongRunnable::Worker def setup require 'listen' path, options = listen_options @listener = Listen.to(path, **options, &method(:callback)) end def run sleep unless agent.check_path_existance(true) @listener.start sleep end def stop @listener.stop end private def callback(*changes) AgentRunner.with_connection do changes.zip([:modified, :added, :removed]).each do |files, event_type| files.each do |file| agent.create_event payload: agent.get_file_pointer(file).merge(event_type:) end end agent.touch(:last_check_at) end end def listen_options if File.directory?(agent.expanded_path) [ agent.expanded_path, ignore!: [] ] else [ File.dirname(agent.expanded_path), ignore!: [], only: /\A#{Regexp.escape(File.basename(agent.expanded_path))}\z/ ] end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/ftpsite_agent.rb
app/models/agents/ftpsite_agent.rb
require 'uri' require 'time' module Agents class FtpsiteAgent < Agent include FileHandling default_schedule "every_12h" gem_dependency_check { defined?(Net::FTP) && defined?(Net::FTP::List) } emits_file_pointer! description do <<~MD The Ftp Site Agent checks an FTP site and creates Events based on newly uploaded files in a directory. When receiving events it creates files on the configured FTP server. #{'## Include `net-ftp-list` in your Gemfile to use this Agent!' if dependencies_missing?} `mode` must be present and either `read` or `write`, in `read` mode the agent checks the FTP site for changed files, with `write` it writes received events to a file on the server. ### Universal options Specify a `url` that represents a directory of an FTP site to watch, and a list of `patterns` to match against file names. Login credentials can be included in `url` if authentication is required: `ftp://username:password@ftp.example.com/path`. Liquid formatting is supported as well: `ftp://{% credential ftp_credentials %}@ftp.example.com/` Optionally specify the encoding of the files you want to read/write in `force_encoding`, by default UTF-8 is used. ### Reading Only files with a last modification time later than the `after` value, if specifed, are emitted as event. ### Writing Specify the filename to use in `filename`, Liquid interpolation is possible to change the name per event. Use [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) templating in `data` to specify which part of the received event should be written. #{emitting_file_handling_agent_description} MD end event_description <<~MD Events look like this: { "url": "ftp://example.org/pub/releases/foo-1.2.tar.gz", "filename": "foo-1.2.tar.gz", "timestamp": "2014-04-10T22:50:00Z" } MD def working? if interpolated['mode'] == 'read' event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs? else received_event_without_error? end end def default_options { 'mode' => 'read', 'expected_update_period_in_days' => "1", 'url' => "ftp://example.org/pub/releases/", 'patterns' => [ 'foo-*.tar.gz', ], 'after' => Time.now.iso8601, 'force_encoding' => '', 'filename' => '', 'data' => '{{ data }}' } end def validate_options # Check for required fields begin if !options['url'].include?('{{') url = interpolated['url'] String === url or raise uri = URI(url) URI::FTP === uri or raise errors.add(:base, "url must end with a slash") if uri.path.present? && !uri.path.end_with?('/') end rescue StandardError errors.add(:base, "url must be a valid FTP URL") end options['mode'] = 'read' if options['mode'].blank? && new_record? if options['mode'].blank? || !['read', 'write'].include?(options['mode']) errors.add(:base, "The 'mode' option is required and must be set to 'read' or 'write'") end case interpolated['mode'] when 'read' patterns = options['patterns'] case patterns when Array if patterns.empty? errors.add(:base, "patterns must not be empty") end when nil, '' errors.add(:base, "patterns must be specified") else errors.add(:base, "patterns must be an array") end when 'write' if options['filename'].blank? errors.add(:base, "filename must be specified in 'write' mode") end if options['data'].blank? errors.add(:base, "data must be specified in 'write' mode") end end # Check for optional fields if (timestamp = options['timestamp']).present? begin Time.parse(timestamp) rescue StandardError errors.add(:base, "timestamp cannot be parsed as time") end end if options['expected_update_period_in_days'].present? errors.add(:base, "Invalid expected_update_period_in_days format") unless is_positive_integer?(options['expected_update_period_in_days']) end end def check return if interpolated['mode'] != 'read' saving_entries do |found| each_entry { |filename, mtime| found[filename, mtime] } end end def receive(incoming_events) return if interpolated['mode'] != 'write' incoming_events.each do |event| mo = interpolated(event) mo['data'].encode!( interpolated['force_encoding'], invalid: :replace, undef: :replace ) if interpolated['force_encoding'].present? open_ftp(base_uri) do |ftp| ftp.storbinary("STOR #{mo['filename']}", StringIO.new(mo['data']), Net::FTP::DEFAULT_BLOCKSIZE) end end end def each_entry patterns = interpolated['patterns'] after = if str = interpolated['after'] Time.parse(str) else Time.at(0) end open_ftp(base_uri) do |ftp| log "Listing the directory" # Do not use a block style call because we need to call other # commands during iteration. list = ftp.list('-a') list.each do |line| entry = Net::FTP::List.parse line filename = entry.basename mtime = Time.parse(entry.mtime.to_s).utc patterns.any? { |pattern| File.fnmatch?(pattern, filename) } or next after < mtime or next yield filename, mtime end end end def open_ftp(uri) ftp = Net::FTP.new log "Connecting to #{uri.host}#{':%d' % uri.port if uri.port != uri.default_port}" ftp.connect(uri.host, uri.port) user = if str = uri.user CGI.unescape(str) else 'anonymous' end password = if str = uri.password CGI.unescape(str) else 'anonymous@' end log "Logging in as #{user}" ftp.login(user, password) ftp.passive = true if (path = uri.path.chomp('/')).present? log "Changing directory to #{path}" ftp.chdir(path) end yield ftp ensure log "Closing the connection" ftp.close end def base_uri @base_uri ||= URI(interpolated['url']) end def saving_entries known_entries = memory['known_entries'] || {} found_entries = {} new_files = [] yield proc { |filename, mtime| found_entries[filename] = misotime = mtime.utc.iso8601 unless (prev = known_entries[filename]) && misotime <= prev new_files << filename end } new_files.sort_by { |filename| found_entries[filename] }.each { |filename| create_event payload: get_file_pointer(filename).merge({ 'url' => (base_uri + uri_path_escape(filename)).to_s, 'filename' => filename, 'timestamp' => found_entries[filename], }) } memory['known_entries'] = found_entries save! end def get_io(file) data = StringIO.new open_ftp(base_uri) do |ftp| ftp.getbinaryfile(file, nil) do |chunk| data.write chunk.force_encoding(options['force_encoding'].presence || 'UTF-8') end end data.rewind data end private def uri_path_escape(string) str = string.b str.gsub!(/([^A-Za-z0-9\-._~!$&()*+,=@]+)/) { |m| '%' + m.unpack('H2' * m.bytesize).join('%').upcase } str.force_encoding(Encoding::US_ASCII) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/http_status_agent.rb
app/models/agents/http_status_agent.rb
require 'time_tracker' module Agents class HttpStatusAgent < Agent include WebRequestConcern include FormConfigurable can_dry_run! can_order_created_events! default_schedule "every_12h" form_configurable :url form_configurable :disable_redirect_follow, type: :boolean form_configurable :changes_only, type: :boolean form_configurable :headers_to_save description <<~MD The HttpStatusAgent will check a url and emit the resulting HTTP status code with the time that it waited for a reply. Additionally, it will optionally emit the value of one or more specified headers. Specify a `Url` and the Http Status Agent will produce an event with the HTTP status code. If you specify one or more `Headers to save` (comma-delimited) as well, that header or headers' value(s) will be included in the event. The `disable redirect follow` option causes the Agent to not follow HTTP redirects. For example, setting this to `true` will cause an agent that receives a 301 redirect to `http://yahoo.com` to return a status of 301 instead of following the redirect and returning 200. The `changes only` option causes the Agent to report an event only when the status changes. If set to false, an event will be created for every check. If set to true, an event will only be created when the status changes (like if your site goes from 200 to 500). MD event_description <<~MD Events will have the following fields: { "url": "...", "status": "...", "elapsed_time": "...", "headers": { "...": "..." } } MD def working? memory['last_status'].to_i > 0 end def default_options { 'url' => "http://google.com", 'disable_redirect_follow' => "true", } end def validate_options errors.add(:base, "a url must be specified") unless options['url'].present? end def header_array(str) (str || '').split(',').map(&:strip) end def check check_this_url interpolated[:url], header_array(interpolated[:headers_to_save]) end def receive(incoming_events) incoming_events.each do |event| interpolate_with(event) do check_this_url interpolated[:url], header_array(interpolated[:headers_to_save]) end end end private def check_this_url(url, local_headers) # Track time measured_result = TimeTracker.track { ping(url) } current_status = measured_result.result ? measured_result.status.to_s : '' return if options['changes_only'] == 'true' && current_status == memory['last_status'].to_s payload = { 'url' => url, 'response_received' => false, 'elapsed_time' => measured_result.elapsed_time } # Deal with failures if measured_result.result final_url = boolify(interpolated['disable_redirect_follow']) ? url : measured_result.result.env.url.to_s payload.merge!({ 'final_url' => final_url, 'redirected' => (url != final_url), 'response_received' => true, 'status' => current_status }) # Deal with headers if local_headers.present? header_results = local_headers.each_with_object({}) { |header, hash| hash[header] = measured_result.result.headers[header] } payload.merge!({ 'headers' => header_results }) end create_event(payload:) memory['last_status'] = measured_result.status.to_s else create_event(payload:) memory['last_status'] = nil end end def ping(url) result = faraday.get url result.status > 0 ? result : nil rescue StandardError nil end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/webhook_agent.rb
app/models/agents/webhook_agent.rb
module Agents class WebhookAgent < Agent include EventHeadersConcern include WebRequestConcern # to make reCAPTCHA verification requests cannot_be_scheduled! cannot_receive_events! description do <<~MD The Webhook Agent will create events by receiving webhooks from any source. In order to create events with this agent, make a POST request to: ``` https://#{ENV['DOMAIN']}/users/#{user.id}/web_requests/#{id || ':id'}/#{options['secret'] || ':secret'} ``` #{'The placeholder symbols above will be replaced by their values once the agent is saved.' unless id} Options: * `secret` - A token that the host will provide for authentication. * `expected_receive_period_in_days` - How often you expect to receive events this way. Used to determine if the agent is working. * `payload_path` - JSONPath of the attribute in the POST body to be used as the Event payload. Set to `.` to return the entire message. If `payload_path` points to an array, Events will be created for each element. * `event_headers` - Comma-separated list of HTTP headers your agent will include in the payload. * `event_headers_key` - The key to use to store all the headers received * `verbs` - Comma-separated list of http verbs your agent will accept. For example, "post,get" will enable POST and GET requests. Defaults to "post". * `response` - The response message to the request. Defaults to 'Event Created'. * `response_headers` - An object with any custom response headers. (example: `{"Access-Control-Allow-Origin": "*"}`) * `code` - The response code to the request. Defaults to '201'. If the code is '301' or '302' the request will automatically be redirected to the url defined in "response". * `recaptcha_secret` - Setting this to a reCAPTCHA "secret" key makes your agent verify incoming requests with reCAPTCHA. Don't forget to embed a reCAPTCHA snippet including your "site" key in the originating form(s). * `recaptcha_send_remote_addr` - Set this to true if your server is properly configured to set REMOTE_ADDR to the IP address of each visitor (instead of that of a proxy server). * `score_threshold` - Setting this when using reCAPTCHA v3 to define the treshold when a submission is verified. Defaults to 0.5 MD end event_description do <<~MD The event payload is based on the value of the `payload_path` option, which is set to `#{interpolated['payload_path']}`. MD end def default_options { "secret" => SecureRandom.uuid, "expected_receive_period_in_days" => 1, "payload_path" => ".", "event_headers" => "", "event_headers_key" => "headers", "score_threshold" => 0.5 } end def receive_web_request(request) # check the secret secret = request.path_parameters[:secret] return ["Not Authorized", 401] unless secret == interpolated['secret'] params = request.query_parameters.dup begin params.update(request.request_parameters) rescue EOFError end method = request.method_symbol.to_s headers = request.headers.each_with_object({}) { |(name, value), hash| case name when /\AHTTP_([A-Z0-9_]+)\z/ hash[$1.tr('_', '-').gsub(/[^-]+/, &:capitalize)] = value end } # check the verbs verbs = (interpolated['verbs'] || 'post').split(/,/).map { |x| x.strip.downcase }.select { |x| x.present? } return ["Please use #{verbs.join('/').upcase} requests only", 401] unless verbs.include?(method) # check the code code = (interpolated['code'].presence || 201).to_i # check the reCAPTCHA response if required if recaptcha_secret = interpolated['recaptcha_secret'].presence recaptcha_response = params.delete('g-recaptcha-response') or return ["Not Authorized", 401] parameters = { secret: recaptcha_secret, response: recaptcha_response, } if boolify(interpolated['recaptcha_send_remote_addr']) parameters[:remoteip] = request.env['REMOTE_ADDR'] end begin response = faraday.post('https://www.google.com/recaptcha/api/siteverify', parameters) rescue StandardError => e error "Verification failed: #{e.message}" return ["Not Authorized", 401] end body = JSON.parse(response.body) if interpolated['score_threshold'].present? && body['score'].present? body['score'] > interpolated['score_threshold'].to_f or return ["Not Authorized", 401] else body['success'] or return ["Not Authorized", 401] end end [payload_for(params)].flatten.each do |payload| create_event(payload: payload.merge(event_headers_payload(headers))) end if interpolated['response_headers'].presence [ interpolated(params)['response'] || 'Event Created', code, "text/plain", interpolated['response_headers'].presence ] else [ interpolated(params)['response'] || 'Event Created', code ] end end def working? event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs? end def validate_options unless options['secret'].present? errors.add(:base, "Must specify a secret for 'Authenticating' requests") end if options['code'].present? && options['code'].to_s !~ /\A\s*(\d+|\{.*)\s*\z/ errors.add(:base, "Must specify a code for request responses") end if options['code'].to_s.in?(['301', '302']) && !options['response'].present? errors.add(:base, "Must specify a url for request redirect") end validate_event_headers_options! end def payload_for(params) Utils.value_at(params, interpolated['payload_path']) || {} end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/weibo_user_agent.rb
app/models/agents/weibo_user_agent.rb
module Agents class WeiboUserAgent < Agent include WeiboConcern cannot_receive_events! description <<~MD The Weibo User Agent follows the timeline of a specified Weibo user. It uses this endpoint: http://open.weibo.com/wiki/2/statuses/user_timeline/en #{'## Include `weibo_2` in your Gemfile to use this Agent!' if dependencies_missing?} You must first set up a Weibo app and generate an `acess_token` to authenticate with. Provide that, along with the `app_key` and `app_secret` for your Weibo app in the options. Specify the `uid` of the Weibo user whose timeline you want to watch. Set `expected_update_period_in_days` to the maximum amount of time that you'd expect to pass between Events being created by this Agent. MD event_description <<~MD Events are the raw JSON provided by the Weibo API. Should look something like: { "created_at": "Tue May 31 17:46:55 +0800 2011", "id": 11488058246, "text": "求关注。", "source": "<a href=\"http://weibo.com\" rel=\"nofollow\">新浪微博</a>", "favorited": false, "truncated": false, "in_reply_to_status_id": "", "in_reply_to_user_id": "", "in_reply_to_screen_name": "", "geo": null, "mid": "5612814510546515491", "reposts_count": 8, "comments_count": 9, "annotations": [], "user": { "id": 1404376560, "screen_name": "zaku", "name": "zaku", "province": "11", "city": "5", "location": "北京 朝阳区", "description": "人生五十年,乃如梦如幻;有生斯有死,壮士复何憾。", "url": "http://blog.sina.com.cn/zaku", "profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1", "domain": "zaku", "gender": "m", "followers_count": 1204, "friends_count": 447, "statuses_count": 2908, "favourites_count": 0, "created_at": "Fri Aug 28 00:00:00 +0800 2009", "following": false, "allow_all_act_msg": false, "remark": "", "geo_enabled": true, "verified": false, "allow_all_comment": true, "avatar_large": "http://tp1.sinaimg.cn/1404376560/180/0/1", "verified_reason": "", "follow_me": false, "online_status": 0, "bi_followers_count": 215 } } MD default_schedule "every_1h" def validate_options unless options['uid'].present? && options['expected_update_period_in_days'].present? errors.add(:base, "expected_update_period_in_days and uid are required") end end def working? event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs? end def default_options { 'uid' => "", 'access_token' => "---", 'app_key' => "---", 'app_secret' => "---", 'expected_update_period_in_days' => "2" } end def check since_id = memory['since_id'] || nil opts = { uid: interpolated['uid'].to_i } opts.merge! since_id: since_id unless since_id.nil? # http://open.weibo.com/wiki/2/statuses/user_timeline/en resp = weibo_client.statuses.user_timeline opts if resp[:statuses] resp[:statuses].each do |status| memory['since_id'] = status.id if !memory['since_id'] || (status.id > memory['since_id']) create_event payload: status.as_json end end save! end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/commander_agent.rb
app/models/agents/commander_agent.rb
module Agents class CommanderAgent < Agent include AgentControllerConcern cannot_create_events! description <<~MD The Commander Agent is triggered by schedule or an incoming event, and commands other agents ("targets") to run, disable, configure, or enable themselves. # Action types Set `action` to one of the action types below: * `run`: Target Agents are run when this agent is triggered. * `disable`: Target Agents are disabled (if not) when this agent is triggered. * `enable`: Target Agents are enabled (if not) when this agent is triggered. * If the option `drop_pending_events` is set to `true`, pending events will be cleared before the agent is enabled. * `configure`: Target Agents have their options updated with the contents of `configure_options`. Here's a tip: you can use [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) templating to dynamically determine the action type. For example: - To create a CommanderAgent that receives an event from a WeatherAgent every morning to kick an agent flow that is only useful in a nice weather, try this: `{% if conditions contains 'Sunny' or conditions contains 'Cloudy' %}` `run{% endif %}` - Likewise, if you have a scheduled agent flow specially crafted for rainy days, try this: `{% if conditions contains 'Rain' %}enable{% else %}disabled{% endif %}` - If you want to update a WeatherAgent based on a UserLocationAgent, you could use `'action': 'configure'` and set 'configure_options' to `{ 'location': '{{_location_.latlng}}' }`. - In templating, you can use the variable `target` to refer to each target agent, which has the following attributes: #{Agent::Drop.instance_methods(false).map { |m| "`#{m}`" }.to_sentence}. # Targets Select Agents that you want to control from this CommanderAgent. MD def working? true end def check control! end def receive(incoming_events) incoming_events.each do |event| interpolate_with(event) do control! end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/telegram_agent.rb
app/models/agents/telegram_agent.rb
require 'httmultiparty' module Agents class TelegramAgent < Agent include FormConfigurable cannot_be_scheduled! cannot_create_events! no_bulk_receive! can_dry_run! description <<~MD The Telegram Agent receives and collects events and sends them via [Telegram](https://telegram.org/). It is assumed that events have either a `text`, `photo`, `audio`, `document`, `video` or `group` key. You can use the EventFormattingAgent if your event does not provide these keys. The value of `text` key is sent as a plain text message. You can also tell Telegram how to parse the message with `parse_mode`, set to either `html`, `markdown` or `markdownv2`. The value of `photo`, `audio`, `document` and `video` keys should be a url whose contents will be sent to you. The value of `group` key should be a list and must consist of 2-10 objects representing an [InputMedia](https://core.telegram.org/bots/api#inputmedia) from the [Telegram Bot API](https://core.telegram.org/bots/api#inputmedia). Be careful: the `caption` field is not covered by the "long message" setting.#{' '} **Setup** * Obtain an `auth_token` by [creating a new bot](https://telegram.me/botfather). * If you would like to send messages to a public channel: * Add your bot to the channel as an administrator * If you would like to send messages to a group: * Add the bot to the group * If you would like to send messages privately to yourself: * Open a conservation with the bot by visiting https://telegram.me/YourHuginnBot * Send a message to the bot, group or channel. * Select the `chat_id` from the dropdown. **Options** * `caption`: caption for a media content (0-1024 characters), applied only for `photo`, `audio`, `document`, or `video` * `disable_notification`: send a message silently in a channel * `disable_web_page_preview`: disable link previews for links in a text message * `long_message`: truncate (default) or split text messages and captions that exceed Telegram API limits. Markdown and HTML tags can't span across messages and, if not opened or closed properly, will render as plain text. * `parse_mode`: parse policy of a text message See the official [Telegram Bot API documentation](https://core.telegram.org/bots/api#available-methods) for detailed info. MD def default_options { auth_token: 'xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', chat_id: 'xxxxxxxx' } end form_configurable :auth_token, roles: :validatable form_configurable :chat_id, roles: :completable form_configurable :caption form_configurable :disable_notification, type: :array, values: ['', 'true', 'false'] form_configurable :disable_web_page_preview, type: :array, values: ['', 'true', 'false'] form_configurable :long_message, type: :array, values: ['', 'split', 'truncate'] form_configurable :parse_mode, type: :array, values: ['', 'html', 'markdown', 'markdownv2'] def validate_auth_token HTTMultiParty.post(telegram_bot_uri('getMe'))['ok'] end def complete_chat_id response = HTTMultiParty.post(telegram_bot_uri('getUpdates')) return [] unless response['ok'] response['result'].map { |update| update_to_complete(update) }.uniq end def validate_options errors.add(:base, 'auth_token is required') unless options['auth_token'].present? errors.add(:base, 'chat_id is required') unless options['chat_id'].present? errors.add(:base, 'caption should be 1024 characters or less') if interpolated['caption'].present? && interpolated['caption'].length > 1024 && (!interpolated['long_message'].present? || interpolated['long_message'] != 'split') errors.add(:base, "disable_notification has invalid value: should be 'true' or 'false'") if interpolated['disable_notification'].present? && !%w[ true false ].include?(interpolated['disable_notification']) errors.add(:base, "disable_web_page_preview has invalid value: should be 'true' or 'false'") if interpolated['disable_web_page_preview'].present? && !%w[ true false ].include?(interpolated['disable_web_page_preview']) errors.add(:base, "long_message has invalid value: should be 'split' or 'truncate'") if interpolated['long_message'].present? && !%w[ split truncate ].include?(interpolated['long_message']) errors.add(:base, "parse_mode has invalid value: should be 'html', 'markdown' or 'markdownv2'") if interpolated['parse_mode'].present? && !%w[ html markdown markdownv2 ].include?(interpolated['parse_mode']) end def working? received_event_without_error? && !recent_error_logs? end def receive(incoming_events) incoming_events.each do |event| receive_event event end end private TELEGRAM_ACTIONS = { text: :sendMessage, photo: :sendPhoto, audio: :sendAudio, document: :sendDocument, video: :sendVideo, group: :sendMediaGroup, }.freeze def configure_params(params) params[:chat_id] = interpolated['chat_id'] params[:disable_notification] = interpolated['disable_notification'] if interpolated['disable_notification'].present? if params.has_key?(:text) params[:disable_web_page_preview] = interpolated['disable_web_page_preview'] if interpolated['disable_web_page_preview'].present? params[:parse_mode] = interpolated['parse_mode'] if interpolated['parse_mode'].present? elsif !params.has_key?(:media) params[:caption] = interpolated['caption'] if interpolated['caption'].present? end params end def receive_event(event) interpolate_with event do messages_send = TELEGRAM_ACTIONS.count do |field, _method| payload = event.payload[field] next unless payload.present? if field == :group send_telegram_messages field, configure_params(media: payload) else send_telegram_messages field, configure_params(field => payload) end true end error("No valid key found in event #{event.payload.inspect}") if messages_send.zero? end end def send_message(field, params) response = HTTMultiParty.post telegram_bot_uri(TELEGRAM_ACTIONS[field]), body: params.to_json, headers: { 'Content-Type' => 'application/json' } unless response['ok'] error(response) end end def send_telegram_messages(field, params) if interpolated['long_message'] == 'split' if field == :text params[:text].scan(/\G\s*(?:\w{4096}|.{1,4096}(?=\b|\z))/m) do |message| message.strip! send_message field, configure_params(field => message) unless message.blank? end else caption_array = (params[:caption].presence || '').scan(/\G\s*\K(?:\w{1024}|.{1,1024}(?=\b|\z))/m).map(&:strip) params[:caption] = caption_array.shift send_message field, params caption_array.each do |caption| send_message(:text, configure_params(text: caption)) unless caption.blank? end end else params[:caption] = params[:caption][0..1023] if params[:caption] params[:text] = params[:text][0..4095] if params[:text] send_message field, params end end def telegram_bot_uri(method) "https://api.telegram.org/bot#{interpolated['auth_token']}/#{method}" end def update_to_complete(update) chat = (update['message'] || update.fetch('channel_post', {})).fetch('chat', {}) { id: chat['id'], text: chat['title'] || "#{chat['first_name']} #{chat['last_name']}" } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/human_task_agent.rb
app/models/agents/human_task_agent.rb
module Agents class HumanTaskAgent < Agent default_schedule "every_10m" gem_dependency_check { defined?(RTurk) } description <<~MD The Human Task Agent is used to create Human Intelligence Tasks (HITs) on Mechanical Turk. #{'## Include `rturk` in your Gemfile to use this Agent!' if dependencies_missing?} HITs can be created in response to events, or on a schedule. Set `trigger_on` to either `schedule` or `event`. # Schedule The schedule of this Agent is how often it should check for completed HITs, __NOT__ how often to submit one. To configure how often a new HIT should be submitted when in `schedule` mode, set `submission_period` to a number of hours. # Example If created with an event, all HIT fields can contain interpolated values via [liquid templating](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid). For example, if the incoming event was a Twitter event, you could make a HITT to rate its sentiment like this: { "expected_receive_period_in_days": 2, "trigger_on": "event", "hit": { "assignments": 1, "title": "Sentiment evaluation", "description": "Please rate the sentiment of this message: '{{message}}'", "reward": 0.05, "lifetime_in_seconds": "3600", "questions": [ { "type": "selection", "key": "sentiment", "name": "Sentiment", "required": "true", "question": "Please select the best sentiment value:", "selections": [ { "key": "happy", "text": "Happy" }, { "key": "sad", "text": "Sad" }, { "key": "neutral", "text": "Neutral" } ] }, { "type": "free_text", "key": "feedback", "name": "Have any feedback for us?", "required": "false", "question": "Feedback", "default": "Type here...", "min_length": "2", "max_length": "2000" } ] } } As you can see, you configure the created HIT with the `hit` option. Required fields are `title`, which is the title of the created HIT, `description`, which is the description of the HIT, and `questions` which is an array of questions. Questions can be of `type` _selection_ or _free\\_text_. Both types require the `key`, `name`, `required`, `type`, and `question` configuration options. Additionally, _selection_ requires a `selections` array of options, each of which contain `key` and `text`. For _free\\_text_, the special configuration options are all optional, and are `default`, `min_length`, and `max_length`. By default, all answers are emitted in a single event. If you'd like separate events for each answer, set `separate_answers` to `true`. # Combining answers There are a couple of ways to combine HITs that have multiple `assignments`, all of which involve setting `combination_mode` at the top level. ## Taking the majority Option 1: if all of your `questions` are of `type` _selection_, you can set `combination_mode` to `take_majority`. This will cause the Agent to automatically select the majority vote for each question across all `assignments` and return it as `majority_answer`. If all selections are numeric, an `average_answer` will also be generated. Option 2: you can have the Agent ask additional human workers to rank the `assignments` and return the most highly ranked answer. To do this, set `combination_mode` to `poll` and provide a `poll_options` object. Here is an example: { "trigger_on": "schedule", "submission_period": 12, "combination_mode": "poll", "poll_options": { "title": "Take a poll about some jokes", "instructions": "Please rank these jokes from most funny (5) to least funny (1)", "assignments": 3, "row_template": "{{joke}}" }, "hit": { "assignments": 5, "title": "Tell a joke", "description": "Please tell me a joke", "reward": 0.05, "lifetime_in_seconds": "3600", "questions": [ { "type": "free_text", "key": "joke", "name": "Your joke", "required": "true", "question": "Joke", "min_length": "2", "max_length": "2000" } ] } } Resulting events will have the original `answers`, as well as the `poll` results, and a field called `best_answer` that contains the best answer as determined by the poll. (Note that `separate_answers` won't work when doing a poll.) # Other settings `lifetime_in_seconds` is the number of seconds a HIT is left on Amazon before it's automatically closed. The default is 1 day. As with most Agents, `expected_receive_period_in_days` is required if `trigger_on` is set to `event`. MD event_description <<~MD Events look like: { "answers": [ { "feedback": "Hello!", "sentiment": "happy" } ] } MD def validate_options options['hit'] ||= {} options['hit']['questions'] ||= [] errors.add( :base, "'trigger_on' must be one of 'schedule' or 'event'" ) unless %w[schedule event].include?(options['trigger_on']) errors.add( :base, "'hit.assignments' should specify the number of HIT assignments to create" ) unless options['hit']['assignments'].present? && options['hit']['assignments'].to_i > 0 errors.add(:base, "'hit.title' must be provided") unless options['hit']['title'].present? errors.add(:base, "'hit.description' must be provided") unless options['hit']['description'].present? errors.add(:base, "'hit.questions' must be provided") unless options['hit']['questions'].present? if options['trigger_on'] == "event" errors.add( :base, "'expected_receive_period_in_days' is required when 'trigger_on' is set to 'event'" ) unless options['expected_receive_period_in_days'].present? elsif options['trigger_on'] == "schedule" errors.add( :base, "'submission_period' must be set to a positive number of hours when 'trigger_on' is set to 'schedule'" ) unless options['submission_period'].present? && options['submission_period'].to_i > 0 end if options['hit']['questions'].any? { |question| %w[key name required type question].any? { |k| question[k].blank? } } errors.add(:base, "all questions must set 'key', 'name', 'required', 'type', and 'question'") end if options['hit']['questions'].any? { |question| question['type'] == "selection" && ( question['selections'].blank? || question['selections'].any? { |s| s['key'].blank? || s['text'].blank? } ) } errors.add(:base, "all questions of type 'selection' must have a selections array with selections that set 'key' and 'name'") end if take_majority? && options['hit']['questions'].any? { |question| question['type'] != "selection" } errors.add(:base, "all questions must be of type 'selection' to use the 'take_majority' option") end if create_poll? errors.add( :base, "poll_options is required when combination_mode is set to 'poll' and must have the keys 'title', 'instructions', 'row_template', and 'assignments'" ) unless options['poll_options'].is_a?(Hash) && options['poll_options']['title'].present? && options['poll_options']['instructions'].present? && options['poll_options']['row_template'].present? && options['poll_options']['assignments'].to_i > 0 end end def default_options { 'expected_receive_period_in_days' => 2, 'trigger_on' => "event", 'hit' => { 'assignments' => 1, 'title' => "Sentiment evaluation", 'description' => "Please rate the sentiment of this message: '{{message}}'", 'reward' => 0.05, 'lifetime_in_seconds' => 24 * 60 * 60, 'questions' => [ { 'type' => "selection", 'key' => "sentiment", 'name' => "Sentiment", 'required' => "true", 'question' => "Please select the best sentiment value:", 'selections' => [ { 'key' => "happy", 'text' => "Happy" }, { 'key' => "sad", 'text' => "Sad" }, { 'key' => "neutral", 'text' => "Neutral" } ] }, { 'type' => "free_text", 'key' => "feedback", 'name' => "Have any feedback for us?", 'required' => "false", 'question' => "Feedback", 'default' => "Type here...", 'min_length' => "2", 'max_length' => "2000" } ] } } end def working? last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs? end def check review_hits if interpolated['trigger_on'] == "schedule" && (memory['last_schedule'] || 0) <= Time.now.to_i - interpolated['submission_period'].to_i * 60 * 60 memory['last_schedule'] = Time.now.to_i create_basic_hit end end def receive(incoming_events) if interpolated['trigger_on'] == "event" incoming_events.each do |event| create_basic_hit event end end end protected if defined?(RTurk) def take_majority? interpolated['combination_mode'] == "take_majority" || interpolated['take_majority'] == "true" end def create_poll? interpolated['combination_mode'] == "poll" end def event_for_hit(hit_id) if memory['hits'][hit_id].is_a?(Hash) Event.find_by_id(memory['hits'][hit_id]['event_id']) else nil end end def hit_type(hit_id) if memory['hits'][hit_id].is_a?(Hash) && memory['hits'][hit_id]['type'] memory['hits'][hit_id]['type'] else 'user' end end def review_hits reviewable_hit_ids = RTurk::GetReviewableHITs.create.hit_ids my_reviewed_hit_ids = reviewable_hit_ids & (memory['hits'] || {}).keys if reviewable_hit_ids.length > 0 log "MTurk reports #{reviewable_hit_ids.length} HITs, of which I own [#{my_reviewed_hit_ids.to_sentence}]" end my_reviewed_hit_ids.each do |hit_id| hit = RTurk::Hit.new(hit_id) assignments = hit.assignments log "Looking at HIT #{hit_id}. I found #{assignments.length} assignments#{" with the statuses: #{assignments.map(&:status).to_sentence}" if assignments.length > 0}" next unless assignments.length == hit.max_assignments && assignments.all? { |assignment| assignment.status == "Submitted" } inbound_event = event_for_hit(hit_id) if hit_type(hit_id) == 'poll' # handle completed polls log "Handling a poll: #{hit_id}" scores = {} assignments.each do |assignment| assignment.answers.each do |index, rating| scores[index] ||= 0 scores[index] += rating.to_i end end top_answer = scores.to_a.sort { |b, a| a.last <=> b.last }.first.first payload = { 'answers' => memory['hits'][hit_id]['answers'], 'poll' => assignments.map(&:answers), 'best_answer' => memory['hits'][hit_id]['answers'][top_answer.to_i - 1] } event = create_event(payload:) log("Event emitted with answer(s) for poll", outbound_event: event, inbound_event:) else # handle normal completed HITs payload = { 'answers' => assignments.map(&:answers) } if take_majority? counts = {} options['hit']['questions'].each do |question| question_counts = question['selections'].each_with_object({}) { |selection, memo| memo[selection['key']] = 0 } assignments.each do |assignment| answers = ActiveSupport::HashWithIndifferentAccess.new(assignment.answers) answer = answers[question['key']] question_counts[answer] += 1 end counts[question['key']] = question_counts end payload['counts'] = counts majority_answer = counts.each_with_object({}) do |(key, question_counts), memo| memo[key] = question_counts.to_a.sort_by(&:last).last.first end payload['majority_answer'] = majority_answer if all_questions_are_numeric? average_answer = counts.each_with_object({}) do |(key, question_counts), memo| sum = divisor = 0 question_counts.to_a.each do |num, count| sum += num.to_s.to_f * count divisor += count end memo[key] = sum / divisor.to_f end payload['average_answer'] = average_answer end end if create_poll? questions = [] selections = 5.times.map { |i| { 'key' => i + 1, 'text' => i + 1 } }.reverse assignments.length.times do |index| questions << { 'type' => "selection", 'name' => "Item #{index + 1}", 'key' => index, 'required' => "true", 'question' => interpolate_string(options['poll_options']['row_template'], assignments[index].answers), 'selections' => selections } end poll_hit = create_hit( 'title' => options['poll_options']['title'], 'description' => options['poll_options']['instructions'], 'questions' => questions, 'assignments' => options['poll_options']['assignments'], 'lifetime_in_seconds' => options['poll_options']['lifetime_in_seconds'], 'reward' => options['poll_options']['reward'], 'payload' => inbound_event && inbound_event.payload, 'metadata' => { 'type' => 'poll', 'original_hit' => hit_id, 'answers' => assignments.map(&:answers), 'event_id' => inbound_event && inbound_event.id } ) log( "Poll HIT created with ID #{poll_hit.id} and URL #{poll_hit.url}. Original HIT: #{hit_id}", inbound_event: ) elsif options[:separate_answers] payload['answers'].each.with_index do |answer, index| sub_payload = payload.dup sub_payload.delete('answers') sub_payload['answer'] = answer event = create_event payload: sub_payload log("Event emitted with answer ##{index}", outbound_event: event, inbound_event:) end else event = create_event(payload:) log("Event emitted with answer(s)", outbound_event: event, inbound_event:) end end assignments.each(&:approve!) hit.dispose! memory['hits'].delete(hit_id) end end def all_questions_are_numeric? interpolated['hit']['questions'].all? do |question| question['selections'].all? do |selection| value = selection['key'] value == value.to_f.to_s || value == value.to_i.to_s end end end def create_basic_hit(event = nil) hit = create_hit( 'title' => options['hit']['title'], 'description' => options['hit']['description'], 'questions' => options['hit']['questions'], 'assignments' => options['hit']['assignments'], 'lifetime_in_seconds' => options['hit']['lifetime_in_seconds'], 'reward' => options['hit']['reward'], 'payload' => event && event.payload, 'metadata' => { 'event_id' => event && event.id } ) log("HIT created with ID #{hit.id} and URL #{hit.url}", inbound_event: event) end def create_hit(opts = {}) payload = opts['payload'] || {} title = interpolate_string(opts['title'], payload).strip description = interpolate_string(opts['description'], payload).strip questions = interpolate_options(opts['questions'], payload) hit = RTurk::Hit.create(title:) do |hit| hit.max_assignments = (opts['assignments'] || 1).to_i hit.description = description hit.lifetime = (opts['lifetime_in_seconds'] || 24 * 60 * 60).to_i hit.question_form AgentQuestionForm.new(title:, description:, questions:) hit.reward = (opts['reward'] || 0.05).to_f # hit.qualifications.add :approval_rate, { gt: 80 } end memory['hits'] ||= {} memory['hits'][hit.id] = opts['metadata'] || {} hit end # RTurk Question Form class AgentQuestionForm < RTurk::QuestionForm needs :title, :description, :questions def question_form_content Overview do Title do text @title end Text do text @description end end @questions.each.with_index do |question, index| Question do QuestionIdentifier do text question['key'] || "question_#{index}" end DisplayName do text question['name'] || "Question ##{index}" end IsRequired do text question['required'] || 'true' end QuestionContent do Text do text question['question'] end end AnswerSpecification do if question['type'] == "selection" SelectionAnswer do StyleSuggestion do text 'radiobutton' end Selections do question['selections'].each do |selection| Selection do SelectionIdentifier do text selection['key'] end Text do text selection['text'] end end end end end else FreeTextAnswer do if question['min_length'].present? || question['max_length'].present? Constraints do lengths = {} lengths['minLength'] = question['min_length'].to_s if question['min_length'].present? lengths['maxLength'] = question['max_length'].to_s if question['max_length'].present? Length lengths end end if question['default'].present? DefaultText do text question['default'] end end end end end end end end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/google_calendar_publish_agent.rb
app/models/agents/google_calendar_publish_agent.rb
require 'json' require 'google/apis/calendar_v3' module Agents class GoogleCalendarPublishAgent < Agent cannot_be_scheduled! no_bulk_receive! gem_dependency_check { defined?(Google) && defined?(Google::Apis::CalendarV3) } description <<~MD The Google Calendar Publish Agent creates events on your Google Calendar. #{'## Include `google-api-client` in your Gemfile to use this Agent!' if dependencies_missing?} This agent relies on service accounts, rather than oauth. Setup: 1. Visit [the google api console](https://code.google.com/apis/console/b/0/) 2. New project -> Huginn 3. APIs & Auth -> Enable google calendar 4. Credentials -> Create new Client ID -> Service Account 5. Download the JSON keyfile and save it to a path, ie: `/home/huginn/Huginn-5d12345678cd.json`. Or open that file and copy the `private_key`. 6. Grant access via google calendar UI to the service account email address for each calendar you wish to manage. For a whole google apps domain, you can [delegate authority](https://developers.google.com/+/domains/authentication/delegation) An earlier version of Huginn used PKCS12 key files to authenticate. This will no longer work, you should generate a new JSON format keyfile, that will look something like: <pre><code>{ "type": "service_account", "project_id": "huginn-123123", "private_key_id": "6d6b476fc6ccdb31e0f171991e5528bb396ffbe4", "private_key": "-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n", "client_email": "huginn-calendar@huginn-123123.iam.gserviceaccount.com", "client_id": "123123...123123", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/huginn-calendar%40huginn-123123.iam.gserviceaccount.com" }</code></pre> Agent Configuration: `calendar_id` - The id the calendar you want to publish to. Typically your google account email address. Liquid formatting (e.g. `{{ cal_id }}`) is allowed here in order to extract the calendar_id from the incoming event. `google` A hash of configuration options for the agent. `google` `service_account_email` - The authorised service account email address. `google` `key_file` OR `google` `key` - The path to the JSON key file above, or the key itself (the value of `private_key`). [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) formatting is supported if you want to use a Credential. (E.g., `{% credential google_key %}`) Set `expected_update_period_in_days` to the maximum amount of time that you'd expect to pass between Events being created by this Agent. Use it with a trigger agent to shape your payload! A hash of event details. See the [Google Calendar API docs](https://developers.google.com/google-apps/calendar/v3/reference/events/insert) The prior version Google's API expected keys like `dateTime` but in the latest version they expect snake case keys like `date_time`. Example payload for trigger agent: <pre><code>{ "message": { "visibility": "default", "summary": "Awesome event", "description": "An example event with text. Pro tip: DateTimes are in RFC3339", "start": { "date_time": "2017-06-30T17:00:00-05:00" }, "end": { "date_time": "2017-06-30T18:00:00-05:00" } } }</code></pre> MD event_description <<~MD Events look like: { 'success' => true, 'published_calendar_event' => { .... }, 'agent_id' => 1234, 'event_id' => 3432 } MD def validate_options errors.add(:base, "expected_update_period_in_days is required") unless options['expected_update_period_in_days'].present? end def working? event_created_within?(options['expected_update_period_in_days']) && most_recent_event && most_recent_event.payload['success'] == true && !recent_error_logs? end def default_options { 'expected_update_period_in_days' => "10", 'calendar_id' => 'you@email.com', 'google' => { 'key_file' => '/path/to/private.key', 'key' => '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n', 'service_account_email' => '' } } end def receive(incoming_events) require 'google_calendar' incoming_events.each do |event| GoogleCalendar.open(interpolate_options(options, event), Rails.logger) do |calendar| cal_message = event.payload["message"] if cal_message["start"].present? && cal_message["start"]["dateTime"].present? && !cal_message["start"]["date_time"].present? cal_message["start"]["date_time"] = cal_message["start"].delete "dateTime" end if cal_message["end"].present? && cal_message["end"]["dateTime"].present? && !cal_message["end"]["date_time"].present? cal_message["end"]["date_time"] = cal_message["end"].delete "dateTime" end calendar_event = calendar.publish_as( interpolated(event)['calendar_id'], cal_message ) create_event payload: { 'success' => true, 'published_calendar_event' => calendar_event, 'agent_id' => event.agent_id, 'event_id' => event.id } end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/key_value_store_agent.rb
app/models/agents/key_value_store_agent.rb
# frozen_string_literal: true module Agents class KeyValueStoreAgent < Agent can_control_other_agents! cannot_be_scheduled! cannot_create_events! description <<~MD The Key-Value Store Agent is a data storage that keeps an associative array in its memory. It receives events to store values and provides the data to other agents as an object via Liquid Templating. Liquid templates specified in the `key` and `value` options are evaluated for each received event to be stored in the memory. The `variable` option specifies the name by which agents that use the storage refers to the data in Liquid templating. The `max_keys` option specifies up to how many keys to keep in the storage. When the number of keys goes beyond this, the oldest key-value pair gets removed. (default: 100) ### Storing data For example, say your agent receives these incoming events: { "city": "Tokyo", "weather": "cloudy" } { "city": "Osaka", "weather": "sunny" } Then you could configure the agent with `{ "key": "{{ city }}", "value": "{{ weather }}" }` to get the following data stored: { "Tokyo": "cloudy", "Osaka": "sunny" } Here are some specifications: - Keys are always stringified as mandated by the JSON format. - Values are stringified by default. Use the `as_object` filter to store non-string values. - If the key is evaluated to an empty string, the event is ignored. - If the value is evaluated to either `null` or empty (`""`, `[]`, `{}`) the key gets deleted. - In the `value` template, the existing value (if any) can be accessed via the variable `_value_`. - In the `key` and `value` templates, the whole event payload can be accessed via the variable `_event_`. ### Extracting data To allow other agents to use the data of a Key-Value Store Agent, designate the agent as a controller. You can do that by adding those agents to the "Controller targets" of the agent. The target agents can refer to the storage via the variable specified by the `variable` option value. So, if the store agent in the above example had an option `"variable": "weather"`, they can say something like `{{ weather[city] | default: "unknown" }}` in their templates to get the weather of a city stored in the variable `city`. MD def validate_options options[:key].is_a?(String) or errors.add(:base, "key is required and must be a string.") options[:value] or errors.add(:base, "value is required.") /\A(?!\d)\w+\z/ === options[:variable] or errors.add(:base, "variable is required and must be valid as a variable name.") max_keys > 0 or errors.add(:base, "max_keys must be a positive number.") end def default_options { 'key' => '{{ id }}', 'value' => '{{ _event_ | as_object }}', 'variable' => 'var', } end def working? !recent_error_logs? end def control_action 'provide' end def max_keys if value = options[:max_keys].presence value.to_i else 100 end end def receive(incoming_events) max_keys = max_keys() incoming_events.each do |event| interpolate_with(event) do interpolation_context.stack do interpolation_context['_event_'] = event.payload key = interpolate_options(options)['key'].to_s next if key.empty? storage = memory interpolation_context['_value_'] = storage.delete(key) value = interpolate_options(options)['value'] if value.nil? || value.try(:empty?) storage.delete(key) else storage[key] = value storage.shift while storage.size > max_keys end update!(memory: storage) end end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/csv_agent.rb
app/models/agents/csv_agent.rb
module Agents class CsvAgent < Agent include FormConfigurable include FileHandling cannot_be_scheduled! consumes_file_pointer! def default_options { 'mode' => 'parse', 'separator' => ',', 'use_fields' => '', 'output' => 'event_per_row', 'with_header' => 'true', 'data_path' => '$.data', 'data_key' => 'data' } end description do <<~MD The `CsvAgent` parses or serializes CSV data. When parsing, events can either be emitted for the entire CSV, or one per row. Set `mode` to `parse` to parse CSV from incoming event, when set to `serialize` the agent serilizes the data of events to CSV. ### Universal options Specify the `separator` which is used to seperate the fields from each other (default is `,`). `data_key` sets the key which contains the serialized CSV or parsed CSV data in emitted events. ### Parsing If `use_fields` is set to a comma seperated string and the CSV file contains field headers the agent will only extract the specified fields. `output` determines wheather one event per row is emitted or one event that includes all the rows. Set `with_header` to `true` if first line of the CSV file are field names. #{receiving_file_handling_agent_description} When receiving the CSV data in a regular event use [JSONPath](http://goessner.net/articles/JsonPath/) to select the path in `data_path`. `data_path` is only used when the received event does not contain a 'file pointer'. ### Serializing If `use_fields` is set to a comma seperated string and the first received event has a object at the specified `data_path` the generated CSV will only include the given fields. Set `with_header` to `true` to include a field header in the CSV. Use [JSONPath](http://goessner.net/articles/JsonPath/) in `data_path` to select with part of the received events should be serialized. MD end event_description do data = if interpolated['mode'] == 'parse' rows = if boolify(interpolated['with_header']) [ { 'column' => 'row1 value1', 'column2' => 'row1 value2' }, { 'column' => 'row2 value3', 'column2' => 'row2 value4' }, ] else [ ['row1 value1', 'row1 value2'], ['row2 value1', 'row2 value2'], ] end if interpolated['output'] == 'event_per_row' rows[0] else rows end else <<~EOS "generated","csv","data" "column1","column2","column3" EOS end "Events will looks like this:\n\n " + Utils.pretty_print({ interpolated['data_key'] => data }) end form_configurable :mode, type: :array, values: %w[parse serialize] form_configurable :separator, type: :string form_configurable :data_key, type: :string form_configurable :with_header, type: :boolean form_configurable :use_fields, type: :string form_configurable :output, type: :array, values: %w[event_per_row event_per_file] form_configurable :data_path, type: :string def validate_options if options['with_header'].blank? || ![true, false].include?(boolify(options['with_header'])) errors.add(:base, "The 'with_header' options is required and must be set to 'true' or 'false'") end if options['mode'] == 'serialize' && options['data_path'].blank? errors.add(:base, "When mode is set to serialize data_path has to be present.") end end def working? received_event_without_error? end def receive(incoming_events) case options['mode'] when 'parse' parse(incoming_events) when 'serialize' serialize(incoming_events) end end private def serialize(incoming_events) mo = interpolated(incoming_events.first) rows = rows_from_events(incoming_events, mo) csv = CSV.generate(col_sep: separator(mo), force_quotes: true) do |csv| if boolify(mo['with_header']) && rows.first.is_a?(Hash) csv << if mo['use_fields'].present? extract_options(mo) else rows.first.keys end end rows.each do |data| csv << if data.is_a?(Hash) if mo['use_fields'].present? data.extract!(*extract_options(mo)).values else data.values end else data end end end create_event payload: { mo['data_key'] => csv } end def rows_from_events(incoming_events, mo) [].tap do |rows| incoming_events.each do |event| data = Utils.value_at(event.payload, mo['data_path']) if data.is_a?(Array) && (data[0].is_a?(Array) || data[0].is_a?(Hash)) data.each { |row| rows << row } else rows << data end end end end def parse(incoming_events) incoming_events.each do |event| mo = interpolated(event) next unless io = local_get_io(event) if mo['output'] == 'event_per_row' parse_csv(io, mo) do |payload| create_event payload: { mo['data_key'] => payload } end else create_event payload: { mo['data_key'] => parse_csv(io, mo, []) } end end end def local_get_io(event) if io = get_io(event) io else Utils.value_at(event.payload, interpolated['data_path']) end end def parse_csv_options(mo) options = { col_sep: separator(mo), headers: boolify(mo['with_header']), } options[:liberal_parsing] = true if CSV::DEFAULT_OPTIONS.key?(:liberal_parsing) options end def parse_csv(io, mo, array = nil) CSV.new(io, **parse_csv_options(mo)).each do |row| if block_given? yield get_payload(row, mo) else array << get_payload(row, mo) end end array end def separator(mo) mo['separator'] == '\\t' ? "\t" : mo['separator'] end def get_payload(row, mo) if boolify(mo['with_header']) if mo['use_fields'].present? row.to_hash.extract!(*extract_options(mo)) else row.to_hash end else row end end def extract_options(mo) mo['use_fields'].split(',').map(&:strip) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/twilio_receive_text_agent.rb
app/models/agents/twilio_receive_text_agent.rb
module Agents class TwilioReceiveTextAgent < Agent cannot_be_scheduled! cannot_receive_events! gem_dependency_check { defined?(Twilio) } description do <<~MD The Twilio Receive Text Agent receives text messages from Twilio and emits them as events. #{'## Include `twilio-ruby` in your Gemfile to use this Agent!' if dependencies_missing?} In order to create events with this agent, configure Twilio to send POST requests to: ``` #{post_url} ``` #{'The placeholder symbols above will be replaced by their values once the agent is saved.' unless id} Options: * `server_url` must be set to the URL of your Huginn installation (probably "https://#{ENV['DOMAIN']}"), which must be web-accessible. Be sure to set http/https correctly. * `account_sid` and `auth_token` are your Twilio account credentials. `auth_token` must be the primary auth token for your Twilio accout. * If `reply_text` is set, it's contents will be sent back as a confirmation text. * `expected_receive_period_in_days` - How often you expect to receive events this way. Used to determine if the agent is working. MD end def default_options { 'account_sid' => 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'auth_token' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'server_url' => "https://#{ENV['DOMAIN'].presence || 'example.com'}", 'reply_text' => '', "expected_receive_period_in_days" => 1 } end def validate_options unless options['account_sid'].present? && options['auth_token'].present? && options['server_url'].present? && options['expected_receive_period_in_days'].present? errors.add(:base, 'account_sid, auth_token, server_url, and expected_receive_period_in_days are all required') end end def working? event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs? end def post_url if interpolated['server_url'].present? "#{interpolated['server_url']}/users/#{user.id}/web_requests/#{id || ':id'}/sms-endpoint" else "https://#{ENV['DOMAIN']}/users/#{user.id}/web_requests/#{id || ':id'}/sms-endpoint" end end def receive_web_request(request) params = request.params.except(:action, :controller, :agent_id, :user_id, :format) method = request.method_symbol.to_s headers = request.headers # check the last url param: 'secret' secret = params.delete('secret') return ["Not Authorized", 401] unless secret == "sms-endpoint" signature = headers['HTTP_X_TWILIO_SIGNATURE'] # validate from twilio @validator ||= Twilio::Security::RequestValidator.new interpolated['auth_token'] if !@validator.validate(post_url, params, signature) error("Twilio Signature Failed to Validate\n\n" + "URL: #{post_url}\n\n" + "POST params: #{params.inspect}\n\n" + "Signature: #{signature}") return ["Not authorized", 401] end if create_event(payload: params) response = Twilio::TwiML::MessagingResponse.new do |r| if interpolated['reply_text'].present? r.message(body: interpolated['reply_text']) end end [response.to_s, 200, "text/xml"] else ["Bad request", 400] end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/post_agent.rb
app/models/agents/post_agent.rb
module Agents class PostAgent < Agent include EventHeadersConcern include WebRequestConcern include FileHandling consumes_file_pointer! MIME_RE = /\A\w+\/.+\z/ can_dry_run! no_bulk_receive! default_schedule "never" description do <<~MD A Post Agent receives events from other agents (or runs periodically), merges those events with the [Liquid-interpolated](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) contents of `payload`, and sends the results as POST (or GET) requests to a specified url. To skip merging in the incoming event, but still send the interpolated payload, set `no_merge` to `true`. The `post_url` field must specify where you would like to send requests. Please include the URI scheme (`http` or `https`). The `method` used can be any of `get`, `post`, `put`, `patch`, and `delete`. By default, non-GETs will be sent with form encoding (`application/x-www-form-urlencoded`). Change `content_type` to `json` to send JSON instead. Change `content_type` to `xml` to send XML, where the name of the root element may be specified using `xml_root`, defaulting to `post`. When `content_type` contains a [MIME](https://en.wikipedia.org/wiki/Media_type) type, and `payload` is a string, its interpolated value will be sent as a string in the HTTP request's body and the request's `Content-Type` HTTP header will be set to `content_type`. When `payload` is a string `no_merge` has to be set to `true`. If `emit_events` is set to `true`, the server response will be emitted as an Event. The "body" value of the Event is the response body. If the `parse_body` option is set to `true` and the content type of the response is JSON, it is parsed to a JSON object. Otherwise it is raw text. A raw HTML/XML text can be fed to a WebsiteAgent for parsing (using its `data_from_event` and `type` options). The Event will also have a "headers" hash and a "status" integer value. If `output_mode` is set to `merge`, the emitted Event will be merged into the original contents of the received Event. Set `event_headers` to a list of header names, either in an array of string or in a comma-separated string, to include only some of the header values. Set `event_headers_style` to one of the following values to normalize the keys of "headers" for downstream agents' convenience: * `capitalized` (default) - Header names are capitalized; e.g. "Content-Type" * `downcased` - Header names are downcased; e.g. "content-type" * `snakecased` - Header names are snakecased; e.g. "content_type" * `raw` - Backward compatibility option to leave them unmodified from what the underlying HTTP library returns. Other Options: * `headers` - When present, it should be a hash of headers to send with the request. * `basic_auth` - Specify HTTP basic auth parameters: `"username:password"`, or `["username", "password"]`. * `disable_ssl_verification` - Set to `true` to disable ssl verification. * `user_agent` - A custom User-Agent name (default: "Faraday v#{Faraday::VERSION}"). #{receiving_file_handling_agent_description} When receiving a `file_pointer` the request will be sent with multipart encoding (`multipart/form-data`) and `content_type` is ignored. `upload_key` can be used to specify the parameter in which the file will be sent, it defaults to `file`. MD end event_description <<~MD Events look like this: { "status": 200, "headers": { "Content-Type": "text/html", ... }, "body": "<html>Some data...</html>" } Original event contents will be merged when `output_mode` is set to `merge`. MD def default_options { 'post_url' => "http://www.example.com", 'expected_receive_period_in_days' => '1', 'content_type' => 'form', 'method' => 'post', 'payload' => { 'key' => 'value', 'something' => 'the event contained {{ somekey }}' }, 'headers' => {}, 'emit_events' => 'false', 'parse_body' => 'true', 'no_merge' => 'true', 'output_mode' => 'clean' } end def working? return false if recent_error_logs? if interpolated['expected_receive_period_in_days'].present? return false unless last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago end true end def method (interpolated['method'].presence || 'post').to_s.downcase end def validate_options unless options['post_url'].present? errors.add(:base, "post_url is a required field") end if options['payload'].present? && %w[get delete].include?(method) && !(options['payload'].is_a?(Hash) || options['payload'].is_a?(Array)) errors.add(:base, "if provided, payload must be a hash or an array") end if options['payload'].present? && %w[post put patch].include?(method) if !(options['payload'].is_a?(Hash) || options['payload'].is_a?(Array)) && options['content_type'] !~ MIME_RE errors.add(:base, "if provided, payload must be a hash or an array") end end if options['content_type'] =~ MIME_RE && options['payload'].is_a?(String) && boolify(options['no_merge']) != true errors.add(:base, "when the payload is a string, `no_merge` has to be set to `true`") end if options['content_type'] == 'form' && options['payload'].present? && options['payload'].is_a?(Array) errors.add(:base, "when content_type is a form, if provided, payload must be a hash") end if options.has_key?('emit_events') && boolify(options['emit_events']).nil? errors.add(:base, "if provided, emit_events must be true or false") end validate_event_headers_options! unless %w[post get put delete patch].include?(method) errors.add(:base, "method must be 'post', 'get', 'put', 'delete', or 'patch'") end if options['no_merge'].present? && !%(true false).include?(options['no_merge'].to_s) errors.add(:base, "if provided, no_merge must be 'true' or 'false'") end if options['output_mode'].present? && !options['output_mode'].to_s.include?('{') && !%(clean merge).include?(options['output_mode'].to_s) errors.add(:base, "if provided, output_mode must be 'clean' or 'merge'") end if options['parse_body'].present? && !/\A(?:true|false)\z|\{/.match?(options['parse_body'].to_s) errors.add(:base, "if provided, parse_body must be 'true' or 'false'") end unless headers.is_a?(Hash) errors.add(:base, "if provided, headers must be a hash") end validate_web_request_options! end def parse_body? boolify(interpolated['parse_body']) end def receive(incoming_events) incoming_events.each do |event| interpolate_with(event) do outgoing = interpolated['payload'].presence || {} if boolify(interpolated['no_merge']) handle outgoing, event, headers(interpolated[:headers]) else handle outgoing.merge(event.payload), event, headers(interpolated[:headers]) end end end end def check handle interpolated['payload'].presence || {}, headers end private def handle(data, event = Event.new, headers) url = interpolated(event.payload)[:post_url] case method when 'get', 'delete' params = data body = nil when 'post', 'put', 'patch' params = nil content_type = if has_file_pointer?(event) data[interpolated(event.payload)['upload_key'].presence || 'file'] = get_upload_io(event) nil else interpolated(event.payload)['content_type'] end case content_type when 'json' headers['Content-Type'] = 'application/json; charset=utf-8' body = data.to_json when 'xml' headers['Content-Type'] = 'text/xml; charset=utf-8' body = data.to_xml(root: (interpolated(event.payload)[:xml_root] || 'post')) when MIME_RE headers['Content-Type'] = content_type body = data.to_s else body = data end else error "Invalid method '#{method}'" end response = faraday.run_request(method.to_sym, url, body, headers) { |request| request.params.update(params) if params } if boolify(interpolated['emit_events']) new_event = interpolated['output_mode'].to_s == 'merge' ? event.payload.dup : {} create_event payload: new_event.merge( body: response.body, status: response.status ).merge( event_headers_payload(response.headers) ) end end def event_headers_key super || 'headers' end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/pushover_agent.rb
app/models/agents/pushover_agent.rb
module Agents class PushoverAgent < Agent can_dry_run! cannot_be_scheduled! cannot_create_events! no_bulk_receive! API_URL = 'https://api.pushover.net/1/messages.json' description <<~MD The Pushover Agent receives and collects events and sends them via push notification to a user/group. **You need a Pushover API Token:** [https://pushover.net/apps/build](https://pushover.net/apps/build) * `token`: your application's API token * `user`: the user or group key (not e-mail address). * `expected_receive_period_in_days`: is maximum number of days that you would expect to pass between events being received by this agent. The following options are all [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) templates whose evaluated values will be posted to the Pushover API. Only the `message` parameter is required, and if it is blank API call is omitted. Pushover API has a `512` Character Limit including `title`. `message` will be truncated. * `message` - your message (required) * `device` - your user's device name to send the message directly to that device, rather than all of the user's devices * `title` or `subject` - your notification's title * `url` - a supplementary URL to show with your message - `512` Character Limit * `url_title` - a title for your supplementary URL, otherwise just the URL is shown - `100` Character Limit * `timestamp` - a [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time) of your message's date and time to display to the user, rather than the time your message is received by the Pushover API. * `priority` - send as `-1` to always send as a quiet notification, `0` is default, `1` to display as high-priority and bypass the user's quiet hours, or `2` for emergency priority: [Please read Pushover Docs on Emergency Priority](https://pushover.net/api#priority) * `sound` - the name of one of the sounds supported by device clients to override the user's default sound choice. [See PushOver docs for sound options.](https://pushover.net/api#sounds) * `retry` - Required for emergency priority - Specifies how often (in seconds) the Pushover servers will send the same notification to the user. Minimum value: `30` * `expire` - Required for emergency priority - Specifies how many seconds your notification will continue to be retried for (every retry seconds). Maximum value: `86400` * `ttl` - set to a Time to Live in seconds * `html` - set to `true` to have Pushover's apps display the `message` content as HTML * `monospace` - set to `true` to have Pushover's apps display the `message` content with a monospace font MD def default_options { 'token' => '', 'user' => '', 'message' => '{{ message }}', 'device' => '{{ device }}', 'title' => '{{ title }}', 'url' => '{{ url }}', 'url_title' => '{{ url_title }}', 'priority' => '{{ priority }}', 'timestamp' => '{{ timestamp }}', 'sound' => '{{ sound }}', 'retry' => '{{ retry }}', 'expire' => '{{ expire }}', 'ttl' => '{{ ttl }}', 'html' => 'false', 'monospace' => 'false', 'expected_receive_period_in_days' => '1' } end def validate_options unless options['token'].present? && options['user'].present? && options['expected_receive_period_in_days'].present? errors.add(:base, 'token, user, and expected_receive_period_in_days are all required.') end end def receive(incoming_events) incoming_events.each do |event| interpolate_with(event) do post_params = {} # required parameters %w[ token user message ].all? { |key| if value = String.try_convert(interpolated[key].presence) post_params[key] = value end } or next # optional parameters %w[ device title url url_title priority timestamp sound retry expire ttl ].each do |key| value = String.try_convert(interpolated[key].presence) or next case key when 'url' value.slice!(512..-1) when 'url_title' value.slice!(100..-1) end post_params[key] = value end # boolean parameters %w[ html monospace ].each do |key| if value = interpolated[key].presence post_params[key] = case value.to_s when 'true', '1' '1' else '0' end end end send_notification(post_params) end end end def working? last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs? end def send_notification(post_params) response = HTTParty.post(API_URL, query: post_params) puts response log "Sent the following notification: \"#{post_params.except('token').inspect}\"" end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/delay_agent.rb
app/models/agents/delay_agent.rb
module Agents class DelayAgent < Agent include FormConfigurable default_schedule 'every_12h' description <<~MD The DelayAgent stores received Events and emits copies of them on a schedule. Use this as a buffer or queue of Events. `max_events` should be set to the maximum number of events that you'd like to hold in the buffer. When this number is reached, new events will either be ignored, or will displace the oldest event already in the buffer, depending on whether you set `keep` to `newest` or `oldest`. `expected_receive_period_in_days` is used to determine if the Agent is working. Set it to the maximum number of days that you anticipate passing without this Agent receiving an incoming Event. `emit_interval` specifies the interval in seconds between emitting events. This is zero (no interval) by default. `max_emitted_events` is used to limit the number of the maximum events which should be created. If you omit this DelayAgent will create events for every event stored in the memory. # Ordering Events #{description_events_order("events in which buffered events are emitted")} MD def default_options { 'expected_receive_period_in_days' => 10, 'max_events' => 100, 'keep' => 'newest', 'max_emitted_events' => '', 'emit_interval' => 0, 'events_order' => [], } end form_configurable :expected_receive_period_in_days, type: :number, html_options: { min: 1 } form_configurable :max_events, type: :number, html_options: { min: 1 } form_configurable :keep, type: :array, values: %w[newest oldest] form_configurable :max_emitted_events, type: :number, html_options: { min: 0 } form_configurable :emit_interval, type: :number, html_options: { min: 0, step: 0.001 } form_configurable :events_order, type: :json def validate_options unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0 errors.add(:base, "Please provide 'expected_receive_period_in_days' to indicate how many days can pass before this Agent is considered to be not working") end unless options['keep'].present? && options['keep'].in?(%w[newest oldest]) errors.add(:base, "The 'keep' option is required and must be set to 'oldest' or 'newest'") end unless interpolated['max_events'].present? && interpolated['max_events'].to_i > 0 errors.add(:base, "The 'max_events' option is required and must be an integer greater than 0") end if interpolated['max_emitted_events'].present? unless interpolated['max_emitted_events'].to_i > 0 errors.add(:base, "The 'max_emitted_events' option is optional and should be an integer greater than 0") end end unless interpolated['emit_interval'] in nil | 0.. | /\A\d+(?:\.\d+)?\z/ errors.add(:base, "The 'emit_interval' option should be a non-negative number if set") end end def working? last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs? end def receive(incoming_events) save! with_lock do incoming_events.each do |event| event_ids = memory['event_ids'] || [] event_ids << event.id if event_ids.length > interpolated['max_events'].to_i if options['keep'] == 'newest' event_ids.shift else event_ids.pop end end memory['event_ids'] = event_ids end end end private def extract_emitted_events! save! with_lock do emitted_events = received_events.where(id: memory['event_ids']).reorder(:id).to_a if interpolated[SortableEvents::EVENTS_ORDER_KEY].present? emitted_events = sort_events(emitted_events) end max_emitted_events = interpolated['max_emitted_events'].presence&.to_i if max_emitted_events&.< emitted_events.length emitted_events[max_emitted_events..] = [] end memory['event_ids'] -= emitted_events.map(&:id) save! emitted_events end end def check return if memory['event_ids'].blank? interval = (options['emit_interval'].presence&.to_f || 0).clamp(0..) extract_emitted_events!.each_with_index do |event, i| sleep interval unless i.zero? create_event payload: event.payload end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/java_script_agent.rb
app/models/agents/java_script_agent.rb
require 'date' require 'cgi' module Agents class JavaScriptAgent < Agent include FormConfigurable can_dry_run! default_schedule "never" gem_dependency_check { defined?(MiniRacer) } description <<~MD The JavaScript Agent allows you to write code in JavaScript that can create and receive events. If other Agents aren't meeting your needs, try this one! #{'## Include `mini_racer` in your Gemfile to use this Agent!' if dependencies_missing?} You can put code in the `code` option, or put your code in a Credential and reference it from `code` with `credential:<name>` (recommended). You can implement `Agent.check` and `Agent.receive` as you see fit. The following methods will be available on Agent in the JavaScript environment: * `this.createEvent(payload)` * `this.incomingEvents()` (the returned event objects will each have a `payload` property) * `this.memory()` * `this.memory(key)` * `this.memory(keyToSet, valueToSet)` * `this.setMemory(object)` (replaces the Agent's memory with the provided object) * `this.deleteKey(key)` (deletes a key from memory and returns the value) * `this.credential(name)` * `this.credential(name, valueToSet)` * `this.options()` * `this.options(key)` * `this.log(message)` * `this.error(message)` * `this.kvs` (whose properties are variables provided by KeyValueStoreAgents) * `this.escapeHtml(htmlToEscape)` * `this.unescapeHtml(htmlToUnescape)` MD form_configurable :language, type: :array, values: %w[JavaScript CoffeeScript] form_configurable :code, type: :text, ace: true form_configurable :expected_receive_period_in_days form_configurable :expected_update_period_in_days def validate_options cred_name = credential_referenced_by_code if cred_name errors.add(:base, "The credential '#{cred_name}' referenced by code cannot be found") unless credential(cred_name).present? else errors.add(:base, "The 'code' option is required") unless options['code'].present? end if interpolated['language'].present? && !interpolated['language'].downcase.in?(%w[javascript coffeescript]) errors.add(:base, "The 'language' must be JavaScript or CoffeeScript") end end def working? return false if recent_error_logs? if interpolated['expected_update_period_in_days'].present? return false unless event_created_within?(interpolated['expected_update_period_in_days']) end if interpolated['expected_receive_period_in_days'].present? return false unless last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago end true end def check log_errors do execute_js("check") end end def receive(incoming_events) log_errors do execute_js("receive", incoming_events) end end def default_options js_code = <<-JS Agent.check = function() { if (this.options('make_event')) { this.createEvent({ 'message': 'I made an event!' }); var callCount = this.memory('callCount') || 0; this.memory('callCount', callCount + 1); } }; Agent.receive = function() { var events = this.incomingEvents(); for(var i = 0; i < events.length; i++) { this.createEvent({ 'message': 'I got an event!', 'event_was': events[i].payload }); } } JS { 'code' => Utils.unindent(js_code), 'language' => 'JavaScript', 'expected_receive_period_in_days' => '2', 'expected_update_period_in_days' => '2' } end private def execute_js(js_function, incoming_events = []) js_function = js_function == "check" ? "check" : "receive" context = MiniRacer::Context.new context.eval(setup_javascript) context.attach("doCreateEvent", ->(y) { create_event(payload: clean_nans(JSON.parse(y))).payload.to_json }) context.attach("getIncomingEvents", -> { incoming_events.to_json }) context.attach("getOptions", -> { interpolated.to_json }) context.attach("doLog", ->(x) { log x; nil }) context.attach("doError", ->(x) { error x; nil }) context.attach("getMemory", -> { memory.to_json }) context.attach("setMemoryKey", ->(x, y) { memory[x] = clean_nans(y) }) context.attach("setMemory", ->(x) { memory.replace(clean_nans(x)) }) context.attach("deleteKey", ->(x) { memory.delete(x).to_json }) context.attach("escapeHtml", ->(x) { CGI.escapeHTML(x) }) context.attach("unescapeHtml", ->(x) { CGI.unescapeHTML(x) }) context.attach('getCredential', ->(k) { credential(k); }) context.attach('setCredential', ->(k, v) { set_credential(k, v) }) kvs = Agents::KeyValueStoreAgent.merge(controllers).find_each.to_h { |kvs| [kvs.options[:variable], kvs.memory.as_json] } context.attach("getKeyValueStores", -> { kvs }) context.eval("Object.defineProperty(Agent, 'kvs', { get: getKeyValueStores })") if (options['language'] || '').downcase == 'coffeescript' context.eval(CoffeeScript.compile(code)) else context.eval(code) end context.eval("Agent.#{js_function}();") end def code cred = credential_referenced_by_code if cred credential(cred) || 'Agent.check = function() { this.error("Unable to find credential"); };' else interpolated['code'] end end def credential_referenced_by_code (interpolated['code'] || '').strip =~ /\Acredential:(.*)\Z/ && $1 end def set_credential(name, value) c = user.user_credentials.find_or_initialize_by(credential_name: name) c.credential_value = value c.save! end def setup_javascript <<-JS function Agent() {}; Agent.createEvent = function(opts) { return JSON.parse(doCreateEvent(JSON.stringify(opts))); } Agent.incomingEvents = function() { return JSON.parse(getIncomingEvents()); } Agent.memory = function(key, value) { if (typeof(key) !== "undefined" && typeof(value) !== "undefined") { setMemoryKey(key, value); } else if (typeof(key) !== "undefined") { return JSON.parse(getMemory())[key]; } else { return JSON.parse(getMemory()); } } Agent.setMemory = function(obj) { setMemory(obj); } Agent.credential = function(name, value) { if (typeof(value) !== "undefined") { setCredential(name, value); } else { return getCredential(name); } } Agent.options = function(key) { if (typeof(key) !== "undefined") { return JSON.parse(getOptions())[key]; } else { return JSON.parse(getOptions()); } } Agent.log = function(message) { doLog(message); } Agent.error = function(message) { doError(message); } Agent.deleteKey = function(key) { return JSON.parse(deleteKey(key)); } Agent.escapeHtml = function(html) { return escapeHtml(html); } Agent.unescapeHtml = function(html) { return unescapeHtml(html); } Agent.check = function(){}; Agent.receive = function(){}; JS end def log_errors yield rescue MiniRacer::Error => e error "JavaScript error: #{e.message}" end def clean_nans(input) case input when Array input.map { |v| clean_nans(v) } when Hash input.transform_values { |v| clean_nans(v) } when Float input.nan? ? 'NaN' : input else input end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/app/models/agents/witai_agent.rb
app/models/agents/witai_agent.rb
module Agents class WitaiAgent < Agent cannot_be_scheduled! no_bulk_receive! description <<~MD The `wit.ai` agent receives events, sends a text query to your `wit.ai` instance and generates outcome events. Fill in `Server Access Token` of your `wit.ai` instance. Use [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) to fill query field. `expected_receive_period_in_days` is the expected number of days by which agent should receive events. It helps in determining if the agent is working. MD event_description <<~MD Every event have `outcomes` key with your payload as value. Sample event: {"outcome" : [ {"_text" : "set temperature to 34 degrees at 11 PM", "intent" : "get_temperature", "entities" : { "temperature" : [ { "type" : "value", "value" : 34, "unit" : "degree" }], "datetime" : [ { "grain" : "hour", "type" : "value", "value" : "2015-03-26T21:00:00.000-07:00" }]}, "confidence" : 0.556 }]} MD def default_options { 'server_access_token' => 'xxxxx', 'expected_receive_period_in_days' => 2, 'query' => '{{xxxx}}' } end def working? !recent_error_logs? && most_recent_event && event_created_within?(interpolated['expected_receive_period_in_days']) end def validate_options unless %w[server_access_token query expected_receive_period_in_days].all? { |field| options[field].present? } errors.add(:base, 'All fields are required') end end def receive(incoming_events) incoming_events.each do |event| interpolated_event = interpolated event response = HTTParty.get query_url(interpolated_event[:query]), headers create_event 'payload' => { 'outcomes' => JSON.parse(response.body)['outcomes'] } end end private def api_endpoint 'https://api.wit.ai/message?v=20141022' end def query_url(query) api_endpoint + { q: query }.to_query end def headers # oauth { headers: { 'Authorization' => 'Bearer ' + interpolated[:server_access_token] } } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false