hivemind-http-protocol 0.0.1__tar.gz

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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 Casimiro Ferreira
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.1
2
+ Name: hivemind-http-protocol
3
+ Version: 0.0.1
4
+ Summary: http network protocol for hivemind-core
5
+ Home-page: https://github.com/JarbasHiveMind/hivemind-http-protocol
6
+ Author: jarbasAi
7
+ Author-email: jarbasai@mailfence.com
8
+ License: Apache-2.0
9
+ License-File: LICENSE.md
@@ -0,0 +1,158 @@
1
+ # HiveMind HTTP Protocol
2
+
3
+ The HiveMind HTTP Protocol provides an alternative REST-based implementation for message exchange in the HiveMind ecosystem.
4
+
5
+
6
+ ---
7
+
8
+ ## Configuration
9
+
10
+ This plugin integrates with the `hivemind-core` framework. It is not a standalone project, and its behavior is controlled by the `hivemind-core` configuration.
11
+
12
+ To enable and configure the HiveMind HTTP Protocol, update the `network_protocol` entry in the `hivemind-core` configuration file. Below is an example configuration:
13
+
14
+ ```json
15
+ "network_protocol": {
16
+ "hivemind-websocket-plugin": {
17
+ "host": "0.0.0.0",
18
+ "port": 5678
19
+ },
20
+ "hivemind-http-plugin": {
21
+ "host": "0.0.0.0",
22
+ "port": 5679
23
+ }
24
+ }
25
+ ```
26
+
27
+ ---
28
+ ## Client Library
29
+
30
+
31
+ ```python
32
+ from hivemind_bus_client.http_client import HiveMindHTTPClient, BinaryDataCallbacks
33
+ from hivemind_bus_client.message import HiveMessage, HiveMessageType
34
+ from ovos_bus_client.message import Message
35
+
36
+
37
+ class BinaryDataHandler(BinaryDataCallbacks):
38
+ def handle_receive_tts(self, bin_data: bytes,
39
+ utterance: str,
40
+ lang: str,
41
+ file_name: str):
42
+ # we can play it or save to file or whatever
43
+ print(f"got {len(bin_data)} bytes of TTS audio")
44
+ print(f"utterance: {utterance}", f"lang: {lang}", f"file_name: {file_name}")
45
+ # got 33836 bytes of TTS audio
46
+ # utterance: hello world lang: en-US file_name: 5eb63bbbe01eeed093cb22bb8f5acdc3.wav
47
+
48
+ # not passing key etc so it uses hivemind identity file for details
49
+ client = HiveMindHTTPClient(host="http://localhost", port=5679,
50
+ bin_callbacks=BinaryDataHandler())
51
+
52
+ client.emit(HiveMessage(HiveMessageType.BUS,
53
+ Message("speak:synth", {"utterance": "hello world"})))
54
+ ```
55
+
56
+ ---
57
+
58
+ ## REST API Documentation
59
+
60
+ ### Authentication
61
+
62
+ Authentication is handled via an HTTP `authorization` parameter in the request. The value should be a Base64-encoded string in the format `useragent:access_key`.
63
+
64
+ ### Endpoints
65
+
66
+ #### 1. Connect to the Server
67
+
68
+ **Endpoint:** `/connect`
69
+ **Method:** `POST`
70
+
71
+ **Request Parameters:**
72
+ - `authorization` (string, mandatory): Base64-encoded `useragent:access_key`.
73
+
74
+ **Response:**
75
+ - `200 OK`: `{ "status": "Connected" }`
76
+ - `400 Bad Request`: `{ "error": "Missing authorization" }`
77
+ - `500 Internal Server Error`: `{ "error": "Connection failed" }`
78
+
79
+ ---
80
+
81
+ #### 2. Disconnect from the Server
82
+
83
+ **Endpoint:** `/disconnect`
84
+ **Method:** `POST`
85
+
86
+ **Request Parameters:**
87
+ - `authorization` (string, mandatory): Base64-encoded `useragent:access_key`.
88
+
89
+ **Response:**
90
+ - `200 OK`: `{ "status": "Disconnected" }`
91
+ - `400 Bad Request`: `{ "error": "Missing authorization" }`
92
+ - `500 Internal Server Error`: `{ "error": "Disconnection failed" }`
93
+
94
+ ---
95
+
96
+ #### 3. Send a Message
97
+
98
+ **Endpoint:** `/send_message`
99
+ **Method:** `POST`
100
+
101
+ **Request Parameters:**
102
+ - `authorization` (string, mandatory): Base64-encoded `useragent:access_key`.
103
+ - `message` (string, mandatory): Encoded message payload.
104
+
105
+ **Response:**
106
+ - `200 OK`: `{ "status": "message sent" }`
107
+ - `400 Bad Request`: `{ "error": "Missing message" }`
108
+ - `500 Internal Server Error`: `{ "error": "Message sending failed" }`
109
+
110
+ ---
111
+
112
+ #### 4. Retrieve Messages
113
+
114
+ **Endpoint:** `/get_messages`
115
+ **Method:** `GET`
116
+
117
+ **Request Parameters:**
118
+ - `authorization` (string, mandatory): Base64-encoded `useragent:access_key`.
119
+
120
+ **Response:**
121
+ - `200 OK`: `{ "messages": ["message1", "message2"] }`
122
+ - `400 Bad Request`: `{ "error": "Missing authorization" }`
123
+ - `500 Internal Server Error`: `{ "error": "Failed to retrieve messages" }`
124
+
125
+ ---
126
+
127
+ #### 5. Retrieve Binary Messages
128
+
129
+ **Endpoint:** `/get_binary_messages`
130
+ **Method:** `GET`
131
+
132
+ **Request Parameters:**
133
+ - `authorization` (string, mandatory): Base64-encoded `useragent:access_key`.
134
+
135
+ **Response:**
136
+ - `200 OK`: `{ "messages": ["Base64Message1", "Base64Message2"] }`
137
+ - `400 Bad Request`: `{ "error": "Missing authorization" }`
138
+ - `500 Internal Server Error`: `{ "error": "Failed to retrieve messages" }`
139
+
140
+ ---
141
+
142
+ ## Notes
143
+
144
+ - The `connect` and `disconnect` endpoints enable state management in scenarios where persistent connections are not feasible
145
+ - Binary messages are Base64-encoded to ensure compatibility with REST APIs, which are text-based protocols.
146
+
147
+
148
+ ---
149
+
150
+ ## Contributing
151
+
152
+ Contributions are welcome! Please submit a pull request or open an issue for bug reports or feature requests.
153
+
154
+ ---
155
+
156
+ ## License
157
+
158
+ This project is licensed under the Apache 2.0 License. See the `LICENSE` file for more details.
@@ -0,0 +1,349 @@
1
+ import asyncio
2
+ import dataclasses
3
+ import os
4
+ import os.path
5
+ import random
6
+ from collections import defaultdict
7
+ from queue import Queue
8
+ from os import makedirs
9
+ from os.path import exists, join
10
+ from socket import gethostname
11
+ from typing import Dict, Any, Optional, Tuple, Union
12
+
13
+ import pybase64
14
+ from OpenSSL import crypto
15
+ from ovos_bus_client.session import Session
16
+ from ovos_utils.log import LOG
17
+ from ovos_utils.xdg_utils import xdg_data_home
18
+ from tornado import ioloop
19
+ from tornado import web
20
+ from tornado.platform.asyncio import AnyThreadEventLoopPolicy
21
+
22
+ from hivemind_bus_client.message import HiveMessageType
23
+ from hivemind_core.protocol import (
24
+ HiveMindListenerProtocol,
25
+ HiveMindClientConnection,
26
+ HiveMindNodeType
27
+ )
28
+ from hivemind_plugin_manager.protocols import ClientCallbacks
29
+ from hivemind_plugin_manager.protocols import NetworkProtocol
30
+ from poorman_handshake import PasswordHandShake
31
+
32
+
33
+ @dataclasses.dataclass
34
+ class HiveMindHttpProtocol(NetworkProtocol):
35
+ """
36
+ HTTP handler for managing HiveMind client connections.
37
+
38
+ Attributes:
39
+ hm_protocol (Optional[HiveMindListenerProtocol]): The protocol instance for handling HiveMind messages.
40
+ """
41
+ config: Dict[str, Any] = dataclasses.field(default_factory=dict)
42
+ hm_protocol: Optional[HiveMindListenerProtocol] = None
43
+ callbacks: ClientCallbacks = dataclasses.field(default_factory=ClientCallbacks)
44
+
45
+ def run(self):
46
+ LOG.debug(f"HTTP server config: {self.config}")
47
+ asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
48
+ HiveMindHttpHandler.hm_protocol = self.hm_protocol
49
+
50
+ ssl = self.config.get("ssl", False)
51
+ cert_dir: str = self.config.get("cert_dir") or f"{xdg_data_home()}/hivemind"
52
+ cert_name: str = self.config.get("cert_name") or "hivemind"
53
+ host = self.config.get("host", "0.0.0.0")
54
+ port = int(self.config.get("port", 5678))
55
+
56
+ routes = [
57
+ (r"/connect", ConnectHandler),
58
+ (r"/disconnect", DisconnectHandler),
59
+ (r"/send_message", SendMessageHandler),
60
+ (r"/get_messages", GetMessagesHandler),
61
+ (r"/get_binary_messages", GetBinMessagesHandler),
62
+ ]
63
+ application = web.Application(routes)
64
+ if ssl:
65
+ cert_file = f"{cert_dir}/{cert_name}.crt"
66
+ key_file = f"{cert_dir}/{cert_name}.key"
67
+ if not os.path.isfile(key_file):
68
+ LOG.info(f"Generating self-signed SSL certificate")
69
+ cert_file, key_file = self.create_self_signed_cert(cert_dir, cert_name)
70
+ LOG.debug("Using SSL key at " + key_file)
71
+ LOG.debug("Using SSL certificate at " + cert_file)
72
+ ssl_options = {"certfile": cert_file, "keyfile": key_file}
73
+ LOG.info(f"HTTPS listener started at port: {port}")
74
+ application.listen(port, host, ssl_options=ssl_options)
75
+ else:
76
+ LOG.info(f"HTTP listener started at port: {port}")
77
+ application.listen(port, host)
78
+
79
+ ioloop.IOLoop.current().start()
80
+
81
+ @staticmethod
82
+ def create_self_signed_cert(
83
+ cert_dir: str = f"{xdg_data_home()}/hivemind",
84
+ name: str = "hivemind"
85
+ ) -> Tuple[str, str]:
86
+ """
87
+ Create a self-signed certificate and key pair if they do not already exist.
88
+
89
+ Args:
90
+ cert_dir (str): The directory where the certificate and key will be stored.
91
+ name (str): The base name for the certificate and key files.
92
+
93
+ Returns:
94
+ Tuple[str, str]: The paths to the created certificate and key files.
95
+ """
96
+ cert_file = name + ".crt"
97
+ key_file = name + ".key"
98
+ cert_path = join(cert_dir, cert_file)
99
+ key_path = join(cert_dir, key_file)
100
+ makedirs(cert_dir, exist_ok=True)
101
+
102
+ if not exists(join(cert_dir, cert_file)) or not exists(join(cert_dir, key_file)):
103
+ # Create a key pair
104
+ k = crypto.PKey()
105
+ k.generate_key(crypto.TYPE_RSA, 2048)
106
+
107
+ # Create a self-signed certificate
108
+ cert = crypto.X509()
109
+ cert.get_subject().C = "PT"
110
+ cert.get_subject().ST = "Europe"
111
+ cert.get_subject().L = "Mountains"
112
+ cert.get_subject().O = "Jarbas AI"
113
+ cert.get_subject().OU = "Powered by HiveMind"
114
+ cert.get_subject().CN = gethostname()
115
+ cert.set_serial_number(random.randint(0, 2000))
116
+ cert.gmtime_adj_notBefore(0)
117
+ cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
118
+ cert.set_issuer(cert.get_subject())
119
+ cert.set_pubkey(k)
120
+ # TODO: Don't use SHA1
121
+ cert.sign(k, "sha1")
122
+
123
+ open(cert_path, "wb").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
124
+ open(key_path, "wb").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
125
+
126
+ return cert_path, key_path
127
+
128
+
129
+ class HiveMindHttpHandler(web.RequestHandler):
130
+ """Base handler for HTTP requests."""
131
+ hm_protocol = None
132
+
133
+ # Class-level properties for managing client state and message queues
134
+ clients: Dict[str, HiveMindClientConnection] = {}
135
+ undelivered: Dict[str, Queue] = defaultdict(Queue) # Non-binary messages
136
+ undelivered_bin: Dict[str, Queue] = defaultdict(Queue) # Binary messages
137
+
138
+ def decode_auth(self):
139
+ auth = self.get_argument("authorization", "")
140
+ if not auth:
141
+ self.set_status(400)
142
+ return None, None
143
+ userpass_encoded = bytes(auth, encoding="utf-8")
144
+ userpass_decoded = pybase64.b64decode(userpass_encoded).decode("utf-8")
145
+ return userpass_decoded.split(":")
146
+
147
+ def get_client(self, useragent, key, cache=True) -> Optional[HiveMindClientConnection]:
148
+ if cache and key in self.clients:
149
+ return self.clients[key]
150
+
151
+ def do_send(payload: Union[bytes, str], is_bin: bool):
152
+ if is_bin:
153
+ payload = pybase64.b64encode(payload).decode("utf-8")
154
+ self.undelivered_bin[key].put(payload)
155
+ else:
156
+ self.undelivered[key].put(payload)
157
+
158
+ def do_disconnect():
159
+ if key in self.undelivered:
160
+ self.undelivered.pop(key)
161
+ if key in self.clients:
162
+ self.clients.pop(key)
163
+
164
+ client = HiveMindClientConnection(
165
+ key=key,
166
+ disconnect=do_disconnect,
167
+ send_msg=do_send,
168
+ sess=Session(session_id="default"), # will be re-assigned once client sends handshake
169
+ name=useragent,
170
+ hm_protocol=self.hm_protocol
171
+ )
172
+ self.hm_protocol.db.sync()
173
+ user = self.hm_protocol.db.get_client_by_api_key(key)
174
+ if not user:
175
+ LOG.error("Client provided an invalid Access key")
176
+ self.hm_protocol.handle_invalid_key_connected(client)
177
+ return None
178
+
179
+ client.name = f"{useragent}::{user.client_id}::{user.name}"
180
+ client.crypto_key = user.crypto_key
181
+ client.msg_blacklist = user.message_blacklist or []
182
+ client.skill_blacklist = user.skill_blacklist or []
183
+ client.intent_blacklist = user.intent_blacklist or []
184
+ client.allowed_types = user.allowed_types
185
+ client.can_propagate = user.can_propagate
186
+ client.can_escalate = user.can_escalate
187
+ client.is_admin = user.is_admin
188
+ if user.password:
189
+ # pre-shared password to derive aes_key
190
+ client.pswd_handshake = PasswordHandShake(user.password)
191
+
192
+ client.node_type = HiveMindNodeType.NODE # TODO . placeholder
193
+ if cache:
194
+ self.clients[key] = client
195
+ return client
196
+
197
+
198
+ class ConnectHandler(HiveMindHttpHandler):
199
+ async def post(self):
200
+ try:
201
+ useragent, key = self.decode_auth()
202
+ if not key:
203
+ self.write({"error": "Missing authorization"})
204
+ return
205
+
206
+ client = self.get_client(useragent, key)
207
+
208
+ if (
209
+ not client.crypto_key
210
+ and not self.hm_protocol.handshake_enabled
211
+ and self.hm_protocol.require_crypto
212
+ ):
213
+ LOG.error(
214
+ "No pre-shared crypto key for client and handshake disabled, "
215
+ "but configured to require crypto!"
216
+ )
217
+ # clients requiring handshake support might fail here
218
+ self.hm_protocol.handle_invalid_protocol_version(client)
219
+ return
220
+
221
+ self.hm_protocol.handle_new_client(client)
222
+ self.write({"status": "Connected"})
223
+ except Exception as e:
224
+ LOG.error(f"Connection failed: {e}")
225
+ self.set_status(500)
226
+ self.write({"error": "Connection failed"})
227
+
228
+
229
+ class DisconnectHandler(HiveMindHttpHandler):
230
+ async def post(self):
231
+
232
+ try:
233
+ useragent, key = self.decode_auth()
234
+ if not key:
235
+ self.write({"error": "Missing authorization"})
236
+ return
237
+ if key in HiveMindHttpHandler.clients:
238
+ client = self.get_client(useragent, key)
239
+ LOG.info(f"disconnecting client: {client.peer}")
240
+ self.hm_protocol.handle_client_disconnected(client)
241
+ self.write({"status": "Disconnected"})
242
+ else:
243
+ self.write({"error": "Already Disconnected"})
244
+ except Exception as e:
245
+ LOG.error(f"Disconnection failed: {e}")
246
+ self.set_status(500)
247
+ self.write({"error": "Disconnection failed"})
248
+
249
+
250
+ class SendMessageHandler(HiveMindHttpHandler):
251
+ async def post(self):
252
+ try:
253
+ useragent, key = self.decode_auth()
254
+ if not key:
255
+ self.write({"error": "Missing authorization"})
256
+ return
257
+ # refuse if connect wasnt called first
258
+ if key not in HiveMindHttpHandler.clients:
259
+ self.write({"error": "Client is not connected"})
260
+ return
261
+
262
+ client = self.get_client(useragent, key)
263
+
264
+ message = self.get_argument("message", "")
265
+ if not message:
266
+ self.set_status(400)
267
+ self.write({"error": "Missing message"})
268
+ return
269
+
270
+ message = client.decode(message)
271
+ if (
272
+ message.msg_type == HiveMessageType.BUS
273
+ and message.payload.msg_type == "recognizer_loop:b64_audio"
274
+ ):
275
+ LOG.info(f"Received {client.peer} sent base64 audio for STT")
276
+ else:
277
+ LOG.info(f"Received {client.peer} message: {message}")
278
+ self.hm_protocol.handle_message(message, client)
279
+
280
+ self.write({"status": "message sent"})
281
+ except Exception as e:
282
+ LOG.error(f"Message sending failed: {e}")
283
+ self.set_status(500)
284
+ self.write({"error": "Message sending failed"})
285
+
286
+
287
+ class GetMessagesHandler(HiveMindHttpHandler):
288
+
289
+ async def get(self):
290
+ try:
291
+ useragent, key = self.decode_auth()
292
+ if not key:
293
+ self.write({"error": "Missing authorization"})
294
+ return
295
+
296
+ # refuse if connect wasnt called first
297
+ if key not in HiveMindHttpHandler.clients:
298
+ self.write({"error": "Client is not connected"})
299
+ return
300
+
301
+ messages = []
302
+ queue = HiveMindHttpHandler.undelivered[key]
303
+
304
+ # Retrieve all messages from the queue
305
+ while not queue.empty():
306
+ try:
307
+ message = queue.get_nowait()
308
+ messages.append(message)
309
+ except Exception as e:
310
+ # Handle unexpected errors (unlikely with get_nowait)
311
+ break
312
+ self.write({"status": "messages retrieved", "messages": messages})
313
+ except Exception as e:
314
+ LOG.error(f"Retrieving messages failed: {e}")
315
+ self.set_status(500)
316
+ self.write({"error": "Retrieving messages failed"})
317
+
318
+
319
+ class GetBinMessagesHandler(HiveMindHttpHandler):
320
+
321
+ async def get(self):
322
+ try:
323
+ useragent, key = self.decode_auth()
324
+ if not key:
325
+ self.write({"error": "Missing authorization"})
326
+ return
327
+
328
+ # refuse if connect wasnt called first
329
+ if key not in HiveMindHttpHandler.clients:
330
+ self.write({"error": "Client is not connected"})
331
+ return
332
+
333
+ messages = []
334
+ queue = HiveMindHttpHandler.undelivered_bin[key]
335
+
336
+ # Retrieve all messages from the queue
337
+ while not queue.empty():
338
+ try:
339
+ message = queue.get_nowait()
340
+ messages.append(message)
341
+ except Exception as e:
342
+ # Handle unexpected errors (unlikely with get_nowait)
343
+ break
344
+
345
+ self.write({"status": "messages retrieved", "b64_messages": messages})
346
+ except Exception as e:
347
+ LOG.error(f"Retrieving messages failed: {e}")
348
+ self.set_status(500)
349
+ self.write({"error": "Retrieving messages failed"})
@@ -0,0 +1,6 @@
1
+ # START_VERSION_BLOCK
2
+ VERSION_MAJOR = 0
3
+ VERSION_MINOR = 0
4
+ VERSION_BUILD = 1
5
+ VERSION_ALPHA = 0
6
+ # END_VERSION_BLOCK
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.1
2
+ Name: hivemind-http-protocol
3
+ Version: 0.0.1
4
+ Summary: http network protocol for hivemind-core
5
+ Home-page: https://github.com/JarbasHiveMind/hivemind-http-protocol
6
+ Author: jarbasAi
7
+ Author-email: jarbasai@mailfence.com
8
+ License: Apache-2.0
9
+ License-File: LICENSE.md
@@ -0,0 +1,11 @@
1
+ LICENSE.md
2
+ README.md
3
+ setup.py
4
+ hivemind_http_protocol/__init__.py
5
+ hivemind_http_protocol/version.py
6
+ hivemind_http_protocol.egg-info/PKG-INFO
7
+ hivemind_http_protocol.egg-info/SOURCES.txt
8
+ hivemind_http_protocol.egg-info/dependency_links.txt
9
+ hivemind_http_protocol.egg-info/entry_points.txt
10
+ hivemind_http_protocol.egg-info/requires.txt
11
+ hivemind_http_protocol.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [hivemind.network.protocol]
2
+ hivemind-http-plugin = hivemind_http_protocol:HiveMindHttpProtocol
@@ -0,0 +1,4 @@
1
+ tornado
2
+ hivemind-plugin-manager
3
+ poorman_handshake>=0.1.0
4
+ pyOpenSSL
@@ -0,0 +1 @@
1
+ hivemind_http_protocol
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,55 @@
1
+ import os
2
+ from setuptools import setup
3
+
4
+ BASEDIR = os.path.abspath(os.path.dirname(__file__))
5
+
6
+
7
+ def get_version():
8
+ """ Find the version of the package"""
9
+ version_file = os.path.join(BASEDIR, 'hivemind_http_protocol', 'version.py')
10
+ major, minor, build, alpha = (None, None, None, None)
11
+ with open(version_file) as f:
12
+ for line in f:
13
+ if 'VERSION_MAJOR' in line:
14
+ major = line.split('=')[1].strip()
15
+ elif 'VERSION_MINOR' in line:
16
+ minor = line.split('=')[1].strip()
17
+ elif 'VERSION_BUILD' in line:
18
+ build = line.split('=')[1].strip()
19
+ elif 'VERSION_ALPHA' in line:
20
+ alpha = line.split('=')[1].strip()
21
+
22
+ if ((major and minor and build and alpha) or
23
+ '# END_VERSION_BLOCK' in line):
24
+ break
25
+ version = f"{major}.{minor}.{build}"
26
+ if int(alpha) > 0:
27
+ version += f"a{alpha}"
28
+ return version
29
+
30
+
31
+ def required(requirements_file):
32
+ """ Read requirements file and remove comments and empty lines. """
33
+ with open(os.path.join(BASEDIR, requirements_file), 'r') as f:
34
+ requirements = f.read().splitlines()
35
+ if 'MYCROFT_LOOSE_REQUIREMENTS' in os.environ:
36
+ print('USING LOOSE REQUIREMENTS!')
37
+ requirements = [r.replace('==', '>=').replace('~=', '>=') for r in requirements]
38
+ return [pkg for pkg in requirements
39
+ if pkg.strip() and not pkg.startswith("#")]
40
+
41
+
42
+ PLUGIN_ENTRY_POINT = 'hivemind-http-plugin=hivemind_http_protocol:HiveMindHttpProtocol'
43
+
44
+ setup(
45
+ name='hivemind-http-protocol',
46
+ version=get_version(),
47
+ packages=['hivemind_http_protocol'],
48
+ url='https://github.com/JarbasHiveMind/hivemind-http-protocol',
49
+ license='Apache-2.0',
50
+ author='jarbasAi',
51
+ install_requires=required("requirements.txt"),
52
+ entry_points={'hivemind.network.protocol': PLUGIN_ENTRY_POINT},
53
+ author_email='jarbasai@mailfence.com',
54
+ description='http network protocol for hivemind-core'
55
+ )