|
| 1 | +require 'oauth2' |
| 2 | +require 'webrick' |
| 3 | + |
| 4 | +FREEAGENT_APP_ID = ENV['FREEAGENT_APP_ID'] |
| 5 | +FREEAGENT_APP_SECRET = ENV['FREEAGENT_APP_SECRET'] |
| 6 | + |
| 7 | +TOKEN_FILE = './.token.yml' |
| 8 | + |
| 9 | +module Freeagent |
| 10 | + class API |
| 11 | + def initialize |
| 12 | + if FREEAGENT_APP_ID.nil? || FREEAGENT_APP_ID.empty? |
| 13 | + raise ArgumentError, 'FREEAGENT_APP_ID is unset' |
| 14 | + end |
| 15 | + if FREEAGENT_APP_SECRET.nil? || FREEAGENT_APP_SECRET.empty? |
| 16 | + raise ArgumentError, 'FREEAGENT_APP_SECRET is unset' |
| 17 | + end |
| 18 | + |
| 19 | + @token = reload || authorize |
| 20 | + File.write TOKEN_FILE, @token.to_hash.to_hash.to_yaml |
| 21 | + end |
| 22 | + |
| 23 | + private |
| 24 | + def reload |
| 25 | + if File.exist? TOKEN_FILE |
| 26 | + OAuth2::AccessToken.from_hash(client, YAML.unsafe_load_file(TOKEN_FILE)).refresh |
| 27 | + end |
| 28 | + rescue OAuth2::Error |
| 29 | + nil |
| 30 | + end |
| 31 | + |
| 32 | + def client |
| 33 | + @client ||= OAuth2::Client.new(FREEAGENT_APP_ID, FREEAGENT_APP_SECRET, |
| 34 | + site: 'https://api.freeagent.com/v2/', |
| 35 | + authorize_url: 'approve_app', |
| 36 | + token_url: 'token_endpoint' |
| 37 | + ) |
| 38 | + end |
| 39 | + |
| 40 | + def authorize |
| 41 | + receiver = WEBrick::HTTPServer.new(Port: 0) |
| 42 | + receiver_url = "http://localhost:#{receiver.config[:Port]}/" |
| 43 | + url = client.auth_code.authorize_url(redirect_uri: receiver_url) |
| 44 | + puts "Go and authorize at #{url}, I'm waiting..." |
| 45 | + |
| 46 | + access_code = nil |
| 47 | + receiver.mount_proc '/' do |req, res| |
| 48 | + # TODO: parse redirect response... |
| 49 | + access_code = req.query['code'] |
| 50 | + receiver.shutdown |
| 51 | + end |
| 52 | + |
| 53 | + Signal.trap('INT') do |
| 54 | + receiver.shutdown |
| 55 | + end |
| 56 | + |
| 57 | + receiver.start |
| 58 | + raise if access_code.nil? |
| 59 | + |
| 60 | + client.auth_code.get_token(access_code, redirect_uri: receiver_url) |
| 61 | + end |
| 62 | + |
| 63 | + def get *parts, **params |
| 64 | + relatives = parts.map(&:to_s).join('/') |
| 65 | + uri = URI.parse(relatives) |
| 66 | + puts "GET #{uri}" |
| 67 | + res = @token.get(uri, params: params, headers: {'Accept': 'application/json'}) |
| 68 | + data = res.parsed |
| 69 | + if res.headers.include? 'Link' |
| 70 | + data._links = res.headers['Link'].split(", ").map do |link| |
| 71 | + url, rel = link.split('; rel=') |
| 72 | + [rel.gsub(/^'|'$/, ''), URI::parse(url.gsub(/^<|>$/, ''))] |
| 73 | + end.to_h |
| 74 | + end |
| 75 | + data |
| 76 | + rescue => err |
| 77 | + if err.response.status == 429 |
| 78 | + retry_after = err.response.headers['retry-after'].to_i |
| 79 | + STDERR.puts "Rate limited; sleeping for #{retry_after}" |
| 80 | + sleep retry_after |
| 81 | + retry |
| 82 | + end |
| 83 | + end |
| 84 | + |
| 85 | + def get_pages *path, **params |
| 86 | + Enumerator.new do |yielder| |
| 87 | + loop do |
| 88 | + res = get(*path, **{per_page: 100}.update(params)) |
| 89 | + yielder << res |
| 90 | + break if res._links.nil? || res._links.next.nil? |
| 91 | + params = URI::decode_www_form(res._links.next.query).to_h |
| 92 | + end |
| 93 | + end |
| 94 | + end |
| 95 | + |
| 96 | + def post *parts, **params |
| 97 | + data = parts.pop |
| 98 | + relatives = parts.map(&:to_s).join('/') |
| 99 | + uri = URI.parse(relatives) |
| 100 | + puts "POST #{uri}" |
| 101 | + body = data.to_json |
| 102 | + @token.post(uri, body: body, params: params, headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}).parsed |
| 103 | + end |
| 104 | + |
| 105 | + def delete *parts, **params |
| 106 | + relatives = parts.map(&:to_s).join('/') |
| 107 | + uri = URI.parse(relatives) |
| 108 | + puts "DELETE #{uri}" |
| 109 | + @token.delete(uri, params: params, headers: {'Accept': 'application/json'}) |
| 110 | + end |
| 111 | + |
| 112 | + public |
| 113 | + def first_accounting_year_end |
| 114 | + Date.parse get('company').company.first_accounting_year_end |
| 115 | + end |
| 116 | + |
| 117 | + def periods year |
| 118 | + get('payroll', year).periods |
| 119 | + end |
| 120 | + |
| 121 | + def payslips year, period |
| 122 | + get('payroll', year, period).period.payslips |
| 123 | + end |
| 124 | + |
| 125 | + def profiles year |
| 126 | + get('payroll_profiles', year).profiles |
| 127 | + end |
| 128 | + |
| 129 | + def projects |
| 130 | + get_pages('projects').flat_map(&:projects) |
| 131 | + end |
| 132 | + |
| 133 | + def tasks project |
| 134 | + get_pages('tasks', project: project.url).flat_map(&:tasks) |
| 135 | + end |
| 136 | + |
| 137 | + def timeslips user, project, task, from, to |
| 138 | + get_pages('timeslips', user: user.url, project: project.url, task: task.url, from_date: from.to_s, to_date: to.to_s).flat_map(&:timeslips) |
| 139 | + end |
| 140 | + |
| 141 | + def create_timeslip user, project, task, dated, hours |
| 142 | + post('timeslips', { |
| 143 | + 'task' => task.url, |
| 144 | + 'project' => project.url, |
| 145 | + 'user' => user.url, |
| 146 | + 'dated_on' => dated.to_s, |
| 147 | + 'hours' => hours, |
| 148 | + }) |
| 149 | + end |
| 150 | + |
| 151 | + def batch_create_timeslips timeslips |
| 152 | + post('timeslips', {'timeslips' => timeslips}) |
| 153 | + end |
| 154 | + |
| 155 | + def delete_timeslip timeslip |
| 156 | + id = timeslip.url.split('/').last |
| 157 | + delete('timeslips', id) |
| 158 | + end |
| 159 | + |
| 160 | + def users |
| 161 | + get_pages('users').flat_map(&:users) |
| 162 | + end |
| 163 | + |
| 164 | + def user id |
| 165 | + get('users', id).user |
| 166 | + end |
| 167 | + |
| 168 | + def profile year, user |
| 169 | + get('payroll_profiles', year, user: user) |
| 170 | + end |
| 171 | + end |
| 172 | +end |
0 commit comments