-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.rb
More file actions
264 lines (216 loc) · 8 KB
/
app.rb
File metadata and controls
264 lines (216 loc) · 8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# frozen_string_literal: true
require 'sinatra'
require 'json'
require 'logger'
require 'fileutils'
require 'dotenv/load'
# Load our services
require_relative 'lib/services/comment_service'
require_relative 'lib/services/text_processor'
require_relative 'lib/helpers/modal_builder'
require_relative 'lib/config/project_config'
# Configuration
configure do
set :environment, ENV.fetch('RACK_ENV', 'development')
set :port, ENV.fetch('PORT', 3000)
# Enable debug mode in development or when explicitly set
set :debug_mode, ENV.fetch('DEBUG', nil) == 'true' || development?
# Setup logging
log_dir = if Dir.exist?('/storage')
'/storage/log'
else
File.join(settings.root, 'log')
end
FileUtils.mkdir_p(log_dir)
log_file = File.join(log_dir, "#{settings.environment}.log")
log_device = settings.environment == 'test' ? StringIO.new : log_file
set :logger, Logger.new(log_device, level: settings.debug_mode ? Logger::DEBUG : Logger::INFO)
# Configure Sinatra's built-in logging
set :logging, true
set :dump_errors, settings.debug_mode
# Add startup logging (only in debug mode)
if settings.debug_mode
puts 'Starting slack-github-threads app...'
puts "RACK_ENV: #{ENV.fetch('RACK_ENV', nil)}"
puts "PORT: #{ENV.fetch('PORT', nil)}"
puts "Environment variables loaded: #{ENV.keys.grep(/GITHUB|SLACK/).join(', ')}"
puts "Log file: #{log_file}"
end
# Load multi-project config if available
config_path = File.join(settings.root, '.config', 'projects.enc')
config_passphrase = ENV.fetch('CONFIG_PASSPHRASE', nil)
if File.exist?(config_path)
if config_passphrase
project_config = Config::ProjectConfig.new(config_path: config_path)
project_config.load!(config_passphrase)
set :project_config, project_config
settings.logger.info "Loaded #{project_config.projects.length} project(s) from encrypted config"
else
set :project_config, nil
settings.logger.warn 'Encrypted project config found but CONFIG_PASSPHRASE is not set; ' \
'falling back to environment variable credentials'
end
else
set :project_config, nil
end
# Log startup
settings.logger.info "Starting slack-github-threads app (#{settings.environment})"
end
# Helpers
helpers do
def json(response_hash)
content_type :json
response_hash.to_json
end
def debug_log(message)
puts message if settings.debug_mode
logger.debug(message)
end
def info_log(message)
logger.info(message)
end
def error_log(message)
puts "ERROR: #{message}"
logger.error(message)
end
def resolve_tokens(team_id)
if settings.project_config && team_id
project = settings.project_config.find_by_team_id(team_id)
return [project[:slack_bot_token], project[:github_token]] if project
end
[ENV.fetch('SLACK_BOT_TOKEN', nil), ENV.fetch('GITHUB_TOKEN', nil)]
end
def comment_service_for(team_id)
slack_token, github_token = resolve_tokens(team_id)
CommentService.new(slack_token, github_token, debug: settings.debug_mode, logger: logger)
end
def validate_tokens!(team_id)
slack_token, github_token = resolve_tokens(team_id)
missing = []
missing << 'Slack bot token' unless slack_token
missing << 'GitHub token' unless github_token
return if missing.empty?
halt 500, "Missing credentials: #{missing.join(', ')}"
end
end
# Health check endpoint
get '/up' do
status 200
'OK'
end
# Slack slash command endpoint
post '/ghcomment' do
team_id = params['team_id']
validate_tokens!(team_id)
issue_url = params['text']&.strip
channel_id = params['channel_id']
thread_ts = params['thread_ts'] || params['message_ts']
halt 400, 'Missing thread.' unless thread_ts
halt 400, 'Missing issue URL.' unless issue_url && !issue_url.empty?
begin
comment_url = comment_service_for(team_id).post_thread_to_github(channel_id, thread_ts, issue_url)
info_log "Successfully posted comment to GitHub: #{comment_url}"
status 200
"✅ Posted to GitHub: #{comment_url}"
rescue StandardError => e
error_log "Failed to post comment: #{e.message}"
error_log e.backtrace.join("\n")
halt 500, "Failed to post comment: #{e.message}"
end
end
# Slack shortcuts and modal submissions
post '/shortcut' do
request.body.rewind
raw_payload = request.body.read
parsed = URI.decode_www_form(raw_payload).to_h
payload = JSON.parse(parsed['payload'])
team_id = payload.dig('team', 'id') || payload.dig('user', 'team_id')
validate_tokens!(team_id)
case payload['type']
when 'shortcut'
handle_global_shortcut(payload, team_id)
when 'message_action'
handle_message_shortcut(payload, team_id)
when 'view_submission'
handle_modal_submission(payload, team_id)
else
halt 400, "Unsupported payload type: #{payload['type']}"
end
end
def handle_global_shortcut(payload, team_id)
trigger_id = payload['trigger_id']
debug_log 'DEBUG: Global shortcut triggered'
result = comment_service_for(team_id).open_global_shortcut_modal(trigger_id)
status result[:status_code]
body result[:body]
end
def handle_message_shortcut(payload, team_id)
trigger_id = payload['trigger_id']
channel_id = payload.dig('channel', 'id')
message_ts = payload.dig('message', 'ts')
thread_ts = payload.dig('message', 'thread_ts') || message_ts
debug_log "DEBUG: Message shortcut - Channel: #{channel_id}, Thread: #{thread_ts}"
result = comment_service_for(team_id).open_message_shortcut_modal(trigger_id, channel_id, thread_ts)
# For message shortcuts, return empty response if modal opened successfully
if result[:success]
status 200
body ''
else
status result[:status_code]
body result[:body]
end
end
def handle_modal_submission(payload, team_id)
callback_id = payload.dig('view', 'callback_id')
case callback_id
when 'gh_comment_modal_global'
handle_global_modal_submission(payload, team_id)
when 'gh_comment_modal_message'
handle_message_modal_submission(payload, team_id)
else
halt 400, "Unknown callback ID: #{callback_id}"
end
end
def handle_global_modal_submission(payload, team_id)
thread_url = payload.dig('view', 'state', 'values', 'thread_block', 'thread_url', 'value')
issue_url = payload.dig('view', 'state', 'values', 'issue_block', 'issue_url', 'value')
debug_log "DEBUG: Global shortcut submission - Thread URL: #{thread_url}, Issue URL: #{issue_url}"
# Parse Slack thread URL
thread_info = TextProcessor.parse_slack_thread_url(thread_url)
unless thread_info
status 200
return json(response_action: 'errors', errors: {
thread_block: 'Invalid Slack URL format. Please copy the link from a message in the thread.',
})
end
process_modal_submission(thread_info[:channel_id], thread_info[:thread_ts], issue_url, team_id)
end
def handle_message_modal_submission(payload, team_id)
metadata = JSON.parse(payload.dig('view', 'private_metadata'))
channel_id = metadata['channel_id']
thread_ts = metadata['thread_ts']
issue_url = payload.dig('view', 'state', 'values', 'issue_block', 'issue_url', 'value')
debug_log "DEBUG: Message shortcut submission - Channel: #{channel_id}, Thread: #{thread_ts}, Issue: #{issue_url}"
process_modal_submission(channel_id, thread_ts, issue_url, team_id)
end
def process_modal_submission(channel_id, thread_ts, issue_url, team_id)
# Validate GitHub issue URL
unless GitHubService.parse_issue_url(issue_url)
status 200
return json(response_action: 'errors', errors: {
issue_block: 'Invalid GitHub issue URL.',
})
end
begin
comment_service_for(team_id).post_thread_to_github(channel_id, thread_ts, issue_url)
info_log "Successfully posted comment via modal to GitHub issue: #{issue_url}"
status 200
body '' # Required response for modals
rescue StandardError => e
error_log "Failed to post comment via modal: #{e.message}"
status 200
json(response_action: 'errors', errors: {
issue_block: "Failed to post comment: #{e.message}",
})
end
end