This repository was archived by the owner on Jul 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathretroarch.py
More file actions
174 lines (155 loc) · 6.12 KB
/
Copy pathretroarch.py
File metadata and controls
174 lines (155 loc) · 6.12 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
import json
import os
import pathlib
from time import sleep
import time
import hashlib
import database
import zipfile
import pathlib
from os import listdir
from os.path import isfile, join
import logger
import shutil
import event_manager
import threading
import config
SETTINGS = config.get_config()
map_file = "retroarch.json"
cores = {}
retroatch_path = SETTINGS["retroarch"]["install_path"]
cores_folder = os.path.join(retroatch_path,"cores")
recents = os.path.join(retroatch_path,"content_history.lpl")
last_details = {}
class RetroarchGameChange():
def __init__(self, system, core, rom,tokens):
self.publisher = "Retroarch"
self.event = "RetroarchGameChange"
self.system = system
self.core = core
self.rom = rom
self.tokens = tokens
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
def get_core_list():
cores = {}
onlyfiles = [pathlib.Path(f).stem.replace("_libretro","") for f in listdir(cores_folder) if isfile(join(cores_folder, f))]
for item in onlyfiles:
core = {}
cores[item] = core
return cores
def read_file_map():
global map_file
if os.path.exists(map_file):
with open(map_file) as map_json:
maps = json.load(map_json)
return maps
else:
return {}
def merge_maps():
if os.path.exists(map_file):
logger.info("Backing up {} ...".format(map_file))
shutil.copyfile(map_file, '{}.bak'.format(map_file))
else:
logger.info("No map file exists, only using map from system.")
system_map = get_core_list()
file_map = read_file_map()
merged_map = system_map
for map in file_map:
merged_map[map] = file_map[map]
added_maps = []
for map in system_map:
if map not in file_map:
added_maps.append(map)
if len(added_maps) > 0:
logger.info("The following cores have been added to the retroarch.json: {}".format(added_maps))
with open(map_file, "w") as write_file:
json.dump(merged_map, write_file, indent=4)
def load_map_to_memory():
global map_file
global cores
if os.path.exists(map_file):
with open(map_file) as map_json:
maps = json.load(map_json)
cores = maps
def hash_zip(file):
archive = zipfile.ZipFile(file)
blocksize = 1024**2 #1M chunks
for fname in archive.namelist():
entry = archive.open(fname)
sha1 = hashlib.sha1()
while True:
block = entry.read(blocksize)
if not block:
break
sha1.update(block)
return sha1.hexdigest().upper()
def hash_file(file):
buf_size = 65536
sha1 = hashlib.sha1()
with open(file, 'rb') as f:
while True:
data = f.read(buf_size)
if not data:
break
sha1.update(data)
return format(sha1.hexdigest().upper())
def initialize():
logger.info("Initializing Retroarch publisher ...")
merge_maps()
load_map_to_memory()
def publish():
global last_details
if os.path.exists(recents):
access = time.time() - os.path.getmtime(recents)
if access < int( SETTINGS["retroarch"]["refresh_rate"]):
with open(recents) as recents_json:
details = json.load(recents_json)
if "items" in details:
if len(details["items"]) > 0:
if details != last_details:
file = details["items"][0]["path"]
core = pathlib.Path(details["items"][0]["core_path"]).stem.replace("_libretro","")
game = pathlib.Path(file).stem
system = core
try:
if "system" in cores[core]:
system = cores[core]["system"]
except Exception as e:
pass
hash = ""
if zipfile.is_zipfile(file):
hash = hash_zip(file)
else:
hash = hash_file(file)
rom = {}
if hash != "":
rom = database.get_rom_by_hash(hash)
if len(rom) != 0:
logger.info(f"Hash: {hash} matched in database")
else:
logger.info(f"Hash: {hash} not matched in database")
if len(rom) == 0:
rom = database.get_rom_by_name(game,system)
if "rom_extensionless_file_name" in rom:
logger.info(f"Rom name match in database for Game: {game}, System: {system}")
system = rom["system"]
else:
logger.info(f"Game {game} not found in database, defaulting to game")
rom = vars(database.Rom())
rom["release_name"] = game
rom["rom_extensionless_file_name"] = game
rom["system"] = system
try:
tokens = cores[core]
tokens["core"] = core
tokens.update(rom)
event = RetroarchGameChange(system,core,rom,tokens)
threading.Thread(target=event_manager.manage_event, args=[event]).start()
except Exception as e:
logger.error(f"Unabled to publish MisterGameChange event")
last_details = details
event_manager.publishers["Retroarch"] = {}
event_manager.publishers["Retroarch"]["initialize"] = lambda:initialize()
event_manager.publishers["Retroarch"]["publish"] = lambda:publish()