mi-service 1.0.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: 11d84e6442b2d12195f5c62fbbb8e9af3d9f54b18403a943960e14850c62ad82
4
+ data.tar.gz: a4db0fe51fd99a345f5ca4d26a098251cb4b5745d0393ccde929626c7dc47a2f
5
+ SHA512:
6
+ metadata.gz: a554690998689a3d94fb32d7f4cd0d790bfb9bcf22f3b213a3ee19fed444b6ca22dd10666835c96c71e7aba35769c40906d2e0a17a402e1cb76b3d314d8300dc
7
+ data.tar.gz: 1928ef32b128ec8347e75f23f7bf5f10bbe90fb84d41525bf79e35a57fe2f27d09a9cbfc93945b8cd47e9fb01a5dfcf808a621fd09281092b83b3aac59e8eb5f
data/.rubocop.yml ADDED
@@ -0,0 +1,25 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Style/StringLiterals:
7
+ Enabled: true
8
+ EnforcedStyle: double_quotes
9
+
10
+ Style/Documentation:
11
+ Enabled: false
12
+
13
+ Style/StringLiteralsInInterpolation:
14
+ Enabled: true
15
+ EnforcedStyle: double_quotes
16
+
17
+ Metrics/MethodLength:
18
+ Enabled: false
19
+ Metrics/ClassLength:
20
+ Enabled: false
21
+ Metrics/AbcSize:
22
+ Enabled: false
23
+
24
+ Layout/LineLength:
25
+ Max: 180
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-06-08
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at hoooopo@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Hooopo
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,39 @@
1
+ # Mi::Service
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/mi/service`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ 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.
26
+
27
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/mi-service. 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]/mi-service/blob/main/CODE_OF_CONDUCT.md).
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
36
+
37
+ ## Code of Conduct
38
+
39
+ Everyone interacting in the Mi::Service project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/mi-service/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
data/lib/mi/logger.rb ADDED
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+
5
+ class RequestLogger < Faraday::Middleware
6
+ def initialize(app, logger = nil)
7
+ super(app)
8
+ @logger = logger || Logger.new($stdout)
9
+ end
10
+
11
+ def call(env)
12
+ @logger.info "Request Method: #{env.method.upcase}"
13
+ @logger.info "Request URL: #{env.url}"
14
+ @logger.info "Request Headers: #{env.request_headers}"
15
+ @logger.info "Request Body: #{env.body}"
16
+ @logger.info "Request Params: #{env.params}"
17
+
18
+ @app.call(env).on_complete do |response_env|
19
+ @logger.info "Response Status: #{response_env.status}"
20
+ @logger.info "Response Headers: #{response_env.response_headers}"
21
+ @logger.info "Response Body: #{response_env.body}"
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "digest"
5
+ require "faraday"
6
+ require "json"
7
+ require "base64"
8
+ require "forwardable"
9
+
10
+ require_relative "../logger"
11
+ require_relative "../utils"
12
+ require_relative "miio"
13
+ require_relative "mina"
14
+
15
+ module Mi
16
+ module Service
17
+ class Account
18
+ extend Forwardable
19
+ attr_reader :userid, :password, :info, :debug, :notification_url
20
+
21
+ DEFAULT_COOKIES = {
22
+ "sdkVersion" => "3.9",
23
+ "uLocale" => "zh_CN"
24
+ }.freeze
25
+
26
+ DEFAULT_HEADERS = {
27
+ "User-Agent" => "APP/com.xiaomi.mihome APPV/6.0.103 iosPassportSDK/3.9.0 iOS/14.4 miHSTS"
28
+ }.freeze
29
+
30
+ def initialize(userid, password, debug: false, info: {})
31
+ @userid = userid
32
+ @password = password
33
+ @debug = debug
34
+ @success = false
35
+ @info = info
36
+ @miio = MiIO.new(self, debug: debug)
37
+ @mina = Mina.new(self, debug: debug)
38
+ end
39
+
40
+ def_delegators :@miio, :miot_action
41
+ def_delegators :@mina, :device_list, :text_to_speech, :player_pause, :player_stop, :player_get_status, :message_list
42
+
43
+ def login_all
44
+ login("xiaomiio")
45
+ login("micoapi")
46
+ end
47
+
48
+ def login_from_data(data)
49
+ @info = data
50
+ @success = true
51
+ end
52
+
53
+ def login(sid)
54
+ device_id = @info["deviceId"] || Mi::Utils.get_random(16).upcase
55
+ login_response = service_login(sid)
56
+
57
+ unless (login_response["code"]).zero?
58
+ data = {
59
+ _json: "true",
60
+ qs: login_response["qs"],
61
+ sid: login_response["sid"],
62
+ _sign: login_response["_sign"],
63
+ callback: login_response["callback"],
64
+ user: userid,
65
+ hash: md5_hash(password)
66
+ }
67
+ login_response = service_login_auth2(data)
68
+ if login_response["notificationUrl"]
69
+ @notification_url = "https://account.xiaomi.com#{login_response["notificationUrl"]}"
70
+ raise "Please verify your account by visiting #{@notification_url}"
71
+ end
72
+ end
73
+
74
+ if (login_response["code"]).zero?
75
+ @info = @info.merge login_response.slice("userId", "passToken")
76
+ @info["deviceId"] = device_id
77
+
78
+ security_token_service(
79
+ sid,
80
+ login_response["location"],
81
+ login_response["nonce"],
82
+ login_response["ssecurity"]
83
+ )
84
+ else
85
+ @success = false
86
+ end
87
+ end
88
+
89
+ def service_login(sid)
90
+ cookies = DEFAULT_COOKIES
91
+ if @info["passToken"]
92
+ cookies = cookies.merge({ "userId" => @info["userId"],
93
+ "passToken" => @info["passToken"] })
94
+ end
95
+
96
+ headers = DEFAULT_HEADERS.merge({
97
+ "Cookie" => Mi::Utils.cookie2str(cookies)
98
+ })
99
+ client = Faraday.new do |faraday|
100
+ faraday.headers = headers
101
+ faraday.use RequestLogger if debug
102
+ end
103
+ response = client.get(
104
+ "https://account.xiaomi.com/pass/serviceLogin?sid=#{sid}&_json=true"
105
+ )
106
+ JSON.parse(response.body.sub("&&&START&&&", ""))
107
+ end
108
+
109
+ def service_login_auth2(data)
110
+ cookies = DEFAULT_COOKIES
111
+ if @info["passToken"]
112
+ cookies = cookies.merge({ "userId" => @info["userId"],
113
+ "passToken" => @info["passToken"] })
114
+ end
115
+
116
+ headers = DEFAULT_HEADERS.merge({
117
+ "Cookie" => Mi::Utils.cookie2str(cookies),
118
+ "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"
119
+ })
120
+ client = Faraday.new do |faraday|
121
+ faraday.request :url_encoded
122
+ faraday.headers = headers
123
+ faraday.use RequestLogger if debug
124
+ end
125
+ response = client.post(
126
+ "https://account.xiaomi.com/pass/serviceLoginAuth2",
127
+ data
128
+ )
129
+ JSON.parse(response.body.sub("&&&START&&&", ""))
130
+ end
131
+
132
+ def security_token_service(sid, location, nonce, ssecurity)
133
+ cookies = DEFAULT_COOKIES
134
+ headers = DEFAULT_HEADERS.merge({
135
+ "Cookie" => Mi::Utils.cookie2str(cookies)
136
+ })
137
+ nsec = "nonce=#{nonce}&#{ssecurity}"
138
+ client_sign = Base64.encode64(Digest::SHA1.digest(nsec)).chomp
139
+
140
+ new_url = "#{location}&clientSign=#{URI.encode_uri_component(client_sign)}"
141
+ client = Faraday.new do |faraday|
142
+ faraday.headers = headers
143
+ faraday.response :logger if debug
144
+ end
145
+ response = client.get(new_url)
146
+ service_token = response.headers["set-cookie"][/serviceToken=([^;]+)/, 1]
147
+ if service_token
148
+ @info[sid] = [ssecurity, service_token]
149
+ @success = true
150
+ end
151
+ response
152
+ end
153
+
154
+ def auth_cookies(sid)
155
+ return {} if @info[sid].nil?
156
+
157
+ {
158
+ "userId" => @info["userId"],
159
+ "serviceToken" => @info[sid][1]
160
+ }
161
+ end
162
+
163
+ def success?
164
+ @success
165
+ end
166
+
167
+ def authed_by_sid?(sid)
168
+ !@info[sid].nil?
169
+ end
170
+
171
+ private
172
+
173
+ def md5_hash(string)
174
+ Digest::MD5.hexdigest(string).upcase
175
+ end
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "openssl"
5
+ require "json"
6
+ require "zlib"
7
+ require "stringio"
8
+ require "securerandom"
9
+ require "digest"
10
+ require "faraday"
11
+
12
+ require_relative "../logger"
13
+ require_relative "../utils"
14
+
15
+ module Mi
16
+ module Service
17
+ class MiIO
18
+ attr_reader :account, :debug
19
+
20
+ DEFAULT_HEADERS = {
21
+ "User-Agent": "iOS-14.4-6.0.103-iPhone12,3--D7744744F7AF32F0544445285880DD63E47D9BE9-8816080-84A3F44E137B71AE-iPhone",
22
+ "x-xiaomi-protocal-flag-cli": "PROTOCAL-HTTP2"
23
+ }.freeze
24
+
25
+ def initialize(account, debug: false)
26
+ @debug = debug
27
+ @account = account
28
+ end
29
+
30
+ def miot_action(did, iid, args)
31
+ sid = "xiaomiio"
32
+ ssecurity = account.info[sid][0]
33
+ device_id = account.info["deviceId"]
34
+
35
+ url = "https://api.io.mi.com/app/miotspec/action"
36
+
37
+ data = { "params" => { did: String(did), siid: Integer(iid[0]), aiid: Integer(iid[1]), in: Array(args) } }
38
+
39
+ signed_data = self.class.sign_data("/miotspec/action", data, ssecurity)
40
+
41
+ client = Faraday.new(url) do |f|
42
+ f.response :logger if debug
43
+ f.request :url_encoded
44
+ f.headers = DEFAULT_HEADERS.merge(
45
+ "Cookie" => Mi::Utils.cookie2str(
46
+ account.auth_cookies(sid).merge("PassportDeviceId" => device_id)
47
+ )
48
+ )
49
+ end
50
+ response = client.post(url, signed_data)
51
+ result = JSON.parse(response.body)
52
+ result["message"] == "ok"
53
+ end
54
+
55
+ def self.sign_nonce(ssecurity, nonce)
56
+ digest = OpenSSL::Digest.new("SHA256")
57
+ digest.update(Base64.decode64(ssecurity))
58
+ digest.update(Base64.decode64(nonce))
59
+ Base64.strict_encode64(digest.digest)
60
+ end
61
+
62
+ def self.sign_data(uri, data, ssecurity)
63
+ data = data.to_json unless data.is_a?(String)
64
+
65
+ nonce = Base64.strict_encode64(OpenSSL::Random.random_bytes(8) + [Time.now.to_i / 60].pack("N"))
66
+ snonce = sign_nonce(ssecurity, nonce)
67
+
68
+ msg = [uri, snonce, nonce, "data=#{data}"].join("&")
69
+ sign = OpenSSL::HMAC.digest("SHA256", Base64.decode64(snonce), msg)
70
+
71
+ {
72
+ "_nonce" => nonce,
73
+ "data" => data,
74
+ "signature" => Base64.strict_encode64(sign)
75
+ }
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "digest"
5
+ require "faraday"
6
+ require "json"
7
+ require "base64"
8
+
9
+ require_relative "../logger"
10
+ require_relative "../utils"
11
+
12
+ module Mi
13
+ module Service
14
+ class Mina
15
+ attr_reader :account, :debug
16
+
17
+ DEFAULT_HEADERS = {
18
+ "User-Agent": "MiHome/6.0.103 (com.xiaomi.mihome; build:6.0.103.1; iOS 14.4.0) Alamofire/6.0.103 MICO/iOSApp/appStore/6.0.103"
19
+ }.freeze
20
+
21
+ def initialize(account, debug: false)
22
+ @debug = debug
23
+ @account = account
24
+ end
25
+
26
+ def device_list(master = 0)
27
+ sid = "micoapi"
28
+ url = "https://api2.mina.mi.com/admin/v2/device_list?master=#{master}"
29
+ request_id = "app_ios_#{Mi::Utils.get_random(30)}"
30
+ url += "&requestId=#{request_id}"
31
+
32
+ client = Faraday.new(url) do |f|
33
+ f.response :logger if debug
34
+ f.headers = DEFAULT_HEADERS.merge("Cookie" => Mi::Utils.cookie2str(account.auth_cookies(sid)))
35
+ end
36
+
37
+ response = client.get(url)
38
+ JSON.parse(response.body)["data"]
39
+ end
40
+
41
+ def text_to_speech(device_id, text)
42
+ sid = "micoapi"
43
+ url = "https://api2.mina.mi.com/remote/ubus"
44
+ request_id = "app_ios_#{Mi::Utils.get_random(30)}"
45
+ data = {
46
+ "requestId" => request_id,
47
+ "deviceId" => device_id,
48
+ "method" => "text_to_speech",
49
+ "path" => "mibrain",
50
+ "message" => { text: text }.to_json
51
+ }
52
+
53
+ client = Faraday.new(url) do |f|
54
+ f.response :logger if debug
55
+ f.request :url_encoded
56
+ f.headers = DEFAULT_HEADERS.merge("Cookie" => Mi::Utils.cookie2str(account.auth_cookies(sid)))
57
+ end
58
+ response = client.post(url, data)
59
+ JSON.parse(response.body)
60
+ end
61
+
62
+ def player_pause(device_id)
63
+ sid = "micoapi"
64
+ url = "https://api2.mina.mi.com/remote/ubus"
65
+ request_id = "app_ios_#{Mi::Utils.get_random(30)}"
66
+ data = {
67
+ "requestId" => request_id,
68
+ "deviceId" => device_id,
69
+ "method" => "player_play_operation",
70
+ "path" => "mediaplayer",
71
+ "message" => { action: "pause", media: "app_ios" }.to_json
72
+ }
73
+
74
+ client = Faraday.new(url) do |f|
75
+ f.response :logger if debug
76
+ f.request :url_encoded
77
+ f.headers = DEFAULT_HEADERS.merge("Cookie" => Mi::Utils.cookie2str(account.auth_cookies(sid)))
78
+ end
79
+ response = client.post(url, data)
80
+ JSON.parse(response.body)
81
+ end
82
+
83
+ def player_stop(device_id)
84
+ sid = "micoapi"
85
+ url = "https://api2.mina.mi.com/remote/ubus"
86
+ request_id = "app_ios_#{Mi::Utils.get_random(30)}"
87
+ data = {
88
+ "requestId" => request_id,
89
+ "deviceId" => device_id,
90
+ "method" => "player_play_operation",
91
+ "path" => "mediaplayer",
92
+ "message" => { action: "stop", media: "app_ios" }.to_json
93
+ }
94
+
95
+ client = Faraday.new(url) do |f|
96
+ f.response :logger if debug
97
+ f.request :url_encoded
98
+ f.headers = DEFAULT_HEADERS.merge("Cookie" => Mi::Utils.cookie2str(account.auth_cookies(sid)))
99
+ end
100
+ response = client.post(url, data)
101
+ JSON.parse(response.body)
102
+ end
103
+
104
+ def player_get_status(device_id)
105
+ sid = "micoapi"
106
+ url = "https://api2.mina.mi.com/remote/ubus"
107
+ request_id = "app_ios_#{Mi::Utils.get_random(30)}"
108
+ data = {
109
+ "requestId" => request_id,
110
+ "deviceId" => device_id,
111
+ "method" => "player_get_play_status",
112
+ "path" => "mediaplayer",
113
+ "message" => { media: "app_ios" }.to_json
114
+ }
115
+
116
+ client = Faraday.new(url) do |f|
117
+ f.response :logger if debug
118
+ f.request :url_encoded
119
+ f.headers = DEFAULT_HEADERS.merge("Cookie" => Mi::Utils.cookie2str(account.auth_cookies(sid)))
120
+ end
121
+ response = client.post(url, data)
122
+ JSON.parse(response.body)
123
+ end
124
+
125
+ def message_list(device_id:, hardware:, timestamp: Time.now.to_i * 1000, limit: 2)
126
+ sid = "micoapi"
127
+ url = "https://userprofile.mina.mi.com/device_profile/v2/conversation?source=dialogu&hardware=#{hardware}&timestamp=#{timestamp}&limit=#{limit}"
128
+
129
+ client = Faraday.new(url) do |f|
130
+ f.response :logger if debug
131
+ f.headers = DEFAULT_HEADERS.merge(
132
+ "Cookie" => Mi::Utils.cookie2str(account.auth_cookies(sid).merge("deviceId" => device_id))
133
+ )
134
+ end
135
+
136
+ response = client.get(url)
137
+ JSON.parse(response.body)
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mi
4
+ module Service
5
+ VERSION = "1.0.0"
6
+ end
7
+ end
data/lib/mi/service.rb ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "service/version"
4
+ require_relative "service/account"
5
+ require_relative "service/mina"
6
+ require_relative "service/miio"
7
+
8
+ module Mi
9
+ module Service
10
+ class Error < StandardError; end
11
+ end
12
+ end
data/lib/mi/utils.rb ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Mi
6
+ module Utils
7
+ def self.get_random(length)
8
+ SecureRandom.alphanumeric(length)
9
+ end
10
+
11
+ def self.cookie2str(cookies)
12
+ cookies.map { |k, v| "#{k}=#{v}" }.join("; ")
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,6 @@
1
+ module Mi
2
+ module Service
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,73 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mi-service
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Hooopo
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-06-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: Write a longer description or delete this line.
28
+ email:
29
+ - hoooopo@gmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rubocop.yml"
35
+ - CHANGELOG.md
36
+ - CODE_OF_CONDUCT.md
37
+ - LICENSE.txt
38
+ - README.md
39
+ - Rakefile
40
+ - lib/mi/logger.rb
41
+ - lib/mi/service.rb
42
+ - lib/mi/service/account.rb
43
+ - lib/mi/service/miio.rb
44
+ - lib/mi/service/mina.rb
45
+ - lib/mi/service/version.rb
46
+ - lib/mi/utils.rb
47
+ - sig/mi/service.rbs
48
+ homepage: https://github.com/hooopo/mi-service
49
+ licenses:
50
+ - MIT
51
+ metadata:
52
+ homepage_uri: https://github.com/hooopo/mi-service
53
+ rubygems_mfa_required: 'true'
54
+ post_install_message:
55
+ rdoc_options: []
56
+ require_paths:
57
+ - lib
58
+ required_ruby_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: 2.6.0
63
+ required_rubygems_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ requirements: []
69
+ rubygems_version: 3.5.3
70
+ signing_key:
71
+ specification_version: 4
72
+ summary: Write a short summary, because RubyGems requires one.
73
+ test_files: []