diff --git a/lib/zendesk_apps_tools/server.rb b/lib/zendesk_apps_tools/server.rb index e79a219f..9b784592 100644 --- a/lib/zendesk_apps_tools/server.rb +++ b/lib/zendesk_apps_tools/server.rb @@ -10,12 +10,77 @@ class Server < Sinatra::Base set :protection, except: :frame_options ZENDESK_DOMAINS_REGEX = %r{^http(?:s)?://[a-z0-9-]+\.(?:zendesk|zopim|futuresimple|local.futuresimple|zendesk-(?:dev|master|staging))\.com$} + get '/app.json' do + server_installed_json + end + get '/app.js' do serve_installed_js end enable :cross_origin + def server_installed_json + access_control_allow_origin + content_type 'application/json' + + apps = [] + installations = [] + + absolute_app_path = File.join(settings.root) + + manifest_json = read_json(File.join(absolute_app_path, 'manifest.json')) + requirements_json = read_json(File.join(absolute_app_path, 'requirements.json')) || nil + + new_settings = settings.settings_helper.refresh! + settings.parameters = new_settings if new_settings + + # add title to settings + settings.parameters['title'] = manifest_json['name'] || 'Local App' + + apps << build_app_object( + settings, + manifest_json + ) + + installations << build_installation_object( + settings, + requirements_json + ) + + { + apps: apps, + installations: installations, + installation_orders: [] + }.to_json + end + + def build_app_object(settings, manifest) + manifest.merge({ + asset_url_prefix: "http://localhost:#{settings.port}/", + id: settings.app_id + }).reject {|key| ['parameters', 'oauth'].include?(key) } + end + + def build_installation_object(settings, requirements) + { + app_id: settings.app_id, + name: settings.parameters['title'], + collapsible: true, + enabled: true, + id: settings.app_id, + plan: { name: settings.plan }, + requirements: requirements, + settings: settings.parameters, + updated_at: Time.now.iso8601 + } + end + + def read_json(path, parser_opts = {}) + file = File.read(path) if File.exists?(path) + JSON.parse(file, parser_opts) unless file.nil? + end + def serve_installed_js access_control_allow_origin content_type 'text/javascript'