1
|
|
|
module MediumSdk |
2
|
|
|
class Client |
3
|
|
|
attr_accessor :connection |
4
|
|
|
|
5
|
|
|
def initialize(opts = {}) |
6
|
|
|
if opts.key? :client_id |
7
|
|
|
@connection = MediumSdk::Connection::AuthCode.new opts |
8
|
|
|
elsif opts.key? :integration_token |
9
|
|
|
@connection = MediumSdk::Connection::IntegrationToken.new opts |
10
|
|
|
end |
11
|
|
|
end |
12
|
|
|
|
13
|
|
|
def get_url(url) |
14
|
|
|
return @connection.http.get do |req| |
15
|
|
|
req.url url |
16
|
|
|
end |
17
|
|
|
end |
18
|
|
|
|
19
|
|
|
def body_key(res, key) |
20
|
|
|
if res.status >= 400 |
21
|
|
|
raise "HTTP Error #{res.status} " + res.pretty_inspect |
22
|
|
|
end |
23
|
|
|
return res.body.key?(key) ? res.body[key] : nil |
24
|
|
|
end |
25
|
|
|
|
26
|
|
|
def me(reload = nil) |
27
|
|
|
if @_me.nil? || reload |
28
|
|
|
@_me = body_key get_url('me'), 'data' |
29
|
|
|
end |
30
|
|
|
return @_me |
31
|
|
|
end |
32
|
|
|
|
33
|
|
|
def me_id |
34
|
|
|
me unless @_me |
35
|
|
|
unless @_me.is_a?(Hash) && @_me.key?('id') && @_me['id'].to_s.length>0 |
36
|
|
|
raise 'Authorized User Id is unknown' |
37
|
|
|
end |
38
|
|
|
return @_me['id'] |
39
|
|
|
end |
40
|
|
|
|
41
|
|
|
def user_publications(user_id = nil) |
42
|
|
|
user_id = me_id if user_id.nil? |
43
|
|
|
res = get_url File.join 'users', user_id.to_s, 'publications' |
44
|
|
|
return body_key(res, 'data') |
45
|
|
|
end |
46
|
|
|
|
47
|
|
|
def post(post) |
48
|
|
|
url = '' |
49
|
|
|
if post.key? :publicationId |
50
|
|
|
publication_id = post[:publicationId].clone |
51
|
|
|
post.delete :publicationId |
52
|
|
|
url = File.join 'publications', publication_id, 'posts' |
53
|
|
|
else |
54
|
|
|
url = File.join 'users', me_id(), 'posts' |
55
|
|
|
end |
56
|
|
|
res = @connection.http.post do |req| |
57
|
|
|
req.url url |
58
|
|
|
req.body = post |
59
|
|
|
end |
60
|
|
|
return body_key(res, 'data') |
61
|
|
|
end |
62
|
|
|
|
63
|
|
|
def publication_contributors(publication_id) |
64
|
|
|
res = get_url File.join 'publications', publication_id, 'contributors' |
65
|
|
|
return body_key(res, 'data') |
66
|
|
|
end |
67
|
|
|
|
68
|
|
|
end |
69
|
|
|
end |
70
|
|
|
|