-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathharc.py
307 lines (257 loc) · 10.4 KB
/
harc.py
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
import argparse
import sys
import json
import shutil
from datetime import datetime
def main():
if sys.version_info.major < 3:
sys.exit("Python 3 required")
arg_parser = create_arg_parser()
parsed_args = arg_parser.parse_args(sys.argv[1:])
path = parsed_args.configDirectory
targetEntityId = parsed_args.targetEntityId
# files needed for this script within Home Assistant folder
files = [
"core.config_entries",
"core.device_registry",
"core.entity_registry",
"core.restore_state",
]
configList = read_file(files[0], path)
deviceList = read_file(files[1], path)
entityList = read_file(files[2], path)
restoreList = read_file(files[3], path)
# print total number of keys found in each file
get_totals(files, configList, deviceList, entityList, restoreList)
# show items for selected args
if parsed_args.show_entries:
print("Config Entries")
c = 0
for key in configList["data"]["entries"]:
print(
"{:03d}".format(c),
":",
key["title"],
"-",
key["domain"],
"-",
key["entry_id"],
)
c += 1
if parsed_args.show_devices:
print("Devices:")
d = 0
for key in deviceList["data"]["devices"]:
print("{:03d}".format(d), ":", key["id"])
d += 1
if parsed_args.show_entities:
print("Entities:")
e = 0
for key in entityList["data"]["entities"]:
print("{:03d}".format(e), ":", key["entity_id"])
e += 1
print("Looking for", targetEntityId)
# check if targetEntity exists
if targetEntityId in [key["entity_id"] for key in entityList["data"]["entities"]]:
# start - scan entity list, find info on entity we need, remove it
entityRemoved = False
deviceRemoved = False
restoreStateRemove = False
entityLastSeen = "N/A"
e = 0
for key in entityList["data"]["entities"]:
if key["entity_id"] == targetEntityId:
if key["disabled_by"] is None:
status = "Enabled"
else:
status = "Disabled"
entityId = key["unique_id"]
deviceId = key["device_id"]
configId = key["config_entry_id"]
for item in restoreList["data"]:
if item["state"]["entity_id"] == key["entity_id"]:
entityLastSeen = item["last_seen"]
print(
"entity ID:",
key["entity_id"],
"- Status:",
status,
"- Last Seen:",
entityLastSeen,
)
print("device ID:", key["device_id"])
print("config Entry ID:", key["config_entry_id"])
# check for other entities share the same deviceList and configList IDs
print("\nOther devices related to this entity's device")
numRelatedDevices = 0
for key in entityList["data"]["entities"]:
if key["device_id"] == deviceId:
print(key["entity_id"])
numRelatedDevices += 1
print("\nOther entities related to this entity's Config Entry")
numRelatedConfig = 0
deviceCount = 0
for key in entityList["data"]["entities"]:
if key["config_entry_id"] == configId:
print(key["entity_id"])
numRelatedConfig += 1
deviceCount += 1
# Confirm and remove from entityList, otherwise skip
# at this point, nothing is written to the file, that step is next
removeQuestion = "\nRemove entity " + targetEntityId + " ?"
if query_yes_no(removeQuestion, "no") is True:
# these will be used to determine if file commit is needed
if status == "Disabled":
print("Removing entity", targetEntityId)
if entityList["data"]["entities"].pop(e):
entityRemoved = True
# remove from deviceList
d = 0
for key in deviceList["data"]["devices"]:
if (
key["id"] == deviceId
and key["identifiers"][0][1] == entityId
):
print("Removing device", deviceId)
if deviceList["data"]["devices"].pop(d):
deviceRemoved = True
d += 1
# remove from restoreList
r = 0
for item in restoreList["data"]:
if item["state"]["entity_id"] == targetEntityId:
print("Removing restore state")
if restoreList["data"].pop(r):
restoreStateRemove = True
r += 1
else:
print(
"Entity is not disabled. "
"Entity must be disabled before it can be removed"
)
e += 1
# end - scan entity list, find info on entity we need, remove it
# print total number of keys found in each file after changes
get_totals(files, configList, deviceList, entityList, restoreList)
# if changes were made, ask to comomit to file
if entityRemoved is True:
commitQuestion = "\nCommit Changes to file?"
if query_yes_no(commitQuestion, "no") is True:
backupQUestion = "\nBackup Files before Commit?"
if query_yes_no(backupQUestion, "yes") is True:
for file in files:
backup_file(file, path)
write_file(entityList, files[2], path)
if numRelatedConfig == 1:
write_file(configList, files[0], path)
if deviceRemoved is True:
write_file(deviceList, files[1], path)
if restoreStateRemove is True:
write_file(restoreList, files[3], path)
else:
print("Entity", targetEntityId, "not found")
# check files and assign files
def read_file(file, path, coreStorage="/.storage/"):
"""Open files and import data."""
fullPath = path + coreStorage + file
try:
configFile = open(fullPath, "r+")
print("Found", configFile.name)
except FileNotFoundError as e:
sys.exit("config file not found", e.filename)
except PermissionError as e:
# sys.exit("Permission denied: " + e.filename)
# try opoening in read only mode if not able to open for write
# this will not allow any changes, but can be used to browse entries, etc
try:
configFile = open(fullPath, "r")
print("READ ONLY - Found", e.filename)
loadJson = json.load(configFile)
configFile.close()
return loadJson
except PermissionError as e:
sys.exit("Permission denied: " + e.filename)
else:
loadJson = json.load(configFile)
configFile.close()
return loadJson
def backup_file(file, path, coreStorage="/.storage/"):
"""Create backup of files before making changes."""
timeStamp = datetime.now().strftime("%Y%m%d_%H%M%S")
originalFile = path + coreStorage + file
backupFile = path + coreStorage + file + "_" + timeStamp + ".bak"
if shutil.copy(originalFile, backupFile):
return True
else:
return False
def write_file(data, file, path, coreStorage="/.storage/"):
"""Write to file once ready to commit changes."""
fullPath = path + coreStorage + file
try:
with open(fullPath, "w") as filetowrite:
json.dump(data, filetowrite, indent=4)
except PermissionError as e:
sys.exit("Permission denied: " + e.filename)
def get_totals(files, *kwargs):
"""Calculate total entries for each file."""
configList = kwargs[0]
deviceList = kwargs[1]
entityList = kwargs[2]
restoreList = kwargs[3]
print()
print(files[0], ":", len(configList["data"]["entries"]))
print(files[1], ":", len(deviceList["data"]["devices"]))
print(files[2], ":", len(entityList["data"]["entities"]))
print(files[3], ":", len(restoreList["data"]))
print()
def create_arg_parser():
"""Create parser for command line arguments."""
parser = argparse.ArgumentParser(
description="Python Script to remove unwanted entities",
prog="Home Assistant Registry Cleaner",
)
parser.add_argument("configDirectory", help="Home Assistant config directory")
parser.add_argument("targetEntityId", help="Name of the entityList ID to remove")
parser.add_argument(
"--show-devices",
action="store_true",
help="List devices from core.device_registry",
)
parser.add_argument(
"--show-entities",
action="store_true",
help="List entities from core.entity_registry",
)
parser.add_argument(
"--show-entries",
action="store_true",
help="List config entries from core.config_entries",
)
return parser
def query_yes_no(question, default=None):
"""
Ask a yes/no question to confirm data changes.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
The return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = "[Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("Invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == "":
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Respond with yes or no")
if __name__ == "__main__":
main()