adash 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 61f2c1aaecd17188279e2bdbdcbc27bd9dbcdca5
4
+ data.tar.gz: 36f79b3aaee75b3a51fb5040e4209863b9c039e2
5
+ SHA512:
6
+ metadata.gz: '099bfecea21fc84cba496e203c126c8d1873a811ba9f1bd95c4e33ea9f94bd6fdb4294e10911144fbcfc8418bb8717f904da09cd3a812ba15eb7ee9a8c35e628'
7
+ data.tar.gz: '016778d780cd3f95ede569ede0b0026aa8d19dd6d7eb7e40d4ba3797877f3c72f09419be56f3ed66d47b04ed7caba7afb9d6a2309b7b89cd85d4b0b5dd901ffe'
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.swp
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.3
5
+ before_install: gem install bundler -v 1.13.6
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in adash.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Code Ass
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.
@@ -0,0 +1,41 @@
1
+ # Adash
2
+
3
+ It's a CLI for Amazon Dash Replenishment Service.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'adash'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install adash
20
+
21
+ ## Usage
22
+
23
+ ```bash
24
+ $ adash init [device_model]
25
+ ```
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ 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).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/adash.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,26 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'adash/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "adash"
8
+ spec.version = Adash::VERSION
9
+ spec.authors = ["Code Ass"]
10
+ spec.email = ["aycabta@gmail.com"]
11
+
12
+ spec.summary = %q{Adash}
13
+ spec.description = %q{Adash}
14
+ spec.homepage = "https://github.com/aycabta/adash"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_development_dependency "bundler", "~> 1.13"
23
+ spec.add_development_dependency "rake", "~> 10.0"
24
+ spec.add_development_dependency "rspec", "~> 3.0"
25
+ spec.add_development_dependency "launchy", "~> 2.5"
26
+ end
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "adash"
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
@@ -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
@@ -0,0 +1,3 @@
1
+ amzn1.application-oa2-client.b5c87429af104636bd7ae83df68383e1
2
+ b32bf97316788bb5faf89e1ae798d2744e6933dbe237c7255f48b9a09c653aec
3
+ 55582
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env ruby
2
+ # vim: set filetype=ruby:
3
+ $: << File.expand_path("../../lib/", __FILE__)
4
+
5
+ require 'adash'
6
+ require 'adash/config'
7
+ require 'adash/wait_indefinitely'
8
+ require 'optparse'
9
+ require 'readline'
10
+ require 'fileutils'
11
+ require 'yaml'
12
+
13
+ opt = OptionParser.new
14
+
15
+ opt.on('-h', '--help') { puts 'help' }
16
+
17
+ def generate_serial(device_model)
18
+ orig = [('a'..'z'), ('A'..'Z'), ('0'..'9')].map { |i| i.to_a }.flatten
19
+ random_suffix = (0...16).map { orig[rand(orig.size)] }.join
20
+ "#{device_model}_#{Time.now.to_i}_#{random_suffix}"
21
+ end
22
+
23
+ def get_credentials
24
+ if File.exist?(Adash::Config.credentials_path)
25
+ credentials = YAML.load_file(Adash::Config.credentials_path)
26
+ else
27
+ { 'authorized_devices' => [] }
28
+ end
29
+ end
30
+
31
+ def save_credentials(credentials)
32
+ open(Adash::Config.credentials_path, 'w') do |f|
33
+ f.write(credentials.to_yaml)
34
+ end
35
+ end
36
+
37
+ def get_device_from_credentials(credentials, device_model)
38
+ i = credentials['authorized_devices'].find_index { |d| d['device_model'] == device_model }
39
+ if i
40
+ credentials['authorized_devices'][i]
41
+ else
42
+ nil
43
+ end
44
+ end
45
+
46
+ def save_credentials_with_device(credentials, device)
47
+ i = credentials['authorized_devices'].find_index { |d| d['device_model'] == device['device_model'] }
48
+ if i
49
+ credentials['authorized_devices'][i] = device
50
+ else
51
+ credentials['authorized_devices'] << device
52
+ end
53
+ save_credentials(credentials)
54
+ end
55
+
56
+ def save_credentials_without_device_model(device_model)
57
+ credentials = get_credentials
58
+ credentials['authorized_devices'] = credentials['authorized_devices'].delete_if { |d| d['device_model'] == device_model }
59
+ save_credentials(credentials)
60
+ end
61
+
62
+ def create_client_from_device(device)
63
+ Adash::Client.new(device['device_model']) do |c|
64
+ c.authorization_code = device['authorization_code']
65
+ c.serial = device['serial']
66
+ c.redirect_uri = device['redirect_uri']
67
+ c.access_token = device['access_token']
68
+ c.refresh_token = device['refresh_token']
69
+ c.on_new_token = proc { |access_token, refresh_token|
70
+ credentials = get_credentials
71
+ updated_device = get_device_from_credentials(credentials, device['device_model'])
72
+ updated_device['access_token'] = access_token
73
+ updated_device['refresh_token'] = refresh_token
74
+ save_credentials_with_device(credentials, updated_device)
75
+ device['device_model']
76
+ }
77
+ end
78
+ end
79
+
80
+ def get_device_by_name(name)
81
+ credentials = get_credentials
82
+ hit = credentials['authorized_devices'].find_index { |d| d['name'] == name }
83
+ if hit
84
+ device = credentials['authorized_devices'][hit]
85
+ else
86
+ nil
87
+ end
88
+ end
89
+
90
+ def show_slots(slots)
91
+ index = 0
92
+ slots.each do |slot_id, available|
93
+ puts
94
+ puts "---- number: #{index}"
95
+ puts "* slot_id: #{slot_id}"
96
+ puts " available: #{available}"
97
+ puts
98
+ index =+ 1
99
+ end
100
+ end
101
+
102
+ def select_slot_prompt(client)
103
+ resp = client.subscription_info
104
+ slots = resp.json['slotsSubscriptionStatus']
105
+ loop do
106
+ show_slots(slots)
107
+ slot_num = Readline.readline('Select slot number> ')
108
+ if (0..(slots.size - 1)).member?(slot_num.to_i)
109
+ break slots.keys[slot_num.to_i]
110
+ else
111
+ puts "ERROR: #{slot_num} is out of Range"
112
+ end
113
+ end
114
+ end
115
+
116
+ argv = opt.order(ARGV)
117
+ unless argv.empty?
118
+ subcmd = argv.shift
119
+ case subcmd
120
+ when 'init'
121
+ init_opt = OptionParser.new
122
+ init_opt.on('-h', '--help') { puts 'init help' }
123
+ is_test = false
124
+ init_opt.on('-t', '--test') {
125
+ is_test = true
126
+ puts 'TEST MODE'
127
+ }
128
+ argv = init_opt.parse(argv)
129
+ if argv.size < 2
130
+ puts 'Usage: adash init name device_model'
131
+ exit 2
132
+ end
133
+ name = argv.shift
134
+ device_model = argv.shift
135
+ serial = generate_serial(device_model)
136
+ credentials = get_credentials
137
+ authorized_devices = credentials['authorized_devices']
138
+ hit = authorized_devices.find_index { |d| d['device_model'] == device_model }
139
+ if hit
140
+ puts "Adash knows device what is #{device_model}."
141
+ exit 3
142
+ end
143
+ hit = authorized_devices.find_index { |d| d['name'] == name }
144
+ if hit
145
+ puts "Adash knows device what is named #{name}."
146
+ exit 3
147
+ end
148
+ wi = Adash::WaitIndefinitely.new(device_model, serial)
149
+ Signal.trap(:INT){ wi.shutdown }
150
+ code = wi.get_code
151
+ FileUtils.mkdir_p(File.expand_path('..', Adash::Config.credentials_path))
152
+ new_device = {
153
+ 'name' => name,
154
+ 'device_model' => device_model,
155
+ 'serial' => serial,
156
+ 'authorization_code' => code,
157
+ 'redirect_uri' => wi.redirect_uri
158
+ }
159
+ new_device['is_test'] = true if is_test
160
+ credentials['authorized_devices'] << new_device
161
+ save_credentials(credentials)
162
+ client = create_client_from_device(new_device)
163
+ client.get_token
164
+ when 'list'
165
+ credentials = get_credentials
166
+ credentials['authorized_devices'].each do |device|
167
+ puts "---- name: #{device['name']}"
168
+ puts "* device_model: #{device['device_model']}"
169
+ puts " serial: #{device['serial']}"
170
+ puts ' THIS DEVICE IS TEST PURCHASE MODE' if device['is_test']
171
+ end
172
+ when 'deregistrate'
173
+ if argv.size < 1
174
+ puts 'Usage: adash deregistrate name'
175
+ exit 4
176
+ end
177
+ name = argv.shift
178
+ device = get_device_by_name(name)
179
+ unless device
180
+ puts "Device #{name} not found"
181
+ exit 5
182
+ end
183
+ client = create_client_from_device(device)
184
+ resp = client.deregistrate_device
185
+ save_credentials_without_device_model(device['device_model'])
186
+ when 'list-slot'
187
+ if argv.size < 1
188
+ puts 'Usage: adash list-slot name'
189
+ exit 5
190
+ end
191
+ name = argv.shift
192
+ device = get_device_by_name(name)
193
+ unless device
194
+ puts "Device #{name} not found"
195
+ exit 5
196
+ end
197
+ client = create_client_from_device(device)
198
+ resp = client.subscription_info
199
+ index = 0
200
+ resp.json['slotsSubscriptionStatus'].each do |slot_id, available|
201
+ puts "---- #{index}"
202
+ puts "* slot_id: #{slot_id}"
203
+ puts " available: #{available}"
204
+ index =+ 1
205
+ end
206
+ when 'replenish'
207
+ if argv.size < 1
208
+ puts 'Usage: adash replenish name [slot_id]'
209
+ exit 6
210
+ end
211
+ name = argv.shift
212
+ slot_id = argv.first&.start_with?('-') ? nil : argv.shift
213
+ device = get_device_by_name(name)
214
+ unless device
215
+ puts "Device #{name} not found"
216
+ exit 5
217
+ end
218
+ client = create_client_from_device(device)
219
+ slot_id = select_slot_prompt(client) unless slot_id
220
+ resp = client.replenish(slot_id)
221
+ if resp.json['message']
222
+ puts "ERROR: #{resp.json['message']}"
223
+ else
224
+ case resp.json['detailCode']
225
+ when 'STANDARD_ORDER_PLACED'
226
+ puts 'Succeeded to order.'
227
+ when 'ORDER_INPROGRESS'
228
+ puts 'The order is in progress.'
229
+ end
230
+ end
231
+ else
232
+ $stderr.puts "no such subcommand: #{k}"
233
+ exit 1
234
+ end
235
+ end
@@ -0,0 +1,5 @@
1
+ require 'adash/version'
2
+
3
+ module Adash
4
+ # Your code goes here...
5
+ end
@@ -0,0 +1,213 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require 'json'
4
+ require 'yaml'
5
+ require 'time'
6
+ require 'date'
7
+ require 'adash/config'
8
+
9
+ class Net::HTTPResponse
10
+ attr_accessor :json
11
+ end
12
+
13
+ module Adash
14
+ class Client
15
+ attr_accessor :device_model, :serial, :authorization_code, :redirect_uri, :access_token, :refresh_token
16
+ attr_accessor :on_new_token
17
+ attr_writer :user_agent
18
+
19
+ def initialize(device_model)
20
+ @drs_host = 'dash-replenishment-service-na.amazon.com'
21
+ @amazon_host = 'api.amazon.com'
22
+ @device_model = device_model
23
+ @serial = nil
24
+ @authorization_code = nil
25
+ @redirect_uri = nil
26
+ @access_token = nil
27
+ @refresh_token = nil
28
+ @on_new_token = nil
29
+ yield(self) if block_given?
30
+ end
31
+
32
+ def user_agent
33
+ @user_agent ||= "AdashRubyGem/#{Adash::VERSION}/#{RUBY_DESCRIPTION}"
34
+ end
35
+
36
+ def deregistrate_device
37
+ headers = {
38
+ 'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsDeregisterResult@1.0',
39
+ 'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsDeregisterInput@1.0'
40
+ }
41
+ path = "/deviceModels/#{@device_model}/devices/#{@serial}/registration"
42
+ request_drs(:delete, path, headers: headers)
43
+ end
44
+
45
+ def device_status(most_recently_active_date)
46
+ headers = {
47
+ 'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsDeviceStatusResult@1.0',
48
+ 'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsDeviceStatusInput@1.0'
49
+ }
50
+ path = '/deviceStatus'
51
+ request_drs(:post, path, headers: headers, params: { 'mostRecentlyActiveDate' => convert_to_iso8601(most_recently_active_date) })
52
+ end
53
+
54
+ def subscription_info
55
+ headers = {
56
+ 'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsSubscriptionInfoResult@1.0',
57
+ 'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsSubscriptionInfoInput@1.0'
58
+ }
59
+ path = '/subscriptionInfo'
60
+ request_drs(:get, path, headers: headers)
61
+ end
62
+
63
+ def slot_status(slot_id, expected_replenishment_date, remaining_quantity_in_unit, original_quantity_in_unit, total_quantity_on_hand, last_use_date)
64
+ headers = {
65
+ 'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsSlotStatusResult@1.0',
66
+ 'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsSlotStatusInput@1.0'
67
+ }
68
+ path = "/slotStatus/#{slot_id}"
69
+ params = {
70
+ 'expectedReplenishmentDate' => convert_to_iso8601(expected_replenishment_date),
71
+ 'remainingQuantityInUnit' => remaining_quantity_in_unit,
72
+ 'originalQuantityInUnit' => original_quantity_in_unit,
73
+ 'totalQuantityOnHand' => total_quantity_on_hand,
74
+ 'lastUseDate' => convert_to_iso8601(last_use_date)
75
+ }
76
+ request_drs(:post, path, headers: headers, params: params)
77
+ end
78
+
79
+ def replenish(slot_id)
80
+ headers = {
81
+ 'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsReplenishResult@1.0',
82
+ 'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsReplenishInput@1.0'
83
+ }
84
+ path = "/replenish/#{slot_id}"
85
+ response = request_drs(:post, path, headers: headers)
86
+ # TODO: imprement response processing
87
+ # https://developer.amazon.com/public/solutions/devices/dash-replenishment-service/docs/dash-replenish-endpoint
88
+ # response examples:
89
+ # {"message":"Unable to place order - slot : <01234567-89ab-cdef-0123-456789abcdef> is unsubscribed."}
90
+ # {"detailCode":"STANDARD_ORDER_PLACED","eventInstanceId":"amzn1.dash.v2.o.xxxxxx......"}
91
+ # {"detailCode":"ORDER_INPROGRESS","eventInstanceId":"amzn1.dash.v2.o.xxxxxx......"}
92
+ end
93
+
94
+ def get_token
95
+ if @access_token
96
+ @access_token
97
+ else
98
+ resp = request_token
99
+ process_token_response(resp)
100
+ end
101
+ end
102
+
103
+ private
104
+
105
+ def convert_to_iso8601(input)
106
+ case input
107
+ when Date, Time
108
+ input.iso8601
109
+ when String
110
+ input
111
+ else
112
+ input.to_s
113
+ end
114
+ end
115
+
116
+ def process_token_response(resp)
117
+ if resp.json['error']
118
+ puts resp.json['error']
119
+ puts resp.json['error_description']
120
+ nil
121
+ else
122
+ @access_token = resp.json['access_token']
123
+ @refresh_token = resp.json['refresh_token']
124
+ @on_new_token.call(@access_token, @refresh_token) if @on_new_token
125
+ @access_token
126
+ end
127
+ end
128
+
129
+ def request_drs(method, path, headers: {}, params: {})
130
+ url = "https://#{@drs_host}#{path}"
131
+ if @authorization_code.nil?
132
+ raise 'Authorization Code is not set'
133
+ end
134
+ if @access_token.nil?
135
+ token = get_token
136
+ if token.nil?
137
+ raise 'Failed to get token'
138
+ end
139
+ end
140
+ resp = request(method, url, headers: headers, params: params)
141
+ if resp.code == '400' && resp.json['message'] == 'Invalid token' && @refresh_token
142
+ resp = refresh_access_token
143
+ process_token_response(resp)
144
+ request(method, url, headers: headers, params: params)
145
+ else
146
+ resp
147
+ end
148
+ end
149
+
150
+ def refresh_access_token
151
+ params = {
152
+ grant_type: 'refresh_token',
153
+ refresh_token: @refresh_token,
154
+ client_id: Adash::Config.client_id,
155
+ client_secret: Adash::Config.client_secret
156
+ }
157
+ @access_token = nil
158
+ request(:post, "https://#{@amazon_host}/auth/o2/token", params: params)
159
+ end
160
+
161
+ def request_token
162
+ params = {
163
+ grant_type: 'authorization_code',
164
+ code: @authorization_code,
165
+ client_id: Adash::Config.client_id,
166
+ client_secret: Adash::Config.client_secret,
167
+ redirect_uri: "http://localhost:#{Adash::Config.redirect_port}/"
168
+ }
169
+ request(:post, "https://#{@amazon_host}/auth/o2/token", params: params)
170
+ end
171
+
172
+ def request(method, url, headers: {}, params: {})
173
+ uri = URI.parse(url)
174
+ if params.any?{ |key, value| value.is_a?(Enumerable) }
175
+ converted_params = []
176
+ params.each do |key, value|
177
+ if value.is_a?(Enumerable)
178
+ value.each_index do |i|
179
+ converted_params << ["#{key}[#{i}]", value[i]]
180
+ end
181
+ else
182
+ converted_params << [key, value]
183
+ end
184
+ end
185
+ params = converted_params
186
+ end
187
+ case method
188
+ when :delete
189
+ uri.query = URI.encode_www_form(params)
190
+ request = Net::HTTP::Delete.new(uri)
191
+ when :get
192
+ uri.query = URI.encode_www_form(params)
193
+ request = Net::HTTP::Get.new(uri)
194
+ when :post
195
+ request = Net::HTTP::Post.new(uri.path)
196
+ request.body = URI.encode_www_form(params)
197
+ end
198
+ request['Content-Type'] = 'application/x-www-form-urlencoded'
199
+ request['User-Agent'] = @user_agent
200
+ headers.each do |key, value|
201
+ request[key] = value
202
+ end
203
+ if not @access_token.nil?
204
+ request["Authorization"] = "Bearer #{@access_token}"
205
+ end
206
+ http = Net::HTTP.new(uri.host, uri.port)
207
+ http.use_ssl = true
208
+ response = http.request(request)
209
+ response.json = JSON.parse(response.body)
210
+ response
211
+ end
212
+ end
213
+ end
@@ -0,0 +1,27 @@
1
+ module Adash
2
+ class Config
3
+
4
+ open("#{File.expand_path('../../../data', __FILE__)}/client", 'r') do |f|
5
+ @@client_id = f.readline.chomp
6
+ @@client_secret = f.readline.chomp
7
+ @@redirect_port = f.readline.chomp.to_i
8
+ @@credentials_path = "#{Dir.home}/.config/adash/credentials"
9
+ end
10
+
11
+ def self.client_id
12
+ @@client_id
13
+ end
14
+
15
+ def self.client_secret
16
+ @@client_secret
17
+ end
18
+
19
+ def self.redirect_port
20
+ @@redirect_port
21
+ end
22
+
23
+ def self.credentials_path
24
+ @@credentials_path
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,3 @@
1
+ module Adash
2
+ VERSION = '0.0.1'
3
+ end
@@ -0,0 +1,87 @@
1
+ require 'uri'
2
+ require 'erb'
3
+ require 'launchy'
4
+ require 'adash/client'
5
+ require 'adash/config'
6
+
7
+ module Adash
8
+ class WaitIndefinitely
9
+ attr_reader :redirect_uri
10
+
11
+ def initialize(device_model, serial, is_test: false)
12
+ require 'webrick'
13
+ @device_model = device_model
14
+ @serial = serial
15
+ @is_test = is_test
16
+ @redirect_uri = "http://localhost:#{Adash::Config.redirect_port}/"
17
+ @code_box = Queue.new
18
+ @code_cv = ConditionVariable.new
19
+ @code_mutex = Mutex.new
20
+ @server = WEBrick::HTTPServer.new({ :BindAddress => '127.0.0.1', :Port => Adash::Config.redirect_port })
21
+ @server.mount_proc('/getting_started', proc { |req, res|
22
+ res.content_type = 'text/html'
23
+ content = %Q`<p>Please go to <a href="#{ERB::Util.html_escape(amazon_authorization_url(@device_model, @serial))}">initial tour</a>.</p>`
24
+ res.body = render(content)
25
+ })
26
+ @server.mount_proc('/', proc { |req, res|
27
+ res.content_type = 'text/html'
28
+ if req.query.include?('code')
29
+ content = '<p>Done. Please close this tab.</p>'
30
+ @code_mutex.synchronize {
31
+ @code_box.push(req.query['code'].to_s)
32
+ @code_cv.signal
33
+ }
34
+ else
35
+ content = "<dl>\n" + req.query.map { |k, v| "<dt>#{k}</dt><dd>#{v}</dd>" }.join("\n") + "\n</dl>"
36
+ end
37
+ res.body = render(content)
38
+ })
39
+ end
40
+
41
+ def render(content)
42
+ <<~EOH
43
+ <html>
44
+ <head>
45
+ <meta name="referrer" content="no-referrer" />
46
+ </head>
47
+ <body>
48
+ #{content}
49
+ </body>
50
+ </html>
51
+ EOH
52
+ end
53
+
54
+ def amazon_authorization_url(device_model, serial)
55
+ base = 'https://www.amazon.com/ap/oa?'
56
+ params = {
57
+ client_id: Adash::Config.client_id,
58
+ scope: 'dash:replenish',
59
+ response_type: 'code',
60
+ # redirect_uri must exact-match with escaped it when access_token is requested
61
+ redirect_uri: URI.encode_www_form_component(@redirect_uri),
62
+ scope_data: %Q`{"dash:replenish":{"device_model":"#{device_model}","serial":"#{serial}"#{ ',"is_test_device":true' if @is_test }}}`
63
+ }
64
+ "#{base}#{params.map{ |k, v| "#{k}=#{v}" }.join(?&)}"
65
+ end
66
+
67
+ def get_code
68
+ t = Thread.new do
69
+ @code_mutex.synchronize {
70
+ # TODO: wait for WEBrick launch
71
+ Launchy.open("http://localhost:#{Adash::Config.redirect_port}/getting_started")
72
+ while @code_box.size == 0
73
+ @code_cv.wait(@code_mutex)
74
+ sleep 1
75
+ @server.shutdown
76
+ end
77
+ }
78
+ end
79
+ @server.start
80
+ @code_box.pop
81
+ end
82
+
83
+ def shutdown
84
+ @server.shutdown
85
+ end
86
+ end
87
+ end
metadata ADDED
@@ -0,0 +1,118 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: adash
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Code Ass
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-12-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.13'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.13'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: launchy
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.5'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.5'
69
+ description: Adash
70
+ email:
71
+ - aycabta@gmail.com
72
+ executables:
73
+ - adash
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".gitignore"
78
+ - ".rspec"
79
+ - ".travis.yml"
80
+ - Gemfile
81
+ - LICENSE.txt
82
+ - README.md
83
+ - Rakefile
84
+ - adash.gemspec
85
+ - bin/console
86
+ - bin/setup
87
+ - data/client
88
+ - exe/adash
89
+ - lib/adash.rb
90
+ - lib/adash/client.rb
91
+ - lib/adash/config.rb
92
+ - lib/adash/version.rb
93
+ - lib/adash/wait_indefinitely.rb
94
+ homepage: https://github.com/aycabta/adash
95
+ licenses:
96
+ - MIT
97
+ metadata: {}
98
+ post_install_message:
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ required_rubygems_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ requirements: []
113
+ rubyforge_project:
114
+ rubygems_version: 2.5.2
115
+ signing_key:
116
+ specification_version: 4
117
+ summary: Adash
118
+ test_files: []