-
Notifications
You must be signed in to change notification settings - Fork 0
/
tv
executable file
·1824 lines (1611 loc) · 71.5 KB
/
tv
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
#!/usr/bin/env python3
"""
tv: control a Sony TV
The Sony TV has a JSON REST-ish RPC interface. We can call it.
We enter a REPL if no parameters are provided.
Beware that digits on the remote do not enter ASCII digits but some other
unicode digits.
Beware that encryption keys are not very securely managed, but I think it's
about appropriate for use as a TV remote, since I don't want to have to enter a
password to talk to the TV. So we have a `changeme` level non-secret used as
a tiny obfuscation layer for local storage. Since we're already storing the PIN
to talk to the TV in clear-text on disk, there's no worse vulnerability here.
"""
__author__ = 'phil@pennock-tech.com (Phil Pennock)'
import argparse
import base64
import collections
from dataclasses import dataclass
import html
import inspect
import json
import os
import pathlib
import re
import readline
import secrets
import shlex
import sys
import time
import traceback
import typing
import uuid
# TV can encrypt text strings, which we want for sending/reading passwords in app prompts
import cryptography.hazmat.backends
import cryptography.hazmat.primitives
import cryptography.hazmat.primitives.padding
# import cryptography.hazmat.primitives.asymmetric.rsa
# Sane HTTP
import requests
if sys.stdout.isatty():
import curses
import curses.textpad
import io
import pygments
import pygments.lexers
import pygments.formatters
if sys.version_info < (3, 6):
raise Exception('Need at least Python 3.6 for this tool')
# pathlib, f-strings
SCRIPT_DIR = pathlib.Path(__file__).absolute().parent
# FIXME: this is not fully XDG-compliant
_APP_NAME = pathlib.Path('tv')
_REGISTER_APP_NAME = 'tv-sony'
_HOME_DIR = _APP_NAME.home()
VERSION_INFO = '0.2.3'
def _xdg_dir(varname: str, home_rel_default: typing.Sequence[str]) -> pathlib.Path:
ps = os.getenv(varname, None)
if ps is None:
p = _HOME_DIR
for n in home_rel_default:
p = p / n
else:
p = pathlib.Path(ps.split(os.path.pathsep)[0])
return p / _APP_NAME
_CONFIG_DIR = _xdg_dir('XDG_CONFIG_HOME', ('.config',)) # read files: default.pin and default.hostname
_CACHE_DIR = _xdg_dir('XDG_CACHE_HOME', ('.cache',)) # keep a copy of the TV's public key for encryption
_DATA_DIR = _xdg_dir('XDG_DATA_HOME', ('.local', 'share',)) # keep our local private/public keys for encryption
_DEFAULT_TV = 'default'
DEF_USERAGENT = f'tv/{VERSION_INFO} (Phil Pennock)'
# This exists just for local disk and might as well be the empty string, but I
# don't want to fight APIs any more, so this is one generated password which
# I'm leaving in source, on the basis that it's like bouncycastle's "changeme"
# string: a password that's not a password, just a known serialization
# constant:
PRIVATE_KEY_PASSWORD = b'Wh#2#*4zbWBH0_o4x,Ad'
class Error(Exception):
"""Base class for exceptions from tv."""
pass
class VolumeSpecParseError(Error):
"""Unparseable volume specification."""
pass
class Exit(Exception):
"""Base class for exceptions which exit without a stack trace."""
pass
class BadInput(Exit):
"""Exceptions indicating bad user input."""
pass
class Unconfigured(Exit):
"""Missing necessary setup configuration."""
pass
class BadAuthentication(Exit):
"""Authentication data is bad."""
pass
# InfraRed Compatible Control data from the TV, for the SOAP interface
IRCCKeyCode = collections.namedtuple('IRCCKeyCode', ['KeyName', 'Rawcode'])
# Readline context management
# If IsCommandSet we will switch; if false, we need to figure out what to do
# differently.
# If Swallow, it takes all remaining args instead of having sub commands.
# MapSubCommands lets us build a tree.
RLContext = collections.namedtuple('RLContext', ['Name', 'IsCommandSet', 'Swallow', 'MapSubCommands'])
# curses button spec
ButtonSpec = collections.namedtuple('ButtonSpec', ['y', 'x', 'Text', 'RemoteKey'])
ButtonMade = collections.namedtuple('ButtonMade', ['top_y', 'top_x', 'height', 'width', 'pad', 'RemoteKey'])
@dataclass
class WrapCrypto:
backend: typing.Any = cryptography.hazmat.backends.default_backend()
DER: typing.Any = cryptography.hazmat.primitives.serialization.Encoding.DER
PEM: typing.Any = cryptography.hazmat.primitives.serialization.Encoding.PEM
PKCS1: typing.Any = cryptography.hazmat.primitives.serialization.PublicFormat.PKCS1
PKCS7: typing.Any = cryptography.hazmat.primitives.padding.PKCS7
PKCS8: typing.Any = cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8
SPKI: typing.Any = cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo
AES: typing.Any = cryptography.hazmat.primitives.ciphers.algorithms.AES
CBC: typing.Any = cryptography.hazmat.primitives.ciphers.modes.CBC
PKCS1v15: typing.Any = cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15
PrivateRaw: typing.Any = cryptography.hazmat.primitives.serialization.PrivateFormat.Raw
Cipher: typing.Any = cryptography.hazmat.primitives.ciphers.Cipher
# NoEncryption apparently does not satisfy KeySerializationEncryption
# I want one fixed serialization type so I can safely load, but
# cryptography only lets me have access to the mutable curated choice.
BestAvailableEncryption: typing.Any = cryptography.hazmat.primitives.serialization.BestAvailableEncryption
want_exponent: int = 65537
want_keysize: int = 2048
AES_BLOCKSIZE_BITS: int = 128
AES_BLOCKSIZE_U8: int = 16
Crypto = WrapCrypto()
class SymKey:
AES_KEY: typing.Optional[bytes] = None
AES_IV: typing.Optional[bytes] = None
def __init__(self):
if SymKey.AES_KEY is None:
SymKey.AES_KEY = secrets.token_bytes(Crypto.AES_BLOCKSIZE_U8)
if SymKey.AES_IV is None:
SymKey.AES_IV = secrets.token_bytes(Crypto.AES_BLOCKSIZE_U8)
self.aes_key = SymKey.AES_KEY
self.aes_iv = SymKey.AES_IV
SymKey.AES_IV = (int.from_bytes(SymKey.AES_IV, byteorder='big') + 1).to_bytes(Crypto.AES_BLOCKSIZE_U8, byteorder='big')
self.cipher = Crypto.Cipher(Crypto.AES(self.aes_key), Crypto.CBC(self.aes_iv), backend=Crypto.backend)
def common_key(self) -> bytes:
return self.aes_key + b':' + self.aes_iv
def encKey(self, pubKey: cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey) -> str:
return base64.b64encode(pubKey.encrypt(
self.common_key(),
Crypto.PKCS1v15(),
)).decode('ASCII')
def encrypt(self, data: str) -> str:
padder = Crypto.PKCS7(Crypto.AES_BLOCKSIZE_BITS).padder()
padded = padder.update(data.encode('utf-8'))
padded += padder.finalize()
enc = self.cipher.encryptor()
return base64.b64encode(enc.update(padded) + enc.finalize()).decode('ASCII')
def decrypt(self, data: str) -> str:
dec = self.cipher.decryptor()
padded = dec.update(data) + dec.finalize()
unpadder = Crypto.PKCS7(Crypto.AES_BLOCKSIZE_BITS).unpadder()
return (unpadder.update(padded) + unpadder.finalize()).encode('utf-8')
class Config:
"""Our storage system and local RSA key mgmt."""
PIN_OPTION, PIN_FILEEXT = 'pin', 'pin'
HOST_OPTION, HOST_FILEEXT = 'host', 'hostname'
def __init__(self, options: argparse.Namespace) -> None:
self.options = options
# .tv is the config name as given, often 'default
# .real_tv is the actual name, use this to write files
self.tv = self.options.tv
self.using_default = self.tv == _DEFAULT_TV
if self.using_default:
self.real_tv = self._find_real_tvname()
else:
self.real_tv = self.tv
try:
self.tv_host = self.derive_field(Config.HOST_OPTION, Config.HOST_FILEEXT)
if self.options.register:
self.remote_name = self.options.register
elif self.auth_cookie_file.exists():
self.load_cookies()
else:
self.tv_pin = self.derive_field(Config.PIN_OPTION, Config.PIN_FILEEXT)
except FileNotFoundError as e:
raise Unconfigured(f'missing stored config for tv ({self.tv})') from e
self.our_rsakey: typing.Optional[cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey] = None
self.aes_iv: typing.Optional[bytes] = None
self.aes_key: typing.Optional[bytes] = None
self.max_age_app_cache = 24 * 3600
def derive_field(self, optname: str, base: str) -> str:
t = getattr(self.options, optname)
if t:
return t
return self.read_config(base)
def read_config(self, base: str) -> str:
fn = _CONFIG_DIR / (self.options.tv + '.' + base)
return fn.read_text().strip()
def load_cookies(self) -> None:
self.cookiejar = requests.cookies.cookiejar_from_dict(
json.load(self.auth_cookie_file.open()),
)
def _find_real_tvname(self) -> str:
# This can't use the PIN file, since that no longer necessarily exists
default_hn_file = _CONFIG_DIR / (_DEFAULT_TV + '.' + Config.HOST_FILEEXT)
return default_hn_file.resolve().stem
@property
def readline_config(self) -> pathlib.Path:
return _CONFIG_DIR / 'readline.conf'
@property
def auth_cookie_file(self) -> pathlib.Path:
return _CACHE_DIR / (self.real_tv + '.cookies.json')
@property
def auth_uuid_file(self) -> pathlib.Path:
return _CACHE_DIR / (self.real_tv + '.uuid')
@property
def auth_remotename_file(self) -> pathlib.Path:
return _CACHE_DIR / (self.real_tv + '.remotename')
@property
def tv_keyfile(self) -> pathlib.Path:
return _CACHE_DIR / (self.real_tv + '.tv.rsa.pub')
@property
def tv_ircc_codes_file(self) -> pathlib.Path:
return _CACHE_DIR / (self.real_tv + '.ircc-codes.json')
@property
def readline_history(self) -> pathlib.Path:
return _CACHE_DIR / (self.real_tv + '.readline.history')
@property
def app_list_file(self) -> pathlib.Path:
return _CACHE_DIR / (self.real_tv + '.apps.json')
@property
def our_public_keyfile(self) -> pathlib.Path:
return _DATA_DIR / 'our.rsa.pub'
@property
def our_private_keyfile(self) -> pathlib.Path:
return _DATA_DIR / 'our.rsa.private'
def persist_current(self, new_tvname: str) -> None:
# A name of '' will write out to current
write_name = new_tvname if new_tvname else self.real_tv
forbidden = [os.path.sep, os.path.pathsep]
if os.path.extsep:
forbidden += [os.path.extsep]
if True in [c in write_name for c in forbidden]:
raise Error(f'bad characters in {write_name!r}')
# We will write the derived merged values, so can modify an existing TV to a new name.
if not _CONFIG_DIR.exists():
_CONFIG_DIR.mkdir(mode=0o700, parents=True)
if write_name == _DEFAULT_TV:
write_name = _DEFAULT_TV + '-real'
pin_file = _CONFIG_DIR / (write_name + '.' + Config.PIN_FILEEXT)
host_file = _CONFIG_DIR / (write_name + '.' + Config.HOST_FILEEXT)
# Don't update defaults until both named entries have been written
to_store = []
if hasattr(self, 'tv_pin'):
to_store.append((pin_file, self.tv_pin))
to_store.append((host_file, self.tv_host))
for f, content in to_store:
if f.exists():
f.unlink()
f.touch(mode=0o600, exist_ok=False)
f.write_text(content + '\n', encoding='utf-8')
self.set_default_tv(write_name)
def set_default_tv(self, target_tvname: str) -> None:
# We have no locking here, so not safe against a concurrent reader.
# For myself now, I don't currently care.
default_pin_file = _CONFIG_DIR / (_DEFAULT_TV + '.' + Config.PIN_FILEEXT)
default_host_file = _CONFIG_DIR / (_DEFAULT_TV + '.' + Config.HOST_FILEEXT)
pin_file = _CONFIG_DIR / (target_tvname + '.' + Config.PIN_FILEEXT)
host_file = _CONFIG_DIR / (target_tvname + '.' + Config.HOST_FILEEXT)
to_link = []
to_unlink = []
if not host_file.exists():
raise BadInput(f"can't repoint default TV to {target_tvname!r}, missing {host_file.name!r}")
if not pin_file.exists():
if not self.auth_cookie_file.exists():
raise BadInput(f"can't repoint default TV to {target_tvname!r}, missing {pin_file.name!r}")
else:
to_unlink.append(default_pin_file)
else:
to_link.append((default_pin_file, pin_file))
to_link.append((default_host_file, host_file))
for src, dest in to_link:
if src.exists() and not src.is_symlink():
src.rename(src.with_suffix('.old' + src.suffix))
if src.exists() or src.is_symlink():
src.unlink()
src.symlink_to(dest.name)
for stale in to_unlink:
if stale.exists():
stale.unlink()
def load_pubkey_b64(self, b64data: str) -> cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey:
return self.load_pubkey_bin(base64.b64decode(b64data, validate=True))
def load_pubkey_bin(self, bindata: bytes) -> cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey:
return cryptography.hazmat.primitives.serialization.load_der_public_key(bindata, backend=Crypto.backend)
def make_rsa_key(self) -> cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey:
return cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(
public_exponent=Crypto.want_exponent,
key_size=Crypto.want_keysize,
backend=Crypto.backend)
def write_file(self, fpath: pathlib.Path, data: bytes) -> None:
if not fpath.parent.exists():
fpath.parent.mkdir(0o700)
if fpath.exists():
saved = fpath.with_suffix('.old' + fpath.suffix)
if saved.exists():
saved.unlink()
fpath.rename(saved)
fpath.touch(mode=0o600, exist_ok=False)
fpath.write_bytes(data)
def save_our_private_key(self, rsakey: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey) -> None:
self.write_file(
self.our_private_keyfile,
rsakey.private_bytes(
encoding=Crypto.PEM,
format=Crypto.PKCS8,
encryption_algorithm=Crypto.BestAvailableEncryption(PRIVATE_KEY_PASSWORD)),
)
def save_our_public_key(self, rsakey: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey) -> None:
# We don't use this ourselves, we do this so that other tooling can look at it if wanted.
self.write_file(
self.our_public_keyfile,
rsakey.public_key().public_bytes(Crypto.PEM, Crypto.PKCS1),
)
def setup_thisremote_encryption(self, force_new_remote_key=False) -> None:
if self.our_private_keyfile.exists() and not force_new_remote_key:
self.our_rsakey = cryptography.hazmat.primitives.serialization.load_pem_private_key(
self.our_private_keyfile.read_bytes(),
password=PRIVATE_KEY_PASSWORD,
backend=Crypto.backend)
else:
self.our_rsakey = self.make_rsa_key()
self.save_our_public_key(self.our_rsakey)
self.save_our_private_key(self.our_rsakey)
def load_ircc_codes(self) -> typing.Dict:
bare = json.load(open(self.tv_ircc_codes_file))
typed: typing.Dict[str, IRCCKeyCode] = {}
for k, p in bare.items():
typed[k] = IRCCKeyCode(*p)
return typed
def save_ircc_codes(self, jdata: typing.Dict) -> None:
if not self.tv_ircc_codes_file.parent.exists():
self.tv_ircc_codes_file.parent.mkdir(0o700)
with self.tv_ircc_codes_file.open('w') as wh:
# sort to make git and diff saner, if we move from cache
json.dump(jdata, wh, indent=1, sort_keys=True)
class Remote:
"""Talking to the TV via various protocols.
Most of the stuff is REST API, but anything which is directly emulating a
remote control is IRCC-IP (InfraRed Compatible Control over Internet Protocol),
using SOAP XML.
"""
def __init__(self, config: Config) -> None:
self.options = config.options
self.config = config
self.output = sys.stdout
self.errstream = sys.stderr
self.next_id = 1
self.addr = config.tv_host
if hasattr(config, 'tv_pin'):
self.pin = config.tv_pin
self._tv_pubkey_b64: typing.Optional[str] = None
self._tv_pubkey_bin: typing.Optional[bytes] = None
self._ircc_dict: typing.Optional[typing.Dict[str, IRCCKeyCode]] = None
self._setup_requests()
def verbosity(self, n: int = 1) -> bool:
return True if self.options.verbose >= n else False
def verbose(self, message: str, level=1) -> None:
if self.options.verbose < level:
return
print('[remote] '+message, file=self.errstream, flush=True)
def _setup_requests(self) -> None:
self.session = requests.Session()
self.session.headers['User-Agent'] = DEF_USERAGENT
if hasattr(self.config, 'cookiejar'):
self.session.cookies = self.config.cookiejar
elif hasattr(self, 'pin'):
self.session.headers['X-Auth-PSK'] = self.pin
def _send(self, service: str, method: str, params: typing.Union[typing.Dict, typing.List], *, api_version='1.0'):
url = f'http://{self.addr}/sony/{service}'
if len(params) == 1 and '_empty' in params:
# The introspection call, alone, seems to want [""] for params and nothing else will do.
# (It also returns inside 'results' instead of 'result')
payload_params = ['']
elif params and isinstance(params, dict):
payload_params = [params]
elif params and isinstance(params, list):
# remote pairing sends _two_ dictionaries
payload_params = params
else:
payload_params = []
payload_d = {
'method': method,
'version': api_version,
'id': self.next_id,
'params': payload_params
}
self.next_id += 1
req = self.session.prepare_request(requests.Request('POST', url, json=payload_d))
if self.verbosity(3):
print(f'> POST <{url}> ', end='', file=self.output, flush=True)
if self.verbosity(5):
# don't use pretty_print_json, an auth header with bytes will upset the JSON encoder
print('', file=self.output)
for k, v in req.headers.items():
print(f'{k}: {v}', file=self.output)
pretty_print_json(payload_d, stream=self.output)
elif self.verbosity(2):
print(f' >> {service} / {method}', file=self.output)
# Just because I want to be able to dump all request headers, things get hairy.
settings = self.session.merge_environment_settings(req.url, {}, None, None, None)
r = self.session.send(req, **settings)
return r
def send(self, service: str, method: str, params: typing.Union[typing.Dict, typing.List], **kwargs) -> None:
r = self._send(service, method, params, **kwargs)
if self.verbosity():
pretty_print_json(r.json(), stream=self.output)
def query(self, service: str, method: str, params: typing.Union[typing.Dict, typing.List], **kwargs) -> typing.Dict:
res = self._send(service, method, params, **kwargs)
if self.verbosity(3):
print(f'< {res.status_code} {res.reason}', file=self.output)
if self.verbosity(4):
pretty_print_json(dict(res.headers), stream=self.output)
pretty_print_json(res.json(), stream=self.output)
return res.json()
def check_error(self, label: str, result: typing.Dict) -> None:
if 'error' not in result:
return
code, message = result['error'][:2]
exitmsg = f'failed in {label}: code {code} message: {message}'
if code == 403:
raise BadAuthentication(exitmsg)
raise Exit(exitmsg)
def checked_send(self, service: str, method: str, params: typing.Union[typing.Dict, typing.List], **kwargs) -> None:
r = self._send(service, method, params, **kwargs)
if self.verbosity():
pretty_print_json(r.json(), stream=self.output)
self.check_error(inspect.stack()[1].function, r.json())
# <https://pro-bravia.sony.net/develop/integrate/rest-api/spec/>
KNOWN_SERVICES = 'guide appControl audio avContent encryption system videoScreen'.split()
def _get_power(self) -> str:
resp = self.query('system', 'getPowerStatus', {})
return resp['result'][0]['status']
def _set_power(self, power_state: bool) -> None:
self.checked_send('system', 'setPowerStatus', {'status': power_state})
power = property(_get_power, _set_power, None)
def _set_mute(self, mute_state: bool) -> None:
self.checked_send('audio', 'setAudioMute', {'status': mute_state})
mute = property(None, _set_mute, None)
# this is paired with :playing, query_playing_content_info()
# might build a map of uris to labels and try to simplify through that, for a better reader?
def set_external_input(self, kind: str, port: str) -> None:
uri = f'extInput:{kind}?port={port}'
self.checked_send('avContent', 'setPlayContent', {'uri': uri})
def _get_volume(self) -> typing.List[typing.Dict]:
resp = self.query('audio', 'getVolumeInformation', {})
return resp['result'][0]
def _set_volume(self, new_volume: str) -> None:
# api 1.2 lets us control if the on-screen volume UI should be displayed; stick to 1.0, accept UI defaults
self.checked_send('audio', 'setAudioVolume', {'target': 'speaker', 'volume': new_volume})
volume = property(_get_volume, _set_volume, None)
def reboot(self) -> None:
self.checked_send('system', 'requestReboot', {})
def list_apps(self) -> typing.List[str]:
apps = self.query('appControl', 'getApplicationList', {})
self.check_error(inspect.stack()[0].function, apps)
return [html.unescape(x['title']) for x in apps['result'][0]]
def launch_app(self, appname: str) -> None:
needle = appname.lower()
res = self.query('appControl', 'getApplicationList', {})
filtered = [app for app in res['result'][0] if html.unescape(app['title']).lower() == needle]
if not filtered:
raise BadInput(f'unknown app {appname!r}')
if len(filtered) > 1:
applist = ', '.join(map(lambda x: shlex.quote(html.unescape(x['title'])), filtered))
raise BadInput(f'too many apps found for {appname!r}: {applist}')
uri = filtered[0]['uri']
self.checked_send('appControl', 'setActiveApp', {'uri': uri})
def list_inputs(self) -> typing.List[typing.Dict]:
inputs = self.query('avContent', 'getCurrentExternalInputsStatus', {}, api_version='1.1')
return inputs['result'][0]
# All methods with names starting 'query_' are directly exposed by the
# Commander as debug commands, specified with a leading colon,
# thus `tv :query_time` works.
def _query_show_json(self, *args, result_index=0, **kwargs) -> None:
res = self.query(*args, **kwargs)
self.check_error(inspect.stack()[1].function, res)
pretty_print_json(res['result'][result_index], stream=self.output)
def query_supported_apis(self) -> None:
self._query_show_json('guide', 'getSupportedApiInfo', {'services': Remote.KNOWN_SERVICES})
def query_time(self) -> None:
self._query_show_json('system', 'getCurrentTime', {}, api_version='1.1')
def query_network_settings(self) -> None:
# We shouldn't need netif per the spec, but we get "Illegal Argument" without it
self._query_show_json('system', 'getNetworkSettings', {'netif': ''})
def query_interface_information(self) -> None:
self._query_show_json('system', 'getInterfaceInformation', {})
def query_sound_settings(self) -> None:
# Array, one for each target
self._query_show_json('audio', 'getSoundSettings', {'target': ''}, api_version='1.1')
def query_speaker_settings(self) -> None:
# Array, one for each target
self._query_show_json('audio', 'getSpeakerSettings', {'target': ''})
def query_playing_content_info(self) -> None:
self._query_show_json('avContent', 'getPlayingContentInfo', {})
def setup_encryption(self, force_fetch=False, tv_only=False, **kwargs) -> None:
if not tv_only:
self.config.setup_thisremote_encryption(**kwargs)
if self.config.tv_keyfile.exists() and not force_fetch:
self._tv_pubkey_b64 = self.config.tv_keyfile.read_text().strip()
else:
kd = self.query('encryption', 'getPublicKey', {})
self._tv_pubkey_b64 = kd['result'][0]['publicKey']
if not self._tv_pubkey_b64:
raise Exit('TV gave us an empty public key')
if not self.config.tv_keyfile.parent.exists():
self.config.tv_keyfile.parent.mkdir(0o700)
self.config.tv_keyfile.write_text(self._tv_pubkey_b64 + '\n')
self._tv_pubkey_bin = base64.b64decode(self._tv_pubkey_b64, validate=True)
@property
def tv_pubkey(self) -> cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey:
if self._tv_pubkey_bin is None:
self.setup_encryption(tv_only=True)
if self._tv_pubkey_bin is None:
raise Error('still no pubkey bin after setting up encryption')
return self.config.load_pubkey_bin(self._tv_pubkey_bin)
def get_text_form(self) -> str:
key = SymKey()
encKey = key.encKey(self.tv_pubkey)
res = self.query('appControl', 'getTextForm', {
'encKey': encKey,
}, api_version='1.1')
self.check_error('get_text_form', res)
encText = res['result'][0]['text']
return key.decrypt(encText)
def set_text_form(self, newText: str) -> None:
key = SymKey()
res = self.query('appControl', 'setTextForm', {
'text': key.encrypt(newText),
'encKey': key.encKey(self.tv_pubkey),
}, api_version='1.1')
self.check_error('set_text_form', res)
if 'result' not in res:
raise Error('missing result (expected empty but present) in set_text_form response')
text = property(get_text_form, set_text_form, None)
def _send_ircc_rawcode(self, rawcode: str) -> requests.Response:
# <https://pro-bravia.sony.net/develop/integrate/ircc-ip/overview/index.html>
url = f'http://{self.addr}/sony/ircc'
soap_headers = {
'Content-Type': 'text/xml; charset=UTF-8',
'SOAPACTION': '"urn:schemas-sony-com:service:IRCC:1#X_SendIRCC"'
}
soap_payload_template = '''<s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<s:Body>
<u:X_SendIRCC xmlns:u="urn:schemas-sony-com:service:IRCC:1">
<IRCCCode>{0}</IRCCCode>
</u:X_SendIRCC>
</s:Body>
</s:Envelope>
'''
self.verbose(f'_send_ircc_rawcode: SOAP IRCCCode {rawcode}', level=4)
r = self.session.post(url,
data=soap_payload_template.format(rawcode),
headers=soap_headers)
r.raise_for_status()
return r
def _setup_ircc(self):
if self._ircc_dict is not None:
return
try:
self._ircc_dict = self.config.load_ircc_codes()
return
except FileNotFoundError:
pass
r = self.query('system', 'getRemoteControllerInfo', {})
self.check_error('getRemoteControllerInfo', r)
# Ideally we'd have a handy case-insensitive dict, so we could store
# preserving the capitalization but not worry for command entry.
#
# result[0] is deprecated; result[1] is list of objs, each with 'name' and 'value' keys
codes = {}
for pair in r['result'][1]:
kp = pair['name']
k = kp.lower()
v = pair['value']
if k in codes:
self.verbose(f'duplicate IRCC code for {kp!r}: had: {codes[k]} also: {v}')
continue
codes[k] = IRCCKeyCode(kp, v)
self.config.save_ircc_codes(codes)
self._ircc_dict = codes
# These _should_ be pre-empted by any actual key definitions of this name
fallback_key_aliases = {
'back': 'return',
'select': 'confirm',
}
def key(self, keyname: str) -> None:
self._setup_ircc()
if self._ircc_dict is None:
raise Error('no _ircc_dict after setup')
# Why Num 0-9,11,12 ? Where's the love for 10?
if len(keyname) == 1 and keyname.isdigit() or keyname in ('Num11', 'Num12',):
keyname = 'Num' + keyname
lk = keyname.lower()
if lk not in self._ircc_dict:
if lk in self.fallback_key_aliases and self.fallback_key_aliases[lk] in self._ircc_dict:
new_lk = self.fallback_key_aliases[lk]
print(f'tv key: alias fixup: {lk!r} -> {new_lk!r}', file=self.errstream)
lk = new_lk
else:
raise BadInput(f'unknown keycode {keyname!r}')
self._send_ircc_rawcode(self._ircc_dict[lk].Rawcode)
def known_keys(self) -> typing.List[str]:
self._setup_ircc()
if self._ircc_dict is None:
raise Error('no _ircc_dict after setup')
keylist = [''] * len(self._ircc_dict)
for i, k in enumerate(self._ircc_dict.keys()):
keylist[i] = self._ircc_dict[k].KeyName
return sorted(keylist)
# There's an introspection API!
def introspect(self, service: str) -> None:
res = self.query(service, 'getMethodTypes', {'_empty': True})
self.check_error(inspect.stack()[0].function, res)
pretty_print_json(res['results'], stream=self.output)
def register_remote(self, *, nickname: str, devicename: str, pin_request_cb) -> None:
# Found the existence of this call and the values to use in random
# Google results, copy/pasted around the Net as samizdat.
for drop in 'X-Auth-PSK', 'Authorization':
if drop in self.session.headers:
del self.session.headers[drop]
our_uuid = str(uuid.uuid4())
register_params = [
{
'clientid': nickname + ':' + our_uuid,
'nickname': f'{nickname} ({_REGISTER_APP_NAME})',
'level': 'private',
},
[
{
'value': 'no',
'function': 'WOL',
},
{
'value': 'yes',
'function': 'pinRegistration',
}
]
]
trigger = self.query('accessControl', 'actRegister', register_params)
# We want to raise an exception for anything _except_ a 401, which is
# reflected in the JSON response too
if 'error' in trigger and trigger['error'][0] == 401:
pass
else:
self.check_error('register_remote', trigger)
try:
challenge = pin_request_cb()
except EOFError:
challenge = ''
challenge = challenge.strip()
if not challenge:
raise Exit('no PIN entered')
authdata = b'Basic ' + base64.b64encode(b':'+challenge.encode('latin1')).strip()
self.next_id -= 1 # retry the _same_ request
self.session.headers['Authorization'] = authdata.decode('ascii')
res = self._send('accessControl', 'actRegister', register_params)
del self.session.headers['Authorization']
pretty_print_json(res.json(), stream=self.output) # FIXME
self.check_error('register_remote', res.json())
self.config.auth_remotename_file.write_text(nickname + '\n')
self.config.auth_uuid_file.write_text(our_uuid + '\n')
json.dump(
requests.utils.dict_from_cookiejar(self.session.cookies),
self.config.auth_cookie_file.open('w'),
indent=1, sort_keys=True)
self.config.persist_current(devicename)
def persist_cookies_maybe(self) -> None:
if not hasattr(self.config, 'cookiejar'):
return
json.dump(
requests.utils.dict_from_cookiejar(self.session.cookies),
self.config.auth_cookie_file.open('w'),
indent=1, sort_keys=True)
class SubRepl(Exception):
"""Indicate that a different REPL needs to be entered."""
# When this is raised, the string value is used to check for a method
# on Commander to invoke. "cli_body_"+str(SubRepl)
pass
class Commander:
"""Command interpreter."""
def __init__(self, remote: Remote, commands: typing.List[str]) -> None:
self.options = remote.options
self.remote = remote
self.commands = commands
self.output = sys.stdout
self.errstream = sys.stderr
self.vol_matcher = re.compile(r'^([+-])(\d+)\Z')
self.repl = False
def _completion_init(self):
self._completion_populate_values()
self._complete_previous = None
self._complete_previous_ctx = ''
self._complete_cache_prev = None
self._completion_context_stack = []
self._prior_completer = None
self._prior_push_ctx = None
def next(self, previous: str) -> str:
try:
return self.commands.pop(0)
except IndexError as e:
raise BadInput(f'parameter needed for command {previous!r}') from e
def volume(self, spec: str, allow_absolute: bool) -> None:
m = self.vol_matcher.match(spec)
if m:
if int(m.group(2)) > 10:
raise BadInput('can only raise/lower by up to ±10')
self.remote.volume = spec
return
if not allow_absolute:
raise VolumeSpecParseError(f'unhandled volume spec {spec!r}')
ivol = int(spec)
if ivol > 100:
raise BadInput('can only set volume to absolute 0..100')
self.remote.volume = str(ivol)
_command_typos = {
'hmdi': 'hdmi',
}
def _completion_populate_values(self) -> None:
# FIXME: this needs to be a proper dispatch system
all_commands = [
'on', 'off', 'power', '?power', 'mute', 'unmute',
'hdmi', 'composite', 'scart',
'vol', 'volume', 'get-vol', 'get-volume', '?vol', '?volume',
'read', 'read-text', 'write', 'write-text', 'send-text',
'app', 'apps', '?apps', 'list-apps',
'list-inputs', '?inputs',
'key', ':keys',
':keypad',
'danger-reboot',
':write', ':default', ':encrypt-setup', ':encrypt-fetch', ':about', ':playing', ':query',
'help', '?help', ':help', # skip '?'
':version',
] + [':'+q for q in dir(self.remote) if q.startswith('query_')]
# If changing this from sorted, check completion logic.
self._top_completions = sorted(all_commands)
key_commands = self.remote.known_keys()
self._key_completions = sorted(key_commands)
app_cache = self.remote.config.app_list_file
if app_cache.exists() and (time.time() - app_cache.stat().st_mtime) < self.remote.config.max_age_app_cache:
app_names = json.load(app_cache.open())
else:
try:
app_names = self.remote.list_apps()
json.dump(app_names, app_cache.open('w'), indent=1, sort_keys=True)
except BadAuthentication as e:
app_names = []
self.remote.verbose('completion setup: failed to get list of app names from the TV', level=0)
self.remote.verbose(str(e), level=0)
self._app_completions = sorted(app_names)
# The MapSubCommands third item in the tuple is to let us walk down so a third level
# could be completed by looking in that, instead of self._rl_contexts.
self._rl_contexts = {
'key': RLContext('key', True, True, {}),
'app': RLContext('app', True, False, {})
}
def one(self, command: str) -> None:
remote = self.remote
if command in self._command_typos:
print(f'tv: typo fixup: {command!r} -> {self._command_typos[command]!r}', file=self.errstream)
command = self._command_typos[command]
if command == 'on':
remote.power = True
return
elif command == 'off':
remote.power = False
return
elif command in ('power', '?power'):
print(remote.power, file=self.output)
return
elif command == 'mute':
remote.mute = True
return
elif command == 'unmute':
remote.mute = False
return
elif command in ('hdmi', 'composite', 'scart'):
try:
port = str(int(self.next(command)))
except BadInput as e:
raise BadInput(f'command {command} needs a port (1..4)') from e
# The actual limit might happen to be 4, but if we want to
# _enforce_ then don't hard-code;
# remote.send('avContent', 'getContentCount', {'source': 'extInput:hdmi'})
# _should_ give us r['result'][0]['count']; I don't want an extra
# RPC call for static data, so instead punt on enforcing this until
# such time as we suck it up and build a capabilities cache in XDG
# storage.
remote.set_external_input(command, port)
return
elif command in ('vol', 'volume'):
self.volume(self.next(command), True)
return
elif command in ('get-vol', 'get-volume', '?vol', '?volume'):
pretty_print_json(remote.volume, stream=self.output)
return
elif command in ('read', 'read-text'):
print(remote.text, file=self.output)
return
elif command in ('write', 'write-text', 'send-text'):
remote.text = self.next(command)
return
elif command == 'app':
remote.launch_app(self.next(command))
return
elif command in ('apps', '?apps', 'list-apps'):
for app in sorted(remote.list_apps()):
print(f' • {app}', file=self.output)
return
elif command in ('list-inputs', '?inputs'):
maxlen_title, maxlen_label = 1, 1
for inp in remote.list_inputs():
tl, ll = len(inp['title']), len(inp['label'])
if tl > maxlen_title:
maxlen_title = tl
if ll > maxlen_label:
maxlen_label = ll
spec = '{title:<%d} {label:<%d} {uri}' % (maxlen_title, maxlen_label)
for inp in remote.list_inputs():
print(spec.format(**inp), file=self.output)
return
elif command == 'key':
try:
keycode = self.next('keycode')
except BadInput as e:
if self.repl:
raise SubRepl(command) from e
else:
raise
#
pause = False
if keycode != '[':
remote.key(keycode)
return
while keycode != ']':
try:
keycode = self.commands.pop(0)
if keycode == ']':
break
except IndexError:
return
if pause:
time.sleep(0.25)