lark-sdk 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: caef8276e49452db055962b584d3b1900c69ddb9c0f09a3b130a6a66df60f071
4
+ data.tar.gz: 060b65c302d12a6701b557ad43991bce65e4717141f3d276841e4c0428329676
5
+ SHA512:
6
+ metadata.gz: f019f2991e57395777bd1db64222d5dd860cd6b4edbd56fb7b068efeb4ee28d90877b72ca23361157148232c7d1d2ea3d4f45ce524846be52083cf143f76f048
7
+ data.tar.gz: e4f55e4f88c4bbe4cd3fee4adef81d98900e56256f64524c0e397caefda4451ebee7a20a826d8c4d579d5f8a77e76e8e23d5a22871587f5ff760d8532d42fc8b
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ *.gem
10
+ Gemfile.lock
11
+ .DS_Store
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.7.0
6
+ before_install: gem install bundler -v 2.1.2
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at sindon@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in lark.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "minitest", "~> 5.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 seandong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,123 @@
1
+ # Lark
2
+
3
+ Unofficial ruby SDKS for lark [飞书](https://www.feishu.cn/)
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'lark'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install lark
20
+
21
+
22
+ ## Usage
23
+
24
+ Add initialize configure to your project:
25
+
26
+ ```ruby
27
+ # config/initializers/lark.rb
28
+
29
+ Lark.configure do |config|
30
+ config.redis = Redis.new(url: 'redis://127.0.0.1:6379/1')
31
+ # ...
32
+ end
33
+ ```
34
+
35
+ Create lark API
36
+
37
+ ```ruby
38
+ api = Lark::Api.new(
39
+ app_id: 'xxx',
40
+ app_secret: 'xxx',
41
+ tenant_key: 'xxx',
42
+ isv: false/true, # Internal app: false, ISV app: true
43
+ )
44
+ ```
45
+
46
+ Invoke lark api, For example:
47
+
48
+ ```ruby
49
+ # Get chat list
50
+ api.contact.list
51
+ ```
52
+
53
+ Decrypt message
54
+
55
+ ```ruby
56
+ Lark::Cipher.new(encrypt_key).decrypt(message)
57
+
58
+ # eg:
59
+ # encrypt = "P37w+VZImNgPEO1RBhJ6RtKl7n6zymIbEG1pReEzghk="
60
+ # Lark::Cipher.new('test key').decrypt encrypt
61
+ # => 'hello world'
62
+ ```
63
+
64
+ ## Api List
65
+
66
+ ### 授权 (auth)
67
+
68
+ 获取 app_access_token
69
+
70
+ api.app_access_token
71
+
72
+ 获取 tenant_access_token
73
+
74
+ api.tenant_access_token
75
+
76
+ 重新推送 app_ticket
77
+
78
+ api.auth.app_ticket_resend
79
+
80
+ 更新 app_ticket
81
+
82
+ api.app_ticket = xxxx
83
+
84
+ ### 身份验证 (authen)
85
+
86
+ 请求身份验证
87
+
88
+ api.authen.index(redirect_uri, state)
89
+
90
+ 获取登录用户身份
91
+
92
+ api.authen.access_token(code)
93
+
94
+ 刷新 access_token
95
+
96
+ api.authen.refresh_access_token(refresh_token)
97
+
98
+ 获取用户信息
99
+
100
+ api.user_info(user_access_token)
101
+
102
+
103
+ ...
104
+
105
+
106
+ ## Development
107
+
108
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
109
+
110
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
111
+
112
+ ## Contributing
113
+
114
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/lark. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/lark/blob/master/CODE_OF_CONDUCT.md).
115
+
116
+
117
+ ## License
118
+
119
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
120
+
121
+ ## Code of Conduct
122
+
123
+ Everyone interacting in the Lark project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/lark/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "lark"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lark.gemspec ADDED
@@ -0,0 +1,37 @@
1
+ require_relative 'lib/lark/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "lark-sdk"
5
+ spec.version = Lark::VERSION
6
+ spec.authors = ["Sean Dong"]
7
+ spec.email = ["sindon@gmail.com"]
8
+
9
+ spec.summary = %q{Lark SDKs for ruby}
10
+ spec.description = %q{Unoffical Lark(飞书) SDKs for ruby https://open.feishu.cn}
11
+ spec.homepage = "https://github.com/mycolorway/lark-ruby-sdk"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ spec.metadata["allowed_push_host"] = "https://rubygems.org/"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/mycolorway/lark-ruby-sdk"
19
+ spec.metadata["changelog_uri"] = "https://github.com/mycolorway/lark-ruby-sdk"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ end
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_dependency 'http', '>= 2.2'
31
+ spec.add_dependency 'activesupport', '>= 5.0'
32
+ spec.add_dependency 'redis'
33
+
34
+ spec.add_development_dependency "bundler", ">= 1.13"
35
+ spec.add_development_dependency "rake", "~> 10.0"
36
+ spec.add_development_dependency "minitest", "~> 5.10"
37
+ end
data/lib/lark/api.rb ADDED
@@ -0,0 +1,90 @@
1
+ require 'lark/request'
2
+
3
+ module Lark
4
+ class Api
5
+ include Route
6
+ include Apis::Message
7
+ include Apis::Chat
8
+
9
+ mount :auth
10
+ mount :authen
11
+ mount :contact
12
+ mount :chat
13
+ mount :message
14
+
15
+ attr_reader :app_id, :app_secret, :tenant_key, :isv, :options
16
+
17
+ def initialize options={}
18
+ @app_id = options.delete(:app_id) || Lark.app_id
19
+ @app_secret = options.delete(:app_secret) || Lark.app_secret
20
+ @tenant_key = options.delete(:tenant_key)
21
+ @isv = options.delete(:isv) || false
22
+ @options = options
23
+ end
24
+
25
+ def valid?
26
+ app_token_store.valid? && tenant_token_store.valid?
27
+ end
28
+
29
+ def request
30
+ @request ||= Lark::Request.new(false)
31
+ end
32
+
33
+ def get(path, headers={})
34
+ with_token(headers) do |headers|
35
+ request.get path, headers
36
+ end
37
+ end
38
+
39
+ def post(path, payload, headers={})
40
+ with_token(headers) do |headers|
41
+ request.post path, payload, headers
42
+ end
43
+ end
44
+
45
+ def post_file(path, file, headers={})
46
+ with_token(headers) do |headers|
47
+ request.post_file path, file, headers
48
+ end
49
+ end
50
+
51
+ def app_ticket= ticket
52
+ Lark.redis.set "APP_TICKET_#{app_id}", ticket
53
+ end
54
+
55
+ def app_ticket
56
+ Lark.redis.get "APP_TICKET_#{app_id}"
57
+ end
58
+
59
+ def app_access_token
60
+ app_token_store.token
61
+ end
62
+
63
+ def tenant_access_token
64
+ tenant_token_store.token
65
+ end
66
+
67
+ private
68
+
69
+ def app_token_store
70
+ return @app_token_store if defined?(@app_token_store)
71
+ klass = isv ? TokenStore::IsvAppToken : TokenStore::AppToken
72
+ @app_token_store = klass.new(self)
73
+ end
74
+
75
+ def tenant_token_store
76
+ return @tenant_token_store if defined?(@tenant_token_store)
77
+ klass = isv ? TokenStore::IsvTenantToken : TokenStore::TenantToken
78
+ @tenant_token_store = klass.new(self)
79
+ end
80
+
81
+ def with_token(headers, tries=2)
82
+ via = headers[:via] || 'tenant'
83
+ token = send("#{via}_access_token")
84
+ yield headers.merge(authorization: "Bearer #{token}")
85
+ rescue AccessTokenExpiredError
86
+ send("#{via}_token_store").fetch_token
87
+ retry unless (tries -= 1).zero?
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,12 @@
1
+ module Lark
2
+ module Apis
3
+ module Auth
4
+ def app_ticket_resend
5
+ request.post 'auth/v3/app_ticket/resend/', {
6
+ app_id: app_id,
7
+ app_secret: app_secret
8
+ }
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,32 @@
1
+ require "erb"
2
+
3
+ module Lark
4
+ module Apis
5
+ module Authen
6
+ def index(redirect_uri, state)
7
+ uri = ERB::Util.url_encode(redirect_uri)
8
+ "#{URI::join(API_BASE_URL, 'authen/v1/index')}?redirect_uri=#{uri}&app_id=#{app_id}&state=#{state}"
9
+ end
10
+
11
+ def access_token(code)
12
+ request.post 'authen/v1/access_token', {
13
+ code: code,
14
+ app_access_token: app_access_token,
15
+ grant_type: 'authorization_code'
16
+ }
17
+ end
18
+
19
+ def refresh_access_token(token)
20
+ request.post 'authen/v1/refresh_access_token', {
21
+ refresh_token: token,
22
+ app_access_token: app_access_token,
23
+ grant_type: 'refresh_token'
24
+ }
25
+ end
26
+
27
+ def user_info(user_access_token)
28
+ request.get('authen/v1/user_info', params: {user_access_token: user_access_token})
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,9 @@
1
+ module Lark
2
+ module Apis
3
+ module Chat
4
+ def list(params={})
5
+ post 'chat/v4/list', params: params
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,13 @@
1
+ module Lark
2
+ module Apis
3
+ module Contact
4
+ def scope_get
5
+ get 'contact/v1/scope/get'
6
+ end
7
+
8
+ def department_add(payload={})
9
+ post 'contact/v1/department/add', payload
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,9 @@
1
+ module Lark
2
+ module Apis
3
+ module Message
4
+ def send(payload)
5
+ post 'message/v4/send/', payload
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,34 @@
1
+ require 'openssl/cipher'
2
+ require 'base64'
3
+
4
+ module Lark
5
+ class Cipher
6
+ attr_reader :key
7
+
8
+ CIPHER = 'AES-256-CBC'.freeze
9
+
10
+ def initialize(key)
11
+ @key = Digest::SHA256.digest(key)
12
+ end
13
+
14
+ def encrypt(message)
15
+ cipher = OpenSSL::Cipher.new(CIPHER)
16
+ cipher.encrypt
17
+ cipher.key = key
18
+ iv = cipher.random_iv
19
+ Base64.urlsafe_encode64(iv + cipher.update(message) + cipher.final)
20
+ end
21
+
22
+ def decrypt(message)
23
+ cipher = OpenSSL::Cipher.new(CIPHER)
24
+ cipher.decrypt
25
+
26
+ decode64 = Base64.urlsafe_decode64(message)
27
+ cipher.key = key
28
+ cipher.iv = decode64[0..15]
29
+ ecrypted = decode64[16..-1]
30
+ cipher.update(ecrypted) + cipher.final
31
+ end
32
+
33
+ end
34
+ end
@@ -0,0 +1,33 @@
1
+ require 'logger'
2
+
3
+ module Lark
4
+ class << self
5
+ def configure
6
+ yield config
7
+ end
8
+
9
+ def config
10
+ @config ||= Config.new
11
+ end
12
+
13
+ def redis
14
+ config.redis
15
+ end
16
+
17
+ def logger
18
+ @logger ||= if config.logger.nil?
19
+ defined?(Rails) && Rails.logger ? Rails.logger : Logger.new(STDOUT)
20
+ else
21
+ config.logger
22
+ end
23
+ end
24
+
25
+ def http_timeout_options
26
+ config.http_timeout_options || {write: 2, connect: 5, read: 10}
27
+ end
28
+ end
29
+
30
+ class Config
31
+ attr_accessor :app_id, :app_secret, :redis, :http_timeout_options, :logger
32
+ end
33
+ end
@@ -0,0 +1,104 @@
1
+ require 'http'
2
+
3
+ module Lark
4
+ class Request
5
+ attr_reader :ssl_context, :http
6
+
7
+ def initialize(skip_verify_ssl=true)
8
+ @http = HTTP.timeout(**Lark.http_timeout_options)
9
+ @ssl_context = OpenSSL::SSL::SSLContext.new
10
+ @ssl_context.ssl_version = :TLSv1
11
+ @ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE if skip_verify_ssl
12
+ end
13
+
14
+ def get(path, get_header={})
15
+ request(path, get_header) do |url, header|
16
+ params = header.delete(:params)
17
+ http.headers(header).get(url, params: params, ssl_context: ssl_context)
18
+ end
19
+ end
20
+
21
+ def post(path, post_body, post_header={})
22
+ request(path, post_header) do |url, header|
23
+ Lark.logger.info "payload: #{post_body}"
24
+ params = header.delete(:params)
25
+ http.headers(header).post(url, params: params, json: post_body, ssl_context: ssl_context)
26
+ end
27
+ end
28
+
29
+ def post_file(path, file, post_header={})
30
+ request(path, post_header) do |url, header|
31
+ params = header.delete(:params)
32
+ http.headers(header).post(
33
+ url,
34
+ params: params,
35
+ form: {
36
+ media: HTTP::FormData::File.new(file),
37
+ hack: 'X'
38
+ }, # Existing here for http-form_data 1.0.1 handle single param improperly
39
+ ssl_context: ssl_context
40
+ )
41
+ end
42
+ end
43
+
44
+ private
45
+
46
+ def request(path, header={}, &_block)
47
+ url = URI::join(API_BASE_URL, path)
48
+ Lark.logger.info "request url(#{url}) with headers: #{header}"
49
+ as = header.delete(:as)
50
+ header['Accept'] = 'application/json'
51
+ response = yield(url, header)
52
+ raise ResponseError.new(response.status) unless response.status.success?
53
+ handle_response(response, as || :json)
54
+ end
55
+
56
+ def handle_response(response, as)
57
+ content_type = response.headers[:content_type]
58
+ parse_as = {
59
+ %r{^application\/json} => :json,
60
+ %r{^image\/.*} => :file
61
+ }.each_with_object([]) { |match, memo| memo << match[1] if content_type =~ match[0] }.first || as || :text
62
+
63
+ body = response.body
64
+ case parse_as
65
+ when :file
66
+ parse_as_file(body)
67
+ when :json
68
+ parse_as_json(body)
69
+ else
70
+ body
71
+ end
72
+ end
73
+
74
+ def parse_as_json(body)
75
+ Lark.logger.info "response body: #{body}"
76
+ data = JSON.parse body.to_s
77
+ result = Result.new(data)
78
+ raise ::Lark::AccessTokenExpiredError if [99991663, 99991664].include?(result.code)
79
+ result
80
+ end
81
+
82
+ def parse_as_file(body)
83
+ file = Tempfile.new('tmp')
84
+ file.binmode
85
+ file.write(body)
86
+ file.close
87
+
88
+ file
89
+ end
90
+ end
91
+
92
+ class Result
93
+ attr_reader :code, :data
94
+
95
+ def initialize(data)
96
+ @code = data['code'].to_i
97
+ @data = data
98
+ end
99
+
100
+ def success?
101
+ code == 0
102
+ end
103
+ end
104
+ end
data/lib/lark/route.rb ADDED
@@ -0,0 +1,17 @@
1
+ module Lark
2
+ module Route
3
+ extend ActiveSupport::Concern
4
+
5
+ module ClassMethods
6
+ def mount(name)
7
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
8
+ def #{name}
9
+ @#{name} ||= Class.new(SimpleDelegator) do
10
+ include Apis::#{name.to_s.classify}
11
+ end.new(self)
12
+ end
13
+ CODE
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,18 @@
1
+ require 'lark/token_store/base'
2
+
3
+ module Lark
4
+ module TokenStore
5
+ class AppToken < Base
6
+ def token_key
7
+ 'app_access_token'
8
+ end
9
+
10
+ def fetch_token
11
+ client.request.post 'auth/v3/app_access_token/internal/', {
12
+ app_id: client.app_id,
13
+ app_secret: client.app_secret
14
+ }
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,61 @@
1
+ module Lark
2
+ module TokenStore
3
+ class Base
4
+ attr_accessor :client
5
+
6
+ def initialize(client)
7
+ @client = client
8
+ raise RedisNotConfigException if redis.nil?
9
+ end
10
+
11
+ def token
12
+ update_token if expired?
13
+ redis.hget(redis_key, token_key)
14
+ end
15
+
16
+ def valid?
17
+ token.present?
18
+ end
19
+
20
+ def update_token
21
+ data = fetch_token.data
22
+ value = data[token_key]
23
+ if value.nil?
24
+ Lark.logger.error "#{self.class.name} fetch token error: #{data.inspect}"
25
+ else
26
+ expires_at = Time.now.to_i + data['expire'].to_i - 120
27
+ redis.hmset(
28
+ redis_key,
29
+ token_key, value,
30
+ 'expires_at', expires_at
31
+ )
32
+ redis.expireat(redis_key, expires_at)
33
+ end
34
+
35
+ value
36
+ end
37
+
38
+ private
39
+
40
+ def fetch_token
41
+ raise NotImplementedError
42
+ end
43
+
44
+ def token_key
45
+ raise NotImplementedError
46
+ end
47
+
48
+ def redis
49
+ Lark.redis
50
+ end
51
+
52
+ def redis_key
53
+ @redis_key ||= Digest::MD5.hexdigest "#{self.class.name}_#{client.app_id}_#{client.app_secret}"
54
+ end
55
+
56
+ def expired?
57
+ redis.hvals(redis_key).empty? || redis.hget(redis_key, 'expires_at').to_i <= Time.now.to_i
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,19 @@
1
+ require 'lark/token_store/base'
2
+
3
+ module Lark
4
+ module TokenStore
5
+ class IsvAppToken < Base
6
+ def token_key
7
+ 'app_access_token'
8
+ end
9
+
10
+ def fetch_token
11
+ client.request.post 'auth/v3/app_access_token/', {
12
+ app_id: client.app_id,
13
+ app_secret: client.app_secret,
14
+ app_ticket: client.app_ticket
15
+ }
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,22 @@
1
+ require 'lark/token_store/base'
2
+
3
+ module Lark
4
+ module TokenStore
5
+ class IsvTenantToken < Base
6
+ def token_key
7
+ 'tenant_access_token'
8
+ end
9
+
10
+ def fetch_token
11
+ client.request.post 'auth/v3/tenant_access_token/', {
12
+ app_access_token: client.app_access_token,
13
+ tenant_key: client.tenant_key
14
+ }
15
+ end
16
+
17
+ def redis_key
18
+ @redis_key ||= Digest::MD5.hexdigest "#{self.class.name}_#{client.app_id}_#{client.app_secret}_#{client.tenant_key}"
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,18 @@
1
+ require 'lark/token_store/base'
2
+
3
+ module Lark
4
+ module TokenStore
5
+ class TenantToken < Base
6
+ def token_key
7
+ 'tenant_access_token'
8
+ end
9
+
10
+ def fetch_token
11
+ client.request.post 'auth/v3/tenant_access_token/internal/', {
12
+ app_id: client.app_id,
13
+ app_secret: client.app_secret
14
+ }
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,3 @@
1
+ module Lark
2
+ VERSION = '0.1.0'.freeze
3
+ end
data/lib/lark.rb ADDED
@@ -0,0 +1,27 @@
1
+ require "lark/version"
2
+ require 'redis'
3
+ require 'active_support/all'
4
+ require 'lark/config'
5
+ require 'lark/cipher'
6
+ require 'lark/route'
7
+
8
+ LIB_PATH = "#{File.dirname(__FILE__)}/lark"
9
+ Dir["#{LIB_PATH}/apis/*.rb", "#{LIB_PATH}/token_store/*.rb"].each { |path| require path }
10
+
11
+ require 'lark/api'
12
+
13
+ module Lark
14
+ API_BASE_URL = 'https://open.feishu.cn/open-apis/'.freeze
15
+
16
+ # Exceptions
17
+ class RedisNotConfigException < RuntimeError; end
18
+ class AccessTokenExpiredError < RuntimeError; end
19
+ class ResultErrorException < RuntimeError; end
20
+ class ResponseError < StandardError
21
+ attr_reader :error_code
22
+ def initialize(errcode, errmsg='')
23
+ @error_code = errcode
24
+ super "(#{error_code}) #{errmsg}"
25
+ end
26
+ end
27
+ end
metadata ADDED
@@ -0,0 +1,158 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: lark-sdk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sean Dong
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-02-17 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: http
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2.2'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2.2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '5.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '5.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: redis
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '1.13'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '1.13'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '10.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '10.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: minitest
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '5.10'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '5.10'
97
+ description: Unoffical Lark(飞书) SDKs for ruby https://open.feishu.cn
98
+ email:
99
+ - sindon@gmail.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".travis.yml"
106
+ - CODE_OF_CONDUCT.md
107
+ - Gemfile
108
+ - LICENSE.txt
109
+ - README.md
110
+ - Rakefile
111
+ - bin/console
112
+ - bin/setup
113
+ - lark.gemspec
114
+ - lib/lark.rb
115
+ - lib/lark/api.rb
116
+ - lib/lark/apis/auth.rb
117
+ - lib/lark/apis/authen.rb
118
+ - lib/lark/apis/chat.rb
119
+ - lib/lark/apis/contact.rb
120
+ - lib/lark/apis/message.rb
121
+ - lib/lark/cipher.rb
122
+ - lib/lark/config.rb
123
+ - lib/lark/request.rb
124
+ - lib/lark/route.rb
125
+ - lib/lark/token_store/app_token.rb
126
+ - lib/lark/token_store/base.rb
127
+ - lib/lark/token_store/isv_app_token.rb
128
+ - lib/lark/token_store/isv_tenant_token.rb
129
+ - lib/lark/token_store/tenant_token.rb
130
+ - lib/lark/version.rb
131
+ homepage: https://github.com/mycolorway/lark-ruby-sdk
132
+ licenses:
133
+ - MIT
134
+ metadata:
135
+ allowed_push_host: https://rubygems.org/
136
+ homepage_uri: https://github.com/mycolorway/lark-ruby-sdk
137
+ source_code_uri: https://github.com/mycolorway/lark-ruby-sdk
138
+ changelog_uri: https://github.com/mycolorway/lark-ruby-sdk
139
+ post_install_message:
140
+ rdoc_options: []
141
+ require_paths:
142
+ - lib
143
+ required_ruby_version: !ruby/object:Gem::Requirement
144
+ requirements:
145
+ - - ">="
146
+ - !ruby/object:Gem::Version
147
+ version: 2.3.0
148
+ required_rubygems_version: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ">="
151
+ - !ruby/object:Gem::Version
152
+ version: '0'
153
+ requirements: []
154
+ rubygems_version: 3.1.2
155
+ signing_key:
156
+ specification_version: 4
157
+ summary: Lark SDKs for ruby
158
+ test_files: []