buzzsprout-cli 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +271 -0
  4. data/bin/buzzsprout +6 -0
  5. data/lib/buzzsprout/animation/wordmark.rb +41 -0
  6. data/lib/buzzsprout/animation.rb +181 -0
  7. data/lib/buzzsprout/cli.rb +215 -0
  8. data/lib/buzzsprout/client.rb +306 -0
  9. data/lib/buzzsprout/color.rb +195 -0
  10. data/lib/buzzsprout/commands/base.rb +188 -0
  11. data/lib/buzzsprout/commands/brand_affiliations.rb +98 -0
  12. data/lib/buzzsprout/commands/chapters.rb +58 -0
  13. data/lib/buzzsprout/commands/contributors.rb +119 -0
  14. data/lib/buzzsprout/commands/downloads.rb +139 -0
  15. data/lib/buzzsprout/commands/episodes.rb +116 -0
  16. data/lib/buzzsprout/commands/fan_mail.rb +216 -0
  17. data/lib/buzzsprout/commands/feed_verifications.rb +74 -0
  18. data/lib/buzzsprout/commands/listings.rb +159 -0
  19. data/lib/buzzsprout/commands/login.rb +264 -0
  20. data/lib/buzzsprout/commands/podcasts.rb +85 -0
  21. data/lib/buzzsprout/commands/podrolls.rb +74 -0
  22. data/lib/buzzsprout/commands/skills.rb +144 -0
  23. data/lib/buzzsprout/commands/status.rb +64 -0
  24. data/lib/buzzsprout/commands/team.rb +75 -0
  25. data/lib/buzzsprout/commands/transcripts.rb +100 -0
  26. data/lib/buzzsprout/commands/update.rb +36 -0
  27. data/lib/buzzsprout/commands/uploads.rb +134 -0
  28. data/lib/buzzsprout/config.rb +125 -0
  29. data/lib/buzzsprout/formatter.rb +68 -0
  30. data/lib/buzzsprout/group_help.rb +74 -0
  31. data/lib/buzzsprout/oauth.rb +203 -0
  32. data/lib/buzzsprout/options.rb +155 -0
  33. data/lib/buzzsprout/podcast_picker.rb +328 -0
  34. data/lib/buzzsprout/redact.rb +65 -0
  35. data/lib/buzzsprout/updater.rb +230 -0
  36. data/lib/buzzsprout/version.rb +5 -0
  37. data/skills/README.md +62 -0
  38. data/skills/brand_affiliations/SKILL.md +52 -0
  39. data/skills/buzzsprout/SKILL.md +111 -0
  40. data/skills/chapters/SKILL.md +49 -0
  41. data/skills/contributors/SKILL.md +58 -0
  42. data/skills/episodes/SKILL.md +61 -0
  43. data/skills/fan_mail/SKILL.md +53 -0
  44. data/skills/feed_verifications/SKILL.md +51 -0
  45. data/skills/insertion_points/SKILL.md +50 -0
  46. data/skills/listings/SKILL.md +52 -0
  47. data/skills/podcasts/SKILL.md +57 -0
  48. data/skills/podrolls/SKILL.md +49 -0
  49. data/skills/soundbites/SKILL.md +51 -0
  50. data/skills/stats/SKILL.md +65 -0
  51. data/skills/team/SKILL.md +10 -0
  52. data/skills/transcripts/SKILL.md +60 -0
  53. data/skills/uploads/SKILL.md +68 -0
  54. metadata +102 -0
@@ -0,0 +1,203 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require 'socket'
5
+ require 'securerandom'
6
+ require 'digest'
7
+ require 'timeout'
8
+
9
+ module Buzzsprout
10
+ module OAuth
11
+ CLIENT_ID = 'X0uM4r1MG9EH0Q6y6n-nT2bvZOV7waPpVnh4FCpYF38'.freeze
12
+ CALLBACK_PATH = '/oauth/callback'
13
+ module_function
14
+
15
+ LOOPBACK_HOSTS = %w[localhost 127.0.0.1 ::1 [::1]].freeze
16
+
17
+ # Plain HTTP is allowed only for loopback development servers; tokens must not cross a network in the clear.
18
+ def secure_uri!(value)
19
+ uri = URI(value.to_s)
20
+ raise 'Invalid API URL' unless %w[https http].include?(uri.scheme) && uri.host && !uri.userinfo
21
+ if uri.scheme == 'http' && !LOOPBACK_HOSTS.include?(uri.host.downcase)
22
+ raise "Refusing to send OAuth tokens over plain HTTP to #{uri.host}. Use https in BUZZSPROUT_API_BASE."
23
+ end
24
+ uri
25
+ end
26
+
27
+ def issuer
28
+ uri = secure_uri!(Config.api_base_url)
29
+ "#{uri.scheme}://#{uri.host}#{uri.port == uri.default_port ? '' : ":#{uri.port}"}"
30
+ end
31
+
32
+ def client_id
33
+ ENV['BUZZSPROUT_OAUTH_CLIENT_ID'].to_s.empty? ? CLIENT_ID : ENV['BUZZSPROUT_OAUTH_CLIENT_ID']
34
+ end
35
+
36
+ def token_request(parameters, server: issuer)
37
+ uri = secure_uri!("#{server}/oauth/token")
38
+ request = Net::HTTP::Post.new(uri)
39
+ request['User-Agent'] = Client::USER_AGENT
40
+ request['Accept'] = 'application/json'
41
+ request.set_form_data(parameters)
42
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 15, read_timeout: 30) { |http| http.request(request) }
43
+ raise "OAuth authorization failed. Run 'buzzsprout login' to reconnect." unless response.is_a?(Net::HTTPSuccess)
44
+ data = JSON.parse(response.body)
45
+ unless data.is_a?(Hash) && data['access_token'].is_a?(String) && !data['access_token'].empty? && data['refresh_token'].is_a?(String) && !data['refresh_token'].empty? && data['token_type'].to_s.downcase == 'bearer' && data['expires_in'].to_i.positive?
46
+ raise 'Invalid OAuth token response. Run buzzsprout login again.'
47
+ end
48
+ { access_token: data['access_token'], refresh_token: data['refresh_token'], expires_at: Time.now.to_i + data['expires_in'].to_i }
49
+ rescue JSON::ParserError
50
+ raise 'Invalid OAuth token response. Run buzzsprout login again.'
51
+ end
52
+
53
+ def authorize(io:, open_browser: true, timeout: 300)
54
+ id = client_id
55
+ raise 'OAuth client registration is not configured. Set BUZZSPROUT_OAUTH_CLIENT_ID for local testing.' if id.empty?
56
+ server = TCPServer.new('127.0.0.1', 0)
57
+ redirect = "http://127.0.0.1:#{server.addr[1]}#{CALLBACK_PATH}"
58
+ state = SecureRandom.hex(32)
59
+ verifier = SecureRandom.urlsafe_base64(48)
60
+ challenge = [Digest::SHA256.digest(verifier)].pack('m0').tr('+/', '-_').delete('=')
61
+ origin = issuer
62
+ url = "#{origin}/oauth/authorize?#{URI.encode_www_form(response_type: 'code', client_id: id, redirect_uri: redirect, state: state, code_challenge: challenge, code_challenge_method: 'S256')}"
63
+ io.puts "Open this link to connect your Buzzsprout account:\n\n#{url}\n\nWaiting for authorization…"
64
+ io.flush if io.respond_to?(:flush)
65
+ launch_browser(url) if open_browser
66
+ code = wait_for_callback(server, state: state, issuer: origin, timeout: timeout)
67
+ token_request({ grant_type: 'authorization_code', client_id: id, code: code, redirect_uri: redirect, code_verifier: verifier }, server: origin).merge(client_id: id, issuer: origin, api_base: Config.api_base_url)
68
+ rescue Interrupt
69
+ raise 'Authorization cancelled. Run buzzsprout login to try again.'
70
+ ensure
71
+ server&.close
72
+ end
73
+
74
+ def wait_for_callback(server, state:, issuer:, timeout:)
75
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
76
+ loop do
77
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
78
+ raise 'Authorization timed out. Run buzzsprout login again.' unless remaining.positive? && IO.select([server], nil, nil, remaining)
79
+ socket = server.accept
80
+ begin
81
+ line = Timeout.timeout([remaining, 5].min) { socket.gets(8192) }
82
+ method, target, = line.to_s.split(' ')
83
+ uri = URI(target.to_s)
84
+ params = URI.decode_www_form(uri.query.to_s).to_h
85
+ valid = method == 'GET' && uri.path == CALLBACK_PATH && params['state'] == state && params['iss'] == issuer
86
+ code = params['code'] if valid
87
+ denied = valid && params['error']
88
+ message = callback_page(success: code && !code.empty?, client: :cli)
89
+ socket.write "HTTP/1.1 #{valid ? '200 OK' : '400 Bad Request'}\r\nContent-Type: text/html; charset=utf-8\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'\r\nConnection: close\r\nContent-Length: #{message.bytesize}\r\n\r\n#{message}"
90
+ raise 'Authorization was declined. Run buzzsprout login to try again.' if denied
91
+ return code if code && !code.empty?
92
+ rescue Timeout::Error, URI::InvalidURIError, ArgumentError, IOError, SystemCallError
93
+ # Ignore unrelated or incomplete local requests while awaiting the callback.
94
+ ensure
95
+ socket.close
96
+ end
97
+ end
98
+ end
99
+
100
+ def callback_page(success:, client: nil)
101
+ cli = client == :cli
102
+ title = success ? (cli ? "All systems go." : "You’re all set.") : "That connection didn’t make it through."
103
+ detail = if success
104
+ cli ? 'Connection approved.<br>Return to your terminal to finish connecting.' : 'Connection approved.<br>Return to your app to finish connecting.'
105
+ else
106
+ cli ? 'Head back to your terminal for details and try again.' : 'Return to your app for details and try again.'
107
+ end
108
+ <<~HTML
109
+ <!doctype html>
110
+ <html lang="en">
111
+ <head>
112
+ <meta charset="utf-8">
113
+ <meta name="viewport" content="width=device-width, initial-scale=1">
114
+ <title>Buzzsprout · Connect #{cli ? "to the CLI" : "your app"}</title>
115
+ <style>
116
+ * { box-sizing: border-box; }
117
+ body { margin: 0; min-height: 100vh; background: #fff; color: #151E1B; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
118
+ header { height: 64px; background: #F4F4F4; display: flex; justify-content: center; }
119
+ .logo { display: grid; place-items: center; width: 88px; height: 88px; margin-top: 32px; border-radius: 50%; background: white; }
120
+ .logo svg { width: 50px; height: 53px; }
121
+ main { width: min(calc(100% - 32px), 720px); margin: 105px auto 60px; text-align: center; padding: 32px 20px 48px; }
122
+ .art { margin: 36px auto; display: flex; justify-content: center; align-items: center; gap: 13px; }
123
+ .mic, .terminal { display: grid; place-items: center; width: 72px; height: 72px; border-radius: 22px; background: #E5EDE9; color: #396252; }
124
+ .terminal { background: #214538; color: #B8F2B4; font: bold 23px monospace; }
125
+ .wave { position: relative; width: 90px; height: 3px; border-radius: 4px; background: #CCDBD3; }
126
+ .wave::after { content: ''; position: absolute; left: 0; top: 50%; width: 12px; height: 12px; border-radius: 50%; background: #40d134; transform: translateY(-50%); box-shadow: 0 0 0 6px #E5FFE3; }
127
+ .failure .wave::after { animation: attempt .65s ease-in-out .3s both, vanish .01s linear .95s forwards; }
128
+ .failure .wave::before { content: '×'; position: absolute; left: 50%; top: 50%; z-index: 1; width: 27px; height: 27px; display: grid; place-items: center; border-radius: 50%; transform: translate(-50%, -50%); background: #FDF3D4; color: #7F4B14; box-shadow: 0 0 0 5px white; font: 700 20px/1 sans-serif; opacity: 0; animation: fail-shake .65s ease-in-out .95s forwards; }
129
+ @keyframes attempt { from { left: 0; } to { left: calc(50% - 6px); } }
130
+ @keyframes fail-shake { 0% { opacity: 0; transform: translate(-50%, -50%) scale(.5); } 15% { opacity: 1; transform: translate(-50%, -50%) scale(1); } 35%, 65% { opacity: 1; transform: translate(calc(-50% - 5px), -50%); } 50%, 80% { opacity: 1; transform: translate(calc(-50% + 5px), -50%); } 100% { opacity: 1; transform: translate(-50%, -50%); } }
131
+ .success .wave::after { animation: travel 1.2s ease-in-out .3s both, return-to-middle .35s ease-in 1.5s forwards, vanish .01s linear 1.85s forwards; }
132
+ .success .wave::before { content: '✓'; position: absolute; left: 50%; top: 50%; z-index: 1; width: 27px; height: 27px; display: grid; place-items: center; transform: translate(-50%, -50%) scale(.5); border-radius: 50%; background: #DBF9D9; color: #195017; box-shadow: 0 0 0 5px white; font: 800 16px/1 sans-serif; opacity: 0; animation: check-bounce .7s cubic-bezier(.2, .8, .3, 1) 1.85s forwards; }
133
+ .success .terminal { animation: pop .6s cubic-bezier(.2, 1.6, .4, 1) 1.4s both; }
134
+ @keyframes travel { from { left: 0; } to { left: calc(100% - 12px); } }
135
+ @keyframes return-to-middle { from { left: calc(100% - 12px); } to { left: calc(50% - 6px); } }
136
+ @keyframes pop { 0% { transform: scale(1); } 45% { transform: scale(1.18) rotate(-5deg); box-shadow: 0 0 0 12px #E5FFE3; } 100% { transform: scale(1); box-shadow: 0 0 0 0 transparent; } }
137
+ @keyframes vanish { to { opacity: 0; } }
138
+ @keyframes check-bounce { 0% { opacity: 0; transform: translate(-50%, -50%) scale(.45); } 25% { opacity: 1; transform: translate(-50%, -65%) scale(1.3); box-shadow: 0 0 0 12px rgba(64, 209, 52, .18); } 50% { opacity: 1; transform: translate(-50%, -45%) scale(.9); } 75% { opacity: 1; transform: translate(-50%, -55%) scale(1.08); } 100% { opacity: 1; transform: translate(-50%, -50%) scale(1); box-shadow: 0 0 0 5px white; } }
139
+ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; } .success .wave::after, .failure .wave::after { opacity: 0; } .success .wave::before, .failure .wave::before { opacity: 1; transform: translate(-50%, -50%); } }
140
+ h1 { margin: 18px 0 12px; font-size: clamp(28px, 6vw, 36px); letter-spacing: -.04em; }
141
+ p { margin: 0 auto; max-width: 620px; line-height: 1.6; color: #396252; }
142
+ .close { margin-top: 24px; font-size: 14px; color: #747576; }
143
+ </style>
144
+ </head>
145
+ <body>
146
+ <header><div class="logo" role="img" aria-label="Buzzsprout"><svg width="50" height="53" viewBox="0 0 50 53" fill="none" xmlns="http://www.w3.org/2000/svg">
147
+ <path d="M24.9923 15.0135L25.0209 0.928619H24.6767L10.2906 27.8003H25.0066L24.9994 41.7991H25.3078L39.7225 15.0135H24.9923Z" fill="#40D134"/>
148
+ <path d="M17.2762 35.5168C12.7653 31.006 6.76274 28.5174 0.380091 28.5103H0L0.0143434 28.8832C0.286861 35.1439 2.87578 41.0317 7.31494 45.4709C11.7541 49.9101 17.6419 52.499 23.9027 52.7715L24.2756 52.7858V52.4058C24.2756 46.0231 21.7799 40.0277 17.269 35.5097L17.2762 35.5168Z" fill="#214538"/>
149
+ <path d="M49.6271 28.5031C43.2445 28.5031 37.2491 30.9988 32.7311 35.5097C28.2202 40.0205 25.7317 46.0231 25.7245 52.4057V52.7858L26.0974 52.7715C32.3581 52.499 38.2459 49.9101 42.6851 45.4709C47.1243 41.0317 49.7132 35.1439 49.9857 28.8832L50.0001 28.5103H49.62L49.6271 28.5031Z" fill="#214538"/>
150
+ </svg></div></header>
151
+ <main class="#{success ? 'success' : 'failure'}">
152
+ <div class="art" aria-hidden="true">
153
+ <div class="mic"><svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v4m-4 0h8"/></svg></div>
154
+ <div class="wave"></div>
155
+ <div class="terminal">#{cli ? "&gt;_" : '<svg width="38" height="38" viewBox="0 0 38 38" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="6" width="30" height="26" rx="5"/><path d="M4 13h30M10 9.5h.01M14 9.5h.01M21 16l1.5 3.5L26 21l-3.5 1.5L21 26l-1.5-3.5L16 21l3.5-1.5L21 16Z"/></svg>'}</div>
156
+ </div>
157
+ <h1>#{title}</h1>
158
+ <p>#{detail}</p>
159
+ <p class="close">You can close this tab.</p>
160
+ </main>
161
+ </body>
162
+ </html>
163
+ HTML
164
+ end
165
+
166
+ def launch_browser(url)
167
+ command = if RUBY_PLATFORM.include?('darwin')
168
+ ['open', url]
169
+ elsif RUBY_PLATFORM.match?(/mswin|mingw/)
170
+ ['rundll32', 'url.dll,FileProtocolHandler', url]
171
+ else
172
+ ['xdg-open', url]
173
+ end
174
+ pid = Process.spawn(*command, out: File::NULL, err: File::NULL)
175
+ Process.detach(pid)
176
+ rescue SystemCallError
177
+ nil # The printed link remains available.
178
+ end
179
+
180
+ def revoke(data)
181
+ uri = secure_uri!("#{data.fetch(:issuer)}/oauth/revoke")
182
+ request = Net::HTTP::Post.new(uri)
183
+ request['User-Agent'] = Client::USER_AGENT
184
+ request.set_form_data(client_id: data.fetch(:client_id), token: data.fetch(:refresh_token), token_type_hint: 'refresh_token')
185
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 15, read_timeout: 30) { |http| http.request(request) }
186
+ raise 'Could not disconnect. Retry logout, or use --local-only to forget this connection on this computer.' unless response.is_a?(Net::HTTPSuccess)
187
+ end
188
+
189
+ def access_token
190
+ Config.with_lock do
191
+ Config.clear_cache
192
+ data = Config.loaded[:oauth]
193
+ raise 'Run buzzsprout login to connect to this server.' unless data && data[:api_base] == Config.api_base_url && data[:issuer] == issuer
194
+ if data[:expires_at].to_i <= Time.now.to_i + 60
195
+ updated = token_request({ grant_type: 'refresh_token', client_id: data[:client_id], refresh_token: data[:refresh_token] }, server: data[:issuer])
196
+ data = data.merge(updated)
197
+ Config.save(oauth: data)
198
+ end
199
+ data[:access_token]
200
+ end
201
+ end
202
+ end
203
+ end
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Buzzsprout
6
+ class Options
7
+ attr_reader :json, :no_animation, :dry_run, :token, :podcast_id, :body, :file, :format, :dir, :install_skills, :skip_skills
8
+
9
+ def initialize
10
+ @json = false
11
+ @no_animation = false
12
+ @dry_run = false
13
+ @token = nil
14
+ @podcast_id = nil
15
+ @body = nil
16
+ @file = nil
17
+ @format = nil
18
+ @dir = nil
19
+ @install_skills = false
20
+ @skip_skills = false
21
+ @fields = {}
22
+ end
23
+
24
+ def json?
25
+ @json
26
+ end
27
+
28
+ def dry_run?
29
+ @dry_run
30
+ end
31
+
32
+ def no_animation?
33
+ @no_animation || ENV['BUZZSPROUT_NO_ANIMATION'] == '1'
34
+ end
35
+
36
+ def install_skills?
37
+ @install_skills
38
+ end
39
+
40
+ def skip_skills?
41
+ @skip_skills
42
+ end
43
+
44
+ def fields
45
+ @fields
46
+ end
47
+
48
+ def extract!(args)
49
+ @json = extract_flag!(args, '--json')
50
+ @no_animation = extract_flag!(args, '--no-animation')
51
+ @dry_run = extract_flag!(args, '--dry-run')
52
+ @token = extract_option!(args, '--token')
53
+ @podcast_id = extract_option!(args, '--podcast')
54
+ @podcast_id ||= extract_option!(args, '--in')
55
+ @file = extract_option!(args, '--file')
56
+ @format = extract_option!(args, '--format')
57
+ @dir = extract_option!(args, '--dir')
58
+ @install_skills = extract_flag!(args, '--install-skills')
59
+ @skip_skills = extract_flag!(args, '--no-skills') || extract_flag!(args, '--skip-skills')
60
+ raw_body = extract_option!(args, '--body')
61
+ @body = raw_body ? JSON.parse(raw_body) : nil
62
+
63
+ extract_kv_fields!(args)
64
+ self
65
+ end
66
+
67
+ def self.parse!(args)
68
+ new.tap { |options| options.extract!(args) }
69
+ end
70
+
71
+ def merge_body(extra = {})
72
+ data = {}
73
+ data.merge!(@body) if @body.is_a?(Hash)
74
+ data.merge!(@fields)
75
+ extra.each { |key, value| data[key.to_s] = value unless value.nil? }
76
+ data
77
+ end
78
+
79
+ def extract_option!(args, flag)
80
+ self.class.extract_option!(args, flag)
81
+ end
82
+
83
+ def extract_flag!(args, flag)
84
+ self.class.extract_flag!(args, flag)
85
+ end
86
+
87
+ def self.extract_flag!(args, flag)
88
+ !!args.delete(flag)
89
+ end
90
+
91
+ def self.extract_option!(args, flag)
92
+ idx = args.index(flag)
93
+ if idx
94
+ args.delete_at(idx)
95
+ return args.delete_at(idx)
96
+ end
97
+
98
+ prefix = "#{flag}="
99
+ found = args.find { |arg| arg.start_with?(prefix) }
100
+ return unless found
101
+
102
+ args.delete(found)
103
+ found.delete_prefix(prefix)
104
+ end
105
+
106
+ private
107
+
108
+ FIELD_FLAGS = %w[
109
+ --title --description --author --artist --tags --name --email --role
110
+ --headline --url --guid --feed-url --value --expires-at --position
111
+ --language --timezone --website-address --contact-email --category
112
+ --category2 --category3 --keywords --episode-number --season-number
113
+ --episode-type --published-at --custom-url --start-time --duration
114
+ --aspect-ratio --artwork --timestamp --seconds --eligible --date --page
115
+ --per-page --filename --type --byte-size --transcript-format
116
+ --contributor-id --brand-affiliation-id --text-line-1 --text-line-2
117
+ --background-color --text-color --wave-color
118
+ ].freeze
119
+
120
+ BOOLEAN_FLAGS = %w[--private --explicit --multipart --published].freeze
121
+
122
+ def extract_kv_fields!(args)
123
+ FIELD_FLAGS.each do |flag|
124
+ value = extract_option!(args, flag)
125
+ next if value.nil?
126
+
127
+ key = flag.delete_prefix('--').tr('-', '_')
128
+ @fields[key] = coerce_number(value)
129
+ end
130
+
131
+ BOOLEAN_FLAGS.each do |flag|
132
+ key = flag.delete_prefix('--')
133
+ prefix = "#{flag}="
134
+ equals = args.find { |arg| arg.start_with?(prefix) }
135
+ if equals
136
+ args.delete(equals)
137
+ @fields[key] = truthy?(equals.delete_prefix(prefix))
138
+ elsif extract_flag!(args, flag)
139
+ @fields[key] = true
140
+ end
141
+ end
142
+ end
143
+
144
+ def truthy?(value)
145
+ %w[1 true yes y on].include?(value.to_s.downcase)
146
+ end
147
+
148
+ def coerce_number(value)
149
+ return value.to_i if value =~ /\A-?\d+\z/
150
+ return value.to_f if value =~ /\A-?\d+\.\d+\z/
151
+
152
+ value
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,328 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'io/console'
4
+ require_relative 'color'
5
+
6
+ module Buzzsprout
7
+ # Interactive TTY selector for the authenticated user's podcasts.
8
+ # Arrow keys move, typing filters by title/id, Enter selects, Esc/Ctrl-C cancels.
9
+ class PodcastPicker
10
+ class Cancelled < StandardError; end
11
+
12
+ MISSING_ID = 'Podcast id required. Pass --podcast ID (or --in ID), or run `buzzsprout podcast use`.'
13
+ WINDOW = 12
14
+ # Title, search line, hints. Reserve this plus WINDOW so redraws never scroll.
15
+ CHROME = 3
16
+
17
+ attr_reader :filter, :index, :podcasts
18
+
19
+ def initialize(podcasts, io: $stdout, stdin: $stdin, default_id: nil)
20
+ @podcasts = self.class.wrap_list(podcasts)
21
+ @io = io
22
+ @stdin = stdin
23
+ @filter = +''
24
+ @index = initial_index(default_id)
25
+ @origin_saved = false
26
+ @selected = nil
27
+ end
28
+
29
+ def self.wrap_list(data)
30
+ rows = case data
31
+ when Array then data
32
+ when Hash then [data]
33
+ else []
34
+ end
35
+ rows.map { |row| stringify(row) }
36
+ end
37
+
38
+ def self.interactive?(stdin:, json: false)
39
+ return false if json
40
+ return false if ENV['BUZZSPROUT_NONINTERACTIVE'] == '1'
41
+
42
+ stdin.respond_to?(:tty?) && stdin.tty?
43
+ end
44
+
45
+ def self.choose!(podcasts, io: $stdout, stdin: $stdin, default_id: nil, auto_single: true)
46
+ list = wrap_list(podcasts)
47
+ raise 'No podcasts on this account. Create one in Buzzsprout, then retry.' if list.empty?
48
+ return list.first if auto_single && list.size == 1
49
+
50
+ new(list, io: io, stdin: stdin, default_id: default_id).select!
51
+ end
52
+
53
+ # Human-readable row: "Title - #12345" (id dimmed when color is on).
54
+ def self.format_label(podcast, io: $stdout)
55
+ row = stringify(podcast)
56
+ title = row['title'].to_s
57
+ id_part = Color.dim(title.empty? ? "##{row['id']}" : " - ##{row['id']}", io: io)
58
+ title.empty? ? id_part : "#{title}#{id_part}"
59
+ end
60
+
61
+ def filtered
62
+ q = @filter.downcase
63
+ return @podcasts if q.empty?
64
+
65
+ @podcasts.select do |podcast|
66
+ "#{podcast['id']} #{podcast['title']}".downcase.include?(q)
67
+ end
68
+ end
69
+
70
+ def highlighted
71
+ filtered[@index]
72
+ end
73
+
74
+ def handle_key(key)
75
+ case key
76
+ when :up
77
+ move(-1)
78
+ when :down
79
+ move(1)
80
+ when :enter
81
+ item = highlighted
82
+ return :empty if item.nil?
83
+
84
+ @selected = item
85
+ :selected
86
+ when :esc, :ctrl_c
87
+ :cancelled
88
+ when :backspace
89
+ @filter = @filter.chars[0...-1].join
90
+ reindex_after_filter
91
+ when :ctrl_u
92
+ @filter = ''
93
+ reindex_after_filter
94
+ when String
95
+ @filter += key
96
+ reindex_after_filter
97
+ end
98
+ end
99
+
100
+ def select!
101
+ with_raw do
102
+ loop do
103
+ render
104
+ result = handle_key(read_key)
105
+ case result
106
+ when :selected
107
+ erase
108
+ return @selected
109
+ when :cancelled
110
+ erase
111
+ raise Cancelled, 'Podcast selection cancelled.'
112
+ end
113
+ end
114
+ end
115
+ ensure
116
+ show_cursor
117
+ end
118
+
119
+ def build_lines
120
+ items = filtered
121
+ lines = []
122
+ lines << Color.bold('Select a podcast', io: @io)
123
+ lines << search_line
124
+ if items.empty?
125
+ lines << Color.dim(' (no matches)', io: @io)
126
+ else
127
+ window_start, visible = visible_slice(items)
128
+ visible.each_with_index do |podcast, offset|
129
+ active = (window_start + offset) == @index
130
+ lines << format_row(podcast, active)
131
+ end
132
+ end
133
+ lines << Color.dim('↑/↓ move type to search Enter select Esc cancel', io: @io)
134
+ lines
135
+ end
136
+
137
+ private
138
+
139
+ def self.stringify(row)
140
+ return { 'id' => nil, 'title' => nil } unless row.is_a?(Hash)
141
+
142
+ {
143
+ 'id' => row['id'] || row[:id],
144
+ 'title' => row['title'] || row[:title]
145
+ }
146
+ end
147
+ private_class_method :stringify
148
+
149
+ def initial_index(default_id)
150
+ return 0 if default_id.nil? || default_id.to_s.empty?
151
+
152
+ found = @podcasts.index { |podcast| podcast['id'].to_s == default_id.to_s }
153
+ found || 0
154
+ end
155
+
156
+ def move(delta)
157
+ items = filtered
158
+ return if items.empty?
159
+
160
+ @index = (@index + delta) % items.size
161
+ end
162
+
163
+ def reindex_after_filter
164
+ items = filtered
165
+ @index = 0 if @index >= items.size || @index.negative?
166
+ end
167
+
168
+ def visible_slice(items)
169
+ return [0, items] if items.size <= WINDOW
170
+
171
+ start = @index - (WINDOW / 2)
172
+ start = 0 if start.negative?
173
+ max_start = items.size - WINDOW
174
+ start = max_start if start > max_start
175
+ [start, items[start, WINDOW]]
176
+ end
177
+
178
+ def format_row(podcast, active)
179
+ title = truncate(podcast['title'].to_s)
180
+ marker = active ? '▸ ' : ' '
181
+ row = { 'id' => podcast['id'], 'title' => title }
182
+ return "#{marker}#{self.class.format_label(row, io: @io)}" unless active && !title.empty?
183
+
184
+ named = Color.paint(title, Color::BOLD, highlight_code, io: @io)
185
+ "#{marker}#{named}#{Color.dim(" - ##{podcast['id']}", io: @io)}"
186
+ end
187
+
188
+ def highlight_code
189
+ hex = Color.theme(@io) == :light ? '214538' : '61D752'
190
+ r = hex[0, 2].to_i(16)
191
+ g = hex[2, 2].to_i(16)
192
+ b = hex[4, 2].to_i(16)
193
+ "\e[38;2;#{r};#{g};#{b}m"
194
+ end
195
+
196
+ def search_line
197
+ caret = Color.enabled?(@io) ? Color.paint('█', Color::DIM, io: @io) : '_'
198
+ "Search: #{@filter}#{caret}"
199
+ end
200
+
201
+ def truncate(text, width = 64)
202
+ return text if text.length <= width
203
+
204
+ "#{text[0, width - 1]}…"
205
+ end
206
+
207
+ # Saved-cursor redraw (DECSC/DECRC + ED). CSI-A by logical line count
208
+ # stair-steps when a row wraps or the screen scrolls.
209
+ def render
210
+ if @origin_saved
211
+ @io.print "\e8\e[u\r"
212
+ else
213
+ height = WINDOW + CHROME
214
+ height.times { @io.print "\n" }
215
+ @io.print "\e[#{height}A\r\e7\e[s"
216
+ @origin_saved = true
217
+ end
218
+ paint_lines(build_lines)
219
+ @io.print "\e[0J"
220
+ @io.flush if @io.respond_to?(:flush)
221
+ end
222
+
223
+ def paint_lines(lines)
224
+ lines.each do |line|
225
+ @io.print "\r\e[2K#{line}\e[0m\n"
226
+ end
227
+ end
228
+
229
+ def erase
230
+ return unless @origin_saved
231
+
232
+ @io.print "\e8\e[u\e[0m\e[0J"
233
+ @origin_saved = false
234
+ end
235
+
236
+ def with_raw
237
+ hide_cursor
238
+ if @stdin.respond_to?(:raw)
239
+ @stdin.raw { yield }
240
+ else
241
+ yield
242
+ end
243
+ end
244
+
245
+ def hide_cursor
246
+ @cursor_hidden = true
247
+ @io.print "\e[?25l" if @io.respond_to?(:print)
248
+ end
249
+
250
+ def show_cursor
251
+ return unless @cursor_hidden
252
+
253
+ @cursor_hidden = false
254
+ @io.print "\e[?25h" if @io.respond_to?(:print)
255
+ end
256
+
257
+ def read_key
258
+ ch = read_char
259
+ if ch.nil? || ch.empty?
260
+ return :cancelled
261
+ end
262
+
263
+ case ch
264
+ when "\u0003" then :ctrl_c
265
+ when "\r", "\n" then :enter
266
+ when "\u007f", "\b" then :backspace
267
+ when "\u0015" then :ctrl_u
268
+ when "\e" then read_escape
269
+ else
270
+ ch.match?(/[[:print:]]/) ? ch : nil
271
+ end
272
+ end
273
+
274
+ def read_escape
275
+ nxt = read_char_if_available
276
+ return :esc if nxt.nil? || nxt.empty?
277
+
278
+ if nxt == '[' || nxt == 'O'
279
+ code = read_char_if_available
280
+ return :up if code == 'A'
281
+ return :down if code == 'B'
282
+ end
283
+ :esc
284
+ end
285
+
286
+ def read_char
287
+ byte = read_byte
288
+ return byte if byte.nil? || byte.empty?
289
+ return byte if byte.bytesize != 1 || byte.ord < 0x80
290
+
291
+ extra = case byte.ord
292
+ when 0xC0..0xDF then 1
293
+ when 0xE0..0xEF then 2
294
+ when 0xF0..0xF7 then 3
295
+ else 0
296
+ end
297
+ extra.times { byte += read_byte.to_s }
298
+ byte.force_encoding(Encoding::UTF_8)
299
+ end
300
+
301
+ def read_char_if_available
302
+ return read_char unless real_tty?
303
+
304
+ ready, = IO.select([@stdin], nil, nil, 0.05)
305
+ return nil unless ready
306
+
307
+ read_char
308
+ end
309
+
310
+ def read_byte
311
+ if @stdin.respond_to?(:getch) && real_tty?
312
+ @stdin.getch
313
+ elsif @stdin.eof?
314
+ nil
315
+ else
316
+ @stdin.read(1)
317
+ end
318
+ rescue EOFError, IOError, Errno::EIO
319
+ nil
320
+ end
321
+
322
+ def real_tty?
323
+ @stdin.respond_to?(:to_io) && @stdin.to_io.is_a?(IO) && @stdin.respond_to?(:tty?) && @stdin.tty?
324
+ rescue StandardError
325
+ false
326
+ end
327
+ end
328
+ end