Repository navigation
Expand file tree
/
Copy pathcore.py
More file actions
executable file
·1238 lines (1045 loc) · 39 KB
/
Copy pathcore.py
File metadata and controls
executable file
·1238 lines (1045 loc) · 39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import string
import logging
import json
import pykka
import urllib
import os
import sys
import tornado.web
import tornado.ioloop
import time
import pickle
from pkg_resources import parse_version
from tornado.escape import json_encode
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from . import Extension
from .system import IrisSystemThread
if sys.platform == "win32":
import ctypes
# import logger
logger = logging.getLogger(__name__)
class IrisCore(pykka.ThreadingActor):
version = ""
spotify_token = False
queue_metadata = {}
connections = {}
commands = {}
initial_consume = False
radio = {
"enabled": 0,
"seed_artists": [],
"seed_genres": [],
"seed_tracks": [],
"results": [],
}
data = {}
ioloop = None
@classmethod
async def do_fetch(cls, client, request):
# This wrapper function exists to ease mocking.
return await client.fetch(request)
def setup(self, config, core):
self.config = config
self.core = core
##
# Mopidy server is starting
##
def start(self):
logger.info("Starting Iris " + Extension.version)
self.data["commands"] = self.load_from_file("commands")
self.data["pinned"] = self.load_from_file("pinned")
self.data["shared_config"] = self.load_from_file("shared_config")
##
# Mopidy is shutting down
##
def stop(self):
logger.info("Stopping Iris")
##
# Load a dict from disk
#
# @param name String
# @return Dict
##
def load_from_file(self, name):
file_path = Extension.get_data_dir(self.config) / ("%s.pkl" % name)
try:
with file_path.open("rb") as f:
content = pickle.load(f)
f.close()
return content
except Exception:
if name == "pinned":
return []
else:
return {}
##
# Save dict object to disk
#
# @param dict Dict
# @param name String
# @return void
##
def save_to_file(self, dict, name):
file_path = Extension.get_data_dir(self.config) / ("%s.pkl" % name)
try:
with file_path.open("wb") as f:
pickle.dump(dict, f, pickle.HIGHEST_PROTOCOL)
pickle.close()
except Exception:
return False
##
# Generate a random string
#
# Used for connection_ids where none is provided by client
# @return string
##
def generateGuid(self):
return "".join(
random.choices(string.ascii_uppercase + string.digits, k=12)
)
##
# Digest a protocol header into it's id/name parts
#
# @return dict
##
def digest_protocol(self, protocol):
# if we're a string, split into list
# this handles the different ways we get this passed
# (select_subprotocols gives string, headers.get gives list)
if isinstance(protocol, str):
# make sure we strip any spaces (IE gives "element,element", proper
# browsers give "element, element")
protocol = [i.strip() for i in protocol.split(",")]
# if we've been given a valid array
try:
client_id = protocol[0]
connection_id = protocol[1]
username = protocol[2]
generated = False
# invalid, so just create a default connection, and auto-generate an ID
except BaseException:
client_id = self.generateGuid()
connection_id = self.generateGuid()
username = "Anonymous"
generated = True
# construct our protocol object, and return
return {
"client_id": client_id,
"connection_id": connection_id,
"username": username,
"generated": generated,
}
def send_message(self, *args, **kwargs):
callback = kwargs.get("callback", None)
data = kwargs.get("data", None)
logger.debug(data)
# Catch invalid recipient
if data["recipient"] not in self.connections:
error = 'Connection "' + data["recipient"] + '" not found'
logger.error(error)
error = {"message": error}
if callback:
callback(False, error)
else:
return error
# Sending of an error
if "error" in data:
message = {"jsonrpc": "2.0", "error": data["error"]}
# Sending of a regular message
else:
message = {
"jsonrpc": "2.0",
"method": data["method"] if "method" in data else None,
}
if "id" in data:
message["id"] = data["id"]
if "params" in data:
message["params"] = data["params"]
if "result" in data:
message["result"] = data["result"]
# Dispatch the message
try:
self.connections[data["recipient"]]["connection"].write_message(
json_encode(message)
)
response = {"message": "Sent message to " + data["recipient"]}
if callback:
callback(response)
else:
return response
except BaseException:
error = "Failed to send message to " + data["recipient"]
logger.error(error)
error = {"message": error}
if callback:
callback(False, error)
else:
return error
def broadcast(self, *args, **kwargs):
callback = kwargs.get("callback", None)
data = kwargs.get("data", None)
logger.debug(data)
if "error" in data:
message = {"jsonrpc": "2.0", "error": data["error"]}
else:
message = {
"jsonrpc": "2.0",
"method": data["method"] if "method" in data else None,
"params": data["params"] if "params" in data else None,
}
for connection in self.connections.values():
send_to_this_connection = True
# Don't send the broadcast to the origin, naturally
if "connection_id" in data:
if connection["connection_id"] == data["connection_id"]:
send_to_this_connection = False
if send_to_this_connection:
connection["connection"].write_message(json_encode(message))
response = {
"message": "Broadcast to "
+ str(len(self.connections))
+ " connections"
}
if callback:
callback(response)
else:
return response
##
# Connections
#
# Contains all our connections and client details. This requires
# updates when new clients connect, and old ones disconnect. These
# events are broadcast to all current connections
##
def get_connections(self, *args, **kwargs):
callback = kwargs.get("callback", None)
connections = []
for connection in self.connections.values():
connections.append(connection["client"])
response = {"connections": connections}
if callback:
callback(response)
else:
return response
def add_connection(self, *args, **kwargs):
connection = kwargs.get("connection", None)
client = kwargs.get("client", None)
logger.debug("Connection added")
logger.debug(connection)
self.connections[client["connection_id"]] = {
"client": client,
"connection_id": client["connection_id"],
"connection": connection,
}
self.broadcast(
data={
"method": "connection_added",
"params": {"connection": client},
}
)
def update_connection(self, *args, **kwargs):
callback = kwargs.get("callback", None)
data = kwargs.get("data", {})
connection_id = data["connection_id"]
if connection_id in self.connections:
username = data["username"]
client_id = data["client_id"]
self.connections[connection_id]["client"]["username"] = username
self.connections[connection_id]["client"]["client_id"] = client_id
self.broadcast(
data={
"method": "connection_changed",
"params": {
"connection": self.connections[connection_id]["client"]
},
}
)
response = {"connection": self.connections[connection_id]["client"]}
if callback:
callback(response)
else:
return response
else:
error = 'Connection "' + data["connection_id"] + '" not found'
logger.error(error)
error = {"message": error}
if callback:
callback(False, error)
else:
return error
def remove_connection(self, connection_id):
if connection_id in self.connections:
try:
client = self.connections[connection_id]["client"]
del self.connections[connection_id]
self.broadcast(
data={
"method": "connection_removed",
"params": {"connection": client},
}
)
except BaseException:
logger.error("Failed to close connection to " + connection_id)
def set_username(self, *args, **kwargs):
callback = kwargs.get("callback", None)
data = kwargs.get("data", {})
connection_id = data["connection_id"]
if connection_id in self.connections:
username = data["username"]
self.connections[connection_id]["client"]["username"] = username
self.broadcast(
data={
"method": "connection_changed",
"params": {
"connection": self.connections[connection_id]["client"]
},
}
)
response = {
"connection_id": connection_id,
"username": data["username"],
}
if callback:
callback(response)
else:
return response
else:
error = 'Connection "' + data["connection_id"] + '" not found'
logger.error(error)
error = {"message": error}
if callback:
callback(False, error)
else:
return error
##
# System controls
#
# Faciitates upgrades and configuration fetching
##
def get_config(self, *args, **kwargs):
callback = kwargs.get("callback", False)
# handle config setups where there is no username/password
# Iris won't work properly anyway, but at least we won't get server
# errors
if "spotify" in self.config and "username" in self.config["spotify"]:
spotify_username = self.config["spotify"]["username"]
else:
spotify_username = False
response = {
"config": {
"is_root": self.is_root(),
"spotify_username": spotify_username,
"country": self.config["iris"]["country"],
"locale": self.config["iris"]["locale"],
"snapcast_enabled": self.config["iris"]["snapcast_enabled"],
"snapcast_host": self.config["iris"]["snapcast_host"],
"snapcast_port": self.config["iris"]["snapcast_port"],
"snapcast_ssl": self.config["iris"]["snapcast_ssl"],
"snapcast_stream": self.config["iris"]["snapcast_stream"],
"spotify_authorization_url": self.config["iris"][
"spotify_authorization_url"
],
"lastfm_authorization_url": self.config["iris"][
"lastfm_authorization_url"
],
"genius_authorization_url": self.config["iris"][
"genius_authorization_url"
],
"shared_config": self.data["shared_config"],
}
}
if callback:
callback(response)
else:
return response
async def get_version(self, *args, **kwargs):
callback = kwargs.get("callback", False)
url = "https://pypi.python.org/pypi/Mopidy-Iris/json"
http_client = AsyncHTTPClient()
try:
http_response = await http_client.fetch(url)
response_body = json.loads(http_response.body)
latest_version = response_body["info"]["version"]
current_version = Extension.version
# compare our versions, and convert result to boolean
upgrade_available = parse_version(latest_version) > parse_version(
current_version
)
upgrade_available = upgrade_available == 1
except (urllib.request.HTTPError, urllib.request.URLError):
latest_version = "0.0.0"
upgrade_available = False
response = {
"version": {
"current": current_version,
"latest": latest_version,
"is_root": self.is_root(),
"upgrade_available": upgrade_available,
}
}
if callback:
callback(response)
else:
return response
##
# Restart Mopidy
# This requires sudo access to system.sh
##
def restart(self, *args, **kwargs):
callback = kwargs.get("callback", False)
ioloop = kwargs.get("ioloop", False)
# Trigger the action
IrisSystemThread("restart", ioloop, self.restart_callback).start()
self.broadcast(data={"method": "restart_started"})
response = {"message": "Restart started"}
if callback:
callback(response)
else:
return response
def restart_callback(self, response, error, update):
if error:
self.broadcast(data={"method": "restart_error", "params": error})
elif update:
self.broadcast(data={"method": "restart_updated", "params": update})
else:
self.broadcast(
data={"method": "restart_finished", "params": response}
)
##
# Run an upgrade of Iris
##
def upgrade(self, *args, **kwargs):
callback = kwargs.get("callback", False)
ioloop = kwargs.get("ioloop", False)
self.broadcast(data={"method": "upgrade_started"})
# Trigger the action
IrisSystemThread("upgrade", ioloop, self.upgrade_callback).start()
response = {"message": "Upgrade started"}
if callback:
callback(response)
else:
return response
def upgrade_callback(self, response, error, update):
if error:
self.broadcast(data={"method": "upgrade_error", "params": error})
elif update:
self.broadcast(data={"method": "upgrade_updated", "params": update})
else:
self.broadcast(
data={"method": "upgrade_finished", "params": response}
)
self.restart()
##
# Run a mopidy local scan
# Essetially an alias to "mopidyctl local scan"
##
def local_scan(self, *args, **kwargs):
callback = kwargs.get("callback", False)
ioloop = kwargs.get("ioloop", False)
# Trigger the action
IrisSystemThread("local_scan", ioloop, self.local_scan_callback).start()
self.broadcast(data={"method": "local_scan_started"})
response = {"message": "Local scan started"}
if callback:
callback(response)
else:
return response
def local_scan_callback(self, response, error, update):
if error:
self.broadcast(data={"method": "local_scan_error", "params": error})
elif update:
self.broadcast(
data={"method": "local_scan_updated", "params": update}
)
else:
self.broadcast(
data={"method": "local_scan_finished", "params": response}
)
##
# Spotify Radio
#
# Accepts seed URIs and creates radio-like experience. When our
# tracklist is nearly empty, we fetch more recommendations. This
# can result in duplicates. We keep the recommendations limit low
# to avoid timeouts and slow UI
##
def get_radio(self, *args, **kwargs):
callback = kwargs.get("callback", False)
response = {"radio": self.radio}
if callback:
callback(response)
else:
return response
async def change_radio(self, *args, **kwargs):
callback = kwargs.get("callback", False)
data = kwargs.get("data", {})
# We're starting a new radio (or forced restart)
if data["reset"] or not self.radio["enabled"]:
starting = True
self.initial_consume = self.core.tracklist.get_consume().get()
else:
starting = False
# fetch more tracks from Mopidy-Spotify
self.radio = {
"seed_artists": data["seed_artists"],
"seed_genres": data["seed_genres"],
"seed_tracks": data["seed_tracks"],
"enabled": 1,
"results": [],
}
uris = await self.load_more_tracks()
# make sure we got recommendations
if uris:
if starting:
self.core.tracklist.clear()
self.core.tracklist.set_consume(True)
# We only want to play the first batch
added = self.core.tracklist.add(uris=uris[0:3])
if not added.get():
logger.error("No recommendations added to queue")
self.radio["enabled"] = 0
error = {
"message": "No recommendations added to queue",
"radio": self.radio,
}
if callback:
callback(False, error)
else:
return error
# Save results (minus first batch) for later use
self.radio["results"] = uris[3:]
self.add_radio_metadata(added)
if starting:
self.core.playback.play()
self.broadcast(
data={
"method": "radio_started",
"params": {"radio": self.radio},
}
)
else:
self.broadcast(
data={
"method": "radio_changed",
"params": {"radio": self.radio},
}
)
self.get_radio(callback=callback)
return
# Failed fetching/adding tracks, so no-go
else:
logger.error("No recommendations returned by Spotify")
self.radio["enabled"] = 0
error = {
"code": 32500,
"message": "Could not start radio",
"data": {"radio": self.radio},
}
if callback:
callback(False, error)
else:
return error
def stop_radio(self, *args, **kwargs):
callback = kwargs.get("callback", False)
self.radio = {
"enabled": 0,
"seed_artists": [],
"seed_genres": [],
"seed_tracks": [],
"results": [],
}
# restore initial consume state
self.core.tracklist.set_consume(self.initial_consume)
self.core.playback.stop()
self.broadcast(
data={"method": "radio_stopped", "params": {"radio": self.radio}}
)
response = {"message": "Stopped radio"}
if callback:
callback(response)
else:
return response
async def load_more_tracks(self, *args, **kwargs):
logger.info("Loading more radio tracks from Spotify")
try:
await self.get_spotify_token()
spotify_token = self.spotify_token
access_token = spotify_token["access_token"]
except BaseException:
error = "IrisFrontend: access_token missing or invalid"
logger.error(error)
return False
url = "https://api.spotify.com/v1/recommendations/"
url = (
url
+ "?seed_artists="
+ (",".join(self.radio["seed_artists"])).replace(
"spotify:artist:", ""
)
)
url = (
url
+ "&seed_genres="
+ (",".join(self.radio["seed_genres"])).replace(
"spotify:genre:", ""
)
)
url = (
url
+ "&seed_tracks="
+ (",".join(self.radio["seed_tracks"])).replace(
"spotify:track:", ""
)
)
url = url + "&limit=50"
http_client = AsyncHTTPClient()
try:
http_response = await http_client.fetch(
url, "POST", headers={"Authorization": "Bearer " + access_token}
)
response_body = json.loads(http_response.body)
uris = []
for track in response_body["tracks"]:
uris.append(track["uri"])
return uris
except (urllib.error.HTTPError, urllib.error.URLError) as e:
error = json.loads(e.read())
error_response = {
"message": "Could not fetch Spotify recommendations: "
+ error["error_description"]
}
logger.error(
"Could not fetch Spotify recommendations: "
+ error["error_description"]
)
logger.debug(error_response)
return False
async def check_for_radio_update(self):
tracklistLength = self.core.tracklist.get_length().get()
if tracklistLength < 3 and self.radio["enabled"] == 1:
# Grab our loaded tracks
uris = self.radio["results"]
# We've run out of pre-fetched tracks, so we need to get more
# recommendations
if len(uris) < 3:
uris = await self.load_more_tracks()
# Remove the next batch, and update our results
self.radio["results"] = uris[3:]
# Only add the next set of uris
uris = uris[0:3]
added = self.core.tracklist.add(uris=uris)
self.add_radio_metadata(added)
def add_radio_metadata(self, added):
seeds = []
if len(self.radio["seed_artists"]) > 0:
seeds = seeds + self.radio["seed_artists"]
if len(self.radio["seed_tracks"]) > 0:
seeds = seeds + self.radio["seed_tracks"]
if len(self.radio["seed_genres"]) > 0:
seeds = seeds + self.radio["seed_genres"]
metadata = {
"tlids": [],
"added_by": "Radio",
"added_from": {
"name": "Radio",
"type": "radio",
"seeds": seeds
}
}
for added_tltrack in added.get():
metadata["tlids"].append(added_tltrack.tlid)
self.add_queue_metadata(data=metadata)
##
# Additional queue metadata
#
# This maps tltracks with extra info for display in Iris, including
# added_by and from_uri.
##
def get_queue_metadata(self, *args, **kwargs):
callback = kwargs.get("callback", False)
response = {"queue_metadata": self.queue_metadata}
if callback:
callback(response)
else:
return response
def add_queue_metadata(self, *args, **kwargs):
callback = kwargs.get("callback", False)
data = kwargs.get("data", {})
for tlid in data["tlids"]:
item = {
"tlid": tlid,
"added_from": data["added_from"]
if "added_from" in data
else None,
"added_by": data["added_by"] if "added_by" in data else None,
}
self.queue_metadata["tlid_" + str(tlid)] = item
self.broadcast(
data={
"method": "queue_metadata_changed",
"params": {"queue_metadata": self.queue_metadata},
}
)
response = {"message": "Added queue metadata"}
if callback:
callback(response)
else:
return response
def clean_queue_metadata(self, *args, **kwargs):
cleaned_queue_metadata = {}
for tltrack in self.core.tracklist.get_tl_tracks().get():
# if we have metadata for this track, push it through to cleaned
# dictionary
if "tlid_" + str(tltrack.tlid) in self.queue_metadata:
cleaned_queue_metadata[
"tlid_" + str(tltrack.tlid)
] = self.queue_metadata["tlid_" + str(tltrack.tlid)]
self.queue_metadata = cleaned_queue_metadata
##
# Server-side data assets
#
# These functions are used internally to store data locally for all users to access
##
def get_data(self, name, *args, **kwargs):
callback = kwargs.get("callback", False)
response = {name: self.data[name]}
if callback:
callback(response)
else:
return response
def set_data(self, name, *args, **kwargs):
callback = kwargs.get("callback", False)
data = kwargs.get("data", {})
# Update our temporary variable
self.data[name] = data[name]
# Save the new commands to file storage
self.save_to_file(self.data[name], name)
self.broadcast(
data={
"method": f"{name}_changed",
"params": {name: self.data[name]},
}
)
response = {"message": f"Saved {name}"}
if callback:
callback(response)
else:
return response
##
# Pinned assets
##
def get_pinned(self, *args, **kwargs):
return self.get_data("pinned", *args, **kwargs)
def set_pinned(self, *args, **kwargs):
return self.set_data("pinned", *args, **kwargs)
##
# Portable configuration template for other users to import
##
def get_shared_config(self, *args, **kwargs):
return self.get_data("shared_config", *args, **kwargs)
def set_shared_config(self, *args, **kwargs):
return self.set_data("shared_config", *args, **kwargs)
##
# Commands
##
def get_commands(self, *args, **kwargs):
return self.get_data("commands", *args, **kwargs)
def set_commands(self, *args, **kwargs):
return self.set_data("commands", *args, **kwargs)
async def run_command(self, *args, **kwargs):
callback = kwargs.get("callback", False)
data = kwargs.get("data", {})
error = False
if str(data["id"]) not in self.data["commands"]:
error = {
"message": "Command failed",
"description": "Could not find command by ID "
+ '"'
+ str(data["id"])
+ '"',
}
else:
command = self.data["commands"][str(data["id"])]
if "method" not in command:
error = {
"message": "Command failed",
"description": 'Missing required property "method"',
}
if "url" not in command:
error = {
"message": "Command failed",
"description": 'Missing required property "url"',
}
logger.debug("Running command " + str(command))
if error:
if callback:
callback(False, error)
return
else:
return error
# Build headers dict if additional headers are given
headers = None
if "additional_headers" in command:
d = command["additional_headers"].split("\n")
lines = list(filter(lambda x: x.find(":") > 0, d))
fields = [
(x.split(":", 1)[0].strip().lower(), x.split(":", 1)[1].strip())
for x in lines
]
headers = dict(fields)
if command["method"] == "POST":
if (
"content-type" in headers
and headers["content-type"].lower() != "application/json"
):
post_data = command["post_data"]
else:
post_data = json.dumps(command["post_data"])
request = HTTPRequest(
command["url"],
connect_timeout=5,
method="POST",
body=post_data,
validate_cert=False,
headers=headers,
)
else:
request = HTTPRequest(
command["url"],
connect_timeout=5,
validate_cert=False,
headers=headers,
)
# Make the request, and handle any request errors
try:
http_client = AsyncHTTPClient()
command_response = await http_client.fetch(request)
except Exception as e:
error = {"message": "Command failed", "description": str(e)}
if callback:
callback(False, error)
return
else:
return error
# Attempt to parse body as JSON
try:
command_response_body = json.loads(command_response.body)
except BaseException:
# Perhaps it requires unicode encoding?
try:
command_response_body = tornado.escape.to_unicode(
command_response.body
)
except BaseException:
command_response_body = ""
# Finally, return the result
response = {"message": "Command run", "response": command_response_body}
if callback:
callback(response)
return
else:
return response