From af1c8df84ee1c5c83716839a5f277dc68e534c78 Mon Sep 17 00:00:00 2001 From: Nicolas Germain Date: Sat, 2 Dec 2023 14:46:08 +0100 Subject: [PATCH] first commit --- .github/workflows/ruby.yml | 43 +++++ Gemfile | 4 + LICENSE.txt | 7 + README.md | 49 ++++- Rakefile | 5 + huginn_bluesky_publish_agent.gemspec | 28 +++ lib/huginn_bluesky_publish_agent.rb | 4 + .../bluesky_publish_agent.rb | 176 ++++++++++++++++++ spec/bluesky_publish_agent_spec.rb | 13 ++ 9 files changed, 327 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/ruby.yml create mode 100644 Gemfile create mode 100644 LICENSE.txt create mode 100644 Rakefile create mode 100644 huginn_bluesky_publish_agent.gemspec create mode 100644 lib/huginn_bluesky_publish_agent.rb create mode 100644 lib/huginn_bluesky_publish_agent/bluesky_publish_agent.rb create mode 100644 spec/bluesky_publish_agent_spec.rb diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml new file mode 100644 index 0000000..7786575 --- /dev/null +++ b/.github/workflows/ruby.yml @@ -0,0 +1,43 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake +# For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby + +name: Ruby + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + test: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@359bebbc29cbe6c87da6bc9ea3bc930432750108 + with: + ruby-version: '3.1.0' + - name: Install dependencies + run: bundle install +# - name: Rubocop +# run: rubocop +# - name: Run tests +# run: bundle exec rake + + - name: Publish to RubyGems + run: | + mkdir -p $HOME/.gem + touch $HOME/.gem/credentials + chmod 0600 $HOME/.gem/credentials + printf -- "---\n:rubygems_api_key: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials + gem build *.gemspec + gem push *.gem + env: + GEM_HOST_API_KEY: "${{secrets.RUBYGEMS_AUTH_TOKEN}}" diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..facd86b --- /dev/null +++ b/Gemfile @@ -0,0 +1,4 @@ +source 'https://rubygems.org' + +gemspec +gem 'huginn_agent', '~> 0.6.1' \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..b2e3ccb --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright (c) 2023 Nicolas Germain + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 1c0f12f..715058d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,47 @@ -# huginn_bluesky_publish_agent - huginn agent to post on bluesky +# BlueskyPublishAgent + +Welcome to your new agent gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/huginn_bluesky_publish_agent`. To experiment with that code, run `bin/console` for an interactive prompt. + +TODO: Delete this and the text above, and describe your gem + +## Installation + +This gem is run as part of the [Huginn](https://github.com/huginn/huginn) project. If you haven't already, follow the [Getting Started](https://github.com/huginn/huginn#getting-started) instructions there. + +Add this string to your Huginn's .env `ADDITIONAL_GEMS` configuration: + +```ruby +huginn_bluesky_publish_agent +# when only using this agent gem it should look like this: +ADDITIONAL_GEMS=huginn_bluesky_publish_agent +``` + +And then execute: + + $ bundle + +## Usage + +TODO: Write usage instructions here + +## Development + +Running `rake` will clone and set up Huginn in `spec/huginn` to run the specs of the Gem in Huginn as if they would be build-in Agents. The desired Huginn repository and branch can be modified in the `Rakefile`: + +```ruby +HuginnAgent.load_tasks(branch: '', remote: 'https://github.com//huginn.git') +``` + +Make sure to delete the `spec/huginn` directory and re-run `rake` after changing the `remote` to update the Huginn source code. + +After the setup is done `rake spec` will only run the tests, without cloning the Huginn source again. + +To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). + +## Contributing + +1. Fork it ( https://github.com/[my-github-username]/huginn_bluesky_publish_agent/fork ) +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create a new Pull Request diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..dd2a952 --- /dev/null +++ b/Rakefile @@ -0,0 +1,5 @@ +#!/usr/bin/env rake + +require 'huginn_agent' + +HuginnAgent.load_tasks(branch: 'master', remote: 'https://github.com/cantino/huginn.git') diff --git a/huginn_bluesky_publish_agent.gemspec b/huginn_bluesky_publish_agent.gemspec new file mode 100644 index 0000000..ccea3a2 --- /dev/null +++ b/huginn_bluesky_publish_agent.gemspec @@ -0,0 +1,28 @@ +# coding: utf-8 +lib = File.expand_path('../lib', __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) + +Gem::Specification.new do |spec| + spec.name = "huginn_bluesky_publish_agent" + spec.version = '0.1.0' + spec.authors = ["Nicolas Germain"] + spec.email = ["ngermain@hihouhou.com"] + + spec.summary = %q{Write a short summary, because Rubygems requires one.} + spec.description = %q{Write a longer description or delete this line.} + + spec.homepage = "https://github.com/hihouhou/huginn_bluesky_publish_agent" + + spec.license = "MIT" + + + spec.files = Dir['LICENSE.txt', 'lib/**/*'] + spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } + spec.test_files = Dir['spec/**/*.rb'].reject { |f| f[%r{^spec/huginn}] } + spec.require_paths = ["lib"] + + spec.add_development_dependency "bundler", ">= 2.1.0" + spec.add_development_dependency "rake", "~> 12.3.3" + + spec.add_runtime_dependency "huginn_agent" +end diff --git a/lib/huginn_bluesky_publish_agent.rb b/lib/huginn_bluesky_publish_agent.rb new file mode 100644 index 0000000..61c3bf4 --- /dev/null +++ b/lib/huginn_bluesky_publish_agent.rb @@ -0,0 +1,4 @@ +require 'huginn_agent' + +#HuginnAgent.load 'huginn_bluesky_publish_agent/concerns/my_agent_concern' +HuginnAgent.register 'huginn_bluesky_publish_agent/bluesky_publish_agent' diff --git a/lib/huginn_bluesky_publish_agent/bluesky_publish_agent.rb b/lib/huginn_bluesky_publish_agent/bluesky_publish_agent.rb new file mode 100644 index 0000000..ee1f573 --- /dev/null +++ b/lib/huginn_bluesky_publish_agent/bluesky_publish_agent.rb @@ -0,0 +1,176 @@ +module Agents + class BlueskyPublishAgent < Agent + include FormConfigurable + can_dry_run! + no_bulk_receive! + default_schedule 'every_1h' + + description do + <<-MD + The Bluesky Publish Agent publishes posts from the events it receives. + + To be able to use this Agent you need to authenticate with Twitter with [twurl](https://github.com/twitter/twurl). + + You must also specify a `message` parameter, you can use [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) to format the message. + Additional parameters can be passed via `parameters`. + + `debug` is used for verbose mode. + + `handle` is mandatory for authentication. + + `app_password` is mandatory for authentication. + + `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. + MD + end + + event_description <<-MD + Events look like this: + + { + "uri": "at://did:plc:XXXXXXXXXXXXXXXXXXXXXXXX/app.bsky.feed.post/XXXXXXXXXXXXX", + "cid": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + } + MD + + def default_options + { + 'message' => "{{text}}", + 'debug' => 'false', + 'handle' => '', + 'app_password' => '', + 'emit_events' => 'true', + 'expected_receive_period_in_days' => '2', + } + end + + form_configurable :message, type: :string + form_configurable :debug, type: :boolean + form_configurable :app_password, type: :string + form_configurable :handle, type: :string + form_configurable :emit_events, type: :boolean + form_configurable :expected_receive_period_in_days, type: :string + def validate_options + unless options['message'].present? + errors.add(:base, "message is a required field") + end + + unless options['app_password'].present? + errors.add(:base, "app_password is a required field") + 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 + + unless options['handle'].present? + errors.add(:base, "handle is a required field") + end + + if options.has_key?('debug') && boolify(options['debug']).nil? + errors.add(:base, "if provided, debug must be true or false") + end + + 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 + end + + def working? + event_created_within?(options['expected_receive_period_in_days']) && !recent_error_logs? + end + + def receive(incoming_events) + incoming_events.each do |event| + interpolate_with(event) do + log event + publish() + end + end + end + + def check + publish() + end + + private + + def log_curl_output(code,body) + + log "request status : #{code}" + + if interpolated['debug'] == 'true' + log "body" + log body + end + + end + + def generate_did() + uri = URI.parse("https://bsky.social/xrpc/com.atproto.identity.resolveHandle") + params = { :handle => interpolated['handle'] } + uri.query = URI.encode_www_form(params) + response = Net::HTTP.get_response(uri) + + log_curl_output(response.code,response.body) + + return JSON.parse(response.body)['did'] + end + + def generate_api_key(did) + uri = URI.parse("https://bsky.social/xrpc/com.atproto.server.createSession") + request = Net::HTTP::Post.new(uri) + request.content_type = "application/json" + request.body = JSON.dump({ + "identifier" => did, + "password" => interpolated['app_password'] + }) + + req_options = { + use_ssl: uri.scheme == "https", + } + + response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| + http.request(request) + end + + log_curl_output(response.code,response.body) + + return JSON.parse(response.body)['accessJwt'] + end + + def publish() + + did = generate_did() + uri = URI.parse("https://bsky.social/xrpc/com.atproto.repo.createRecord") + request = Net::HTTP::Post.new(uri) + request.content_type = "application/json" + request["Authorization"] = "Bearer #{generate_api_key(did)}" + request.body = JSON.dump({ + "collection" => "app.bsky.feed.post", + "repo" => did, + "record" => { + "text" => interpolated['message'], + "createdAt" => Time.now.strftime('%Y-%m-%dT%H:%M:%S.%3NZ'), + "$type" => "app.bsky.feed.post" + } + }) + + req_options = { + use_ssl: uri.scheme == "https", + } + + response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| + http.request(request) + end + + log_curl_output(response.code,response.body) + + if interpolated['emit_events'] == 'true' + create_event payload: response.body + end + + end + end +end diff --git a/spec/bluesky_publish_agent_spec.rb b/spec/bluesky_publish_agent_spec.rb new file mode 100644 index 0000000..b116667 --- /dev/null +++ b/spec/bluesky_publish_agent_spec.rb @@ -0,0 +1,13 @@ +require 'rails_helper' +require 'huginn_agent/spec_helper' + +describe Agents::BlueskyPublishAgent do + before(:each) do + @valid_options = Agents::BlueskyPublishAgent.new.default_options + @checker = Agents::BlueskyPublishAgent.new(:name => "BlueskyPublishAgent", :options => @valid_options) + @checker.user = users(:bob) + @checker.save! + end + + pending "add specs here" +end