anzu 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d97c27bef9b0713737acc17c923dbb0064077991193e5efab38c5303c5238325
4
+ data.tar.gz: 15e036049b22d89402fc1f24aded173a68af638703a0022f16ab77d27ffaf7f6
5
+ SHA512:
6
+ metadata.gz: 7a02a88aa1394426e8c7a14642d8916e0f88d051fdb73e3fe157e2f3ff66369bc61df254d0f7382ace0eeaf09e0023f5d6949d1e34524ae3ae958049d2d19834
7
+ data.tar.gz: 55de812b8fe33b570c6914b299f0486dbafe9ffdf404eff06e3dbc40990ee6477f7a9cd52b6c46478ec4438e8423733c8b0d78d6a1c9fa11ed8935b6d475514a
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,45 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Metrics/AbcSize:
5
+ Max: 170
6
+
7
+ Metrics/BlockLength:
8
+ Max: 250
9
+
10
+ Metrics/ClassLength:
11
+ Max: 1000
12
+
13
+ Metrics/CyclomaticComplexity:
14
+ Max: 70
15
+
16
+ Metrics/MethodLength:
17
+ Max: 100
18
+
19
+ Metrics/ModuleLength:
20
+ Max: 1000
21
+
22
+ Metrics/ParameterLists:
23
+ Max: 50
24
+
25
+ Metrics/PerceivedComplexity:
26
+ Max: 80
27
+
28
+ Layout/SpaceInsideBlockBraces:
29
+ EnforcedStyle: no_space
30
+ SpaceBeforeBlockParameters: false
31
+
32
+ Layout/LineLength:
33
+ Max: 180
34
+
35
+ Style/Documentation:
36
+ Enabled: false
37
+
38
+ Style/NumericPredicate:
39
+ EnforcedStyle: comparison
40
+
41
+ Style/MultilineBlockChain:
42
+ Enabled: false
43
+
44
+ Style/SpecialGlobalVars:
45
+ EnforcedStyle: use_perl_names
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in anzu.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
data/Gemfile.lock ADDED
@@ -0,0 +1,40 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ anzu (0.1.0)
5
+ mime-types
6
+ simple_oauth
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ diff-lcs (1.5.0)
12
+ mime-types (3.4.1)
13
+ mime-types-data (~> 3.2015)
14
+ mime-types-data (3.2023.0218.1)
15
+ rake (13.0.6)
16
+ rspec (3.12.0)
17
+ rspec-core (~> 3.12.0)
18
+ rspec-expectations (~> 3.12.0)
19
+ rspec-mocks (~> 3.12.0)
20
+ rspec-core (3.12.1)
21
+ rspec-support (~> 3.12.0)
22
+ rspec-expectations (3.12.2)
23
+ diff-lcs (>= 1.2.0, < 2.0)
24
+ rspec-support (~> 3.12.0)
25
+ rspec-mocks (3.12.5)
26
+ diff-lcs (>= 1.2.0, < 2.0)
27
+ rspec-support (~> 3.12.0)
28
+ rspec-support (3.12.0)
29
+ simple_oauth (0.3.1)
30
+
31
+ PLATFORMS
32
+ arm64-darwin-22
33
+
34
+ DEPENDENCIES
35
+ anzu!
36
+ rake (~> 13.0)
37
+ rspec (~> 3.0)
38
+
39
+ BUNDLED WITH
40
+ 2.4.12
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Ishotihadus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # Anzu
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new 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/anzu`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ 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`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/anzu.
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require 'simple_oauth'
5
+ require 'uri'
6
+ require_relative 'errors'
7
+ require_relative 'endpoints/manage_tweets_v2'
8
+ require_relative 'endpoints/media_v1'
9
+
10
+ module Anzu
11
+ class Client
12
+ attr_accessor :access_token, :access_token_secret, :consumer_key, :consumer_secret, :bearer_token
13
+
14
+ def initialize(access_token: nil, access_token_secret: nil, consumer_key: nil, consumer_secret: nil, bearer_token: nil)
15
+ @access_token = access_token
16
+ @access_token_secret = access_token_secret
17
+ @consumer_key = consumer_key
18
+ @consumer_secret = consumer_secret
19
+ @bearer_token = bearer_token
20
+
21
+ yield(self) if block_given?
22
+ end
23
+
24
+ def req_bearer(method, url)
25
+ uri = URI.parse(url)
26
+
27
+ req_klass = Net::HTTP.const_get(method.capitalize)
28
+ req = req_klass.new(uri)
29
+
30
+ req['authorization'] = "Bearer #{@bearer_token}"
31
+ yield(req) if block_given?
32
+
33
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
34
+ http.request(req)
35
+ end
36
+ end
37
+
38
+ def req_oauth1(method, url)
39
+ uri = URI.parse(url)
40
+
41
+ req_klass = Net::HTTP.const_get(method.to_s.capitalize)
42
+ req = req_klass.new(uri)
43
+
44
+ req['authorization'] =
45
+ SimpleOAuth::Header.new(method, url, {}, consumer_key: @consumer_key, consumer_secret: @consumer_secret, token: @access_token, token_secret: @access_token_secret).to_s
46
+ yield(req) if block_given?
47
+
48
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
49
+ http.request(req)
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'uri'
5
+
6
+ module Anzu
7
+ class Client
8
+ def create_tweet_v2(
9
+ text,
10
+ direct_message_deep_link: nil,
11
+ for_super_followers_only: nil,
12
+ geo_place_id: nil,
13
+ media_ids: nil,
14
+ media_tagged_user_ids: nil,
15
+ poll_duration_minutes: nil,
16
+ poll_options: nil,
17
+ quote_tweet_id: nil,
18
+ exclude_reply_user_ids: nil,
19
+ in_reply_to_tweet_id: nil,
20
+ reply_settings: nil
21
+ )
22
+ options = {
23
+ direct_message_deep_link: direct_message_deep_link,
24
+ for_super_followers_only: for_super_followers_only,
25
+ geo: geo_place_id && { place_id: geo_place_id }.compact,
26
+ media: media_ids && { media_ids: media_ids, tagged_user_ids: media_tagged_user_ids }.compact,
27
+ poll: poll_options && { duration_minutes: poll_duration_minutes, options: poll_options }.compact,
28
+ quote_tweet_id: quote_tweet_id,
29
+ reply: in_reply_to_tweet_id && { in_reply_to_tweet_id: in_reply_to_tweet_id, exclude_reply_user_ids: exclude_reply_user_ids }.compact,
30
+ reply_settings: reply_settings,
31
+ text: text
32
+ }
33
+ options.compact!
34
+
35
+ res = req_oauth1(:post, 'https://api.twitter.com/2/tweets') do |req|
36
+ req.content_type = 'application/json; charset=UTF-8'
37
+ req.body = options.to_json
38
+ end
39
+ Error.raise_from_response(res)
40
+
41
+ json = JSON.parse(res.body)
42
+ { id: json['data']['id'], text: json['data']['text'] }
43
+ end
44
+
45
+ def delete_tweet_v2(id)
46
+ res = req_oauth1(:delete, "https://api.twitter.com/2/tweets/#{URI.encode_www_form_component(id.to_s)}")
47
+ Error.raise_from_response(res)
48
+
49
+ json = JSON.parse(res.body)
50
+ { deleted: json['data']['deleted'] }
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'mime/types'
4
+ require 'json'
5
+ require 'uri'
6
+
7
+ module Anzu
8
+ class Client
9
+ UPLAOD_MEDIA_SEGMENT_SIZE = 5_000_000
10
+
11
+ # Upload media (chunked)
12
+ # https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/uploading-media/chunked-media-upload
13
+ # @param [String | File] bin
14
+ # @param [String | nil] mime_type
15
+ # @param [String | nil] media_category Must be nil, tweet_image, tweet_video, tweet_gif, dm_image, dm_video, dm_gif, or subtitles
16
+ # @param [Array<String>] additional_owners
17
+ def upload_media_v1(bin, mime_type = nil, media_category: nil, additional_owners: nil)
18
+ unless mime_type
19
+ file = bin.is_a?(String) ? File.open(bin, 'rb') : bin
20
+ file.binmode
21
+ file.rewind
22
+ bin = file.read
23
+ mime_type ||= MIME::Types.type_for(file.path).find {|e| e.media_type == 'image' || e.media_type == 'video'}&.content_type
24
+ end
25
+
26
+ unless media_category
27
+ if mime_type == 'image/gif'
28
+ media_category = 'tweet_gif'
29
+ elsif mime_type == 'application/x-subrip'
30
+ media_category = 'subtitles'
31
+ elsif mime_type.start_with?('image/')
32
+ media_category = 'tweet_image'
33
+ elsif mime_type.start_with?('video/')
34
+ media_category = 'tweet_video'
35
+ end
36
+ end
37
+
38
+ bytesize = bin.bytesize
39
+
40
+ init_res = req_oauth1(:post, 'https://upload.twitter.com/1.1/media/upload.json') do |req|
41
+ req.set_form(
42
+ [
43
+ %w[command INIT],
44
+ ['total_bytes', bytesize.to_s],
45
+ ['media_type', mime_type],
46
+ media_category && ['media_category', media_category],
47
+ additional_owners && ['additional_owners', additional_owners.join(',')]
48
+ ].compact,
49
+ 'multipart/form-data'
50
+ )
51
+ puts req.body
52
+ end
53
+ Error.raise_from_response(init_res)
54
+ init_json = JSON.parse(init_res.body)
55
+
56
+ count = (bytesize + UPLAOD_MEDIA_SEGMENT_SIZE - 1) / UPLAOD_MEDIA_SEGMENT_SIZE
57
+ count.times do |i|
58
+ append_res = req_oauth1(:post, 'https://upload.twitter.com/1.1/media/upload.json') do |req|
59
+ req.set_form(
60
+ [
61
+ %w[command APPEND],
62
+ ['media_id', init_json['media_id_string']],
63
+ ['media', bin.byteslice(i * UPLAOD_MEDIA_SEGMENT_SIZE, UPLAOD_MEDIA_SEGMENT_SIZE), { content_type: 'application/octet-stream' }],
64
+ ['segment_index', i.to_s]
65
+ ],
66
+ 'multipart/form-data'
67
+ )
68
+ end
69
+ Error.raise_from_response(append_res)
70
+ end
71
+
72
+ finalize_res = req_oauth1(:post, 'https://upload.twitter.com/1.1/media/upload.json') do |req|
73
+ req.set_form([%w[command FINALIZE], ['media_id', init_json['media_id_string']]], 'multipart/form-data')
74
+ end
75
+ Error.raise_from_response(finalize_res)
76
+
77
+ json = JSON.parse(finalize_res.body)
78
+
79
+ if json['processing_info'] && json['processing_info']['state'] == 'pending'
80
+ sleep json['processing_info']['check_after_secs']
81
+
82
+ loop do
83
+ status_res = req_oauth1(:get, "https://upload.twitter.com/1.1/media/upload.json?command=STATUS&media_id=#{URI.encode_www_form_component(json['media_id_string'])}")
84
+ Error.raise_from_response(status_res)
85
+ status_json = JSON.parse(status_res.body)
86
+
87
+ case status_json['processing_info']['state']
88
+ when 'succeeded'
89
+ break
90
+ when 'failed'
91
+ raise MediaUploadError.new(status_json['processing_info']['error']['code'], status_json['processing_info']['error']['name'],
92
+ status_json['processing_info']['error']['message'])
93
+ when 'pending'
94
+ sleep status_json['processing_info']['check_after_secs']
95
+ end
96
+ end
97
+ end
98
+
99
+ {
100
+ media_id: json['media_id_string'],
101
+ expires_after_secs: json['expires_after_secs'],
102
+ size: json['size']
103
+ }
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anzu
4
+ class Error < StandardError
5
+ def self.raise_from_response(response)
6
+ response.value
7
+ rescue StandardError
8
+ begin
9
+ json = JSON.parse(response.body)
10
+ raise Error, json['error']
11
+ rescue StandardError
12
+ raise Error, response.body
13
+ end
14
+ end
15
+ end
16
+
17
+ class MediaUploadError < StandardError
18
+ def initialize(code, name, message)
19
+ @code = code
20
+ @name = name
21
+ @message = message
22
+ super("#{code}: #{name} - #{message}")
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anzu
4
+ VERSION = '0.1.0'
5
+ end
data/lib/anzu.rb ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'anzu/client'
4
+ require_relative 'anzu/version'
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: anzu
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ishotihadus
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2023-04-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: mime-types
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: simple_oauth
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: Twitter API wrapper for Ruby
42
+ email:
43
+ - hanachan.pao@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".rspec"
49
+ - ".rubocop.yml"
50
+ - Gemfile
51
+ - Gemfile.lock
52
+ - LICENSE
53
+ - README.md
54
+ - Rakefile
55
+ - lib/anzu.rb
56
+ - lib/anzu/client.rb
57
+ - lib/anzu/endpoints/manage_tweets_v2.rb
58
+ - lib/anzu/endpoints/media_v1.rb
59
+ - lib/anzu/errors.rb
60
+ - lib/anzu/version.rb
61
+ homepage: https://github.com/Ishotihadus/anzu
62
+ licenses: []
63
+ metadata:
64
+ homepage_uri: https://github.com/Ishotihadus/anzu
65
+ source_code_uri: https://github.com/Ishotihadus/anzu
66
+ post_install_message:
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 2.6.0
75
+ required_rubygems_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ requirements: []
81
+ rubygems_version: 3.4.1
82
+ signing_key:
83
+ specification_version: 4
84
+ summary: Twitter API wrapper for Ruby
85
+ test_files: []