-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathUtils.cpp
395 lines (373 loc) · 17.3 KB
/
Utils.cpp
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
#include <utils.h>
#include <dirent.h>
#include <unistd.h>
#include <minizip/unzip.h>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <AmiigoSettings.h>
#include <AmiigoUI.h>
#include <Networking.h>
#include <emuiibo.hpp>
#include <nlohmann/json.hpp>
bool checkIfFileExists(const char* path) {
return !access(path, F_OK);
}
std::vector<AmiiboEntry> scanForAmiibo(const char* path) {
// Open path
DIR* folder = opendir(path);
std::vector<AmiiboEntry> amiibos;
if (folder) {
// List folder entries
dirent* entry;
while (entry = readdir(folder)) {
AmiiboEntry amiibo;
amiibo.name = entry->d_name;
char flagPath[512] = "";
strcat(flagPath, path);
strcat(flagPath, "/");
strcat(flagPath, entry->d_name);
amiibo.path = flagPath;
strcat(flagPath, "/amiibo.flag");
amiibo.isCategory = !checkIfFileExists(flagPath);
amiibos.push_back(amiibo);
}
closedir(folder);
// Sort alphabetically
std::sort(amiibos.begin(), amiibos.end(), [](AmiiboEntry amiiboA, AmiiboEntry amiiboB)->bool{
int maxLength = (amiiboA.name.length() < amiiboB.name.length()) ? amiiboA.name.length() : amiiboB.name.length();
int iterations = 0;
while (iterations < maxLength) {
if (std::tolower(amiiboA.name[iterations]) != std::tolower(amiiboB.name[iterations]))
return std::tolower(amiiboA.name[iterations]) < std::tolower(amiiboB.name[iterations]);
else
iterations++;
}
return false;
});
// Prepend favorites if path is sdmc:/emuiibo/amiibo
if (!strcmp(path, "sdmc:/emuiibo/amiibo")) {
amiibos.insert(amiibos.begin(), {"¤ Favorites", true, "Favorites"});
} else {
// If not in "sdmc:/emuiibo/amiibo" then add back entry
std::string upDir = path;
upDir = upDir.substr(0, upDir.find_last_of("/"));
amiibos.insert(amiibos.begin(), {"¤ Back", true, upDir});
}
return amiibos;
}
// Check if path is supposed to be favorites
if (!strcmp(path, "Favorites")) {
// Add in the back button
amiibos.insert(amiibos.begin(), {"¤ Back", true, "sdmc:/emuiibo/amiibo"});
// Read each line from the favorites file
std::string tempLine;
std::ifstream fileStream("sdmc:/emuiibo/overlay/favorites.txt");
while (getline(fileStream, tempLine)) {
// Check if Amiibo or dir
char flagPath[512] = "";
strcat(flagPath, tempLine.c_str());
strcat(flagPath, "/amiibo.flag");
// Add to amiibo list
amiibos.push_back({tempLine.substr(tempLine.find_last_of('/')+1, tempLine.length()+1 - tempLine.find_last_of('/')), !checkIfFileExists(flagPath), tempLine});
}
fileStream.close();
return amiibos;
}
}
std::vector<std::string> getListOfSeries() {
std::vector<std::string> series;
if (checkIfFileExists("sdmc:/config/amiigo/API.json")) {
std::string APIData;
std::string tempLine;
std::ifstream fileStream("sdmc:/config/amiigo/API.json");
// Read the file from disk
while (getline(fileStream, tempLine)) {
APIData += tempLine;
}
fileStream.close();
nlohmann::json APIJson = nlohmann::json::parse(APIData, nullptr, false);
// Check API cache is valid
if (APIJson.is_discarded()) {
printf("API cache is corrupt\n");
remove("sdmc:/config/amiigo/API.json");
return {"Error, API cache corrupt!", "Try updating cache in settings!"};
}
// Loop over every entry under the Amiibo object
for (int i = 0; i < APIJson["amiibo"].size(); i++) {
bool isKnown = false;
std::string seriesName = APIJson["amiibo"][i]["amiiboSeries"].get<std::string>();
// Check if series is in list
for (size_t i = 0; i < series.size(); i++) {
if (series[i] == seriesName) isKnown = true;
}
// If not add it to the list
if (!isKnown) series.push_back(seriesName);
}
} else {
return {"Error, no API cache!"};
}
// Sort alphabetically
std::sort(series.begin(), series.end(), [](std::string seriesA, std::string seriesB)->bool{
int maxLength = (seriesA.length() < seriesB.length()) ? seriesA.length() : seriesB.length();
int iterations = 0;
while (iterations < maxLength) {
if (std::tolower(seriesA[iterations]) != std::tolower(seriesB[iterations]))
return std::tolower(seriesA[iterations]) < std::tolower(seriesB[iterations]);
else
iterations++;
}
return false;
});
return series;
}
// Written on 27/01/2021 for Kronos, can't remember how it works but does magic bit shifting
unsigned short shiftAndDec(std::string input) {
unsigned short value = std::stoi(input, nullptr, 16);
unsigned short a = value & 0xFF00;
a = 0x00FF & (a >> 8);
value = value << 8;
value = 0xffff & value;
value = value | a;
return value;
}
std::vector<AmiiboCreatorData> getAmiibosFromSeries(std::string series) {
std::vector<AmiiboCreatorData> amiibos;
if (checkIfFileExists("sdmc:/config/amiigo/API.json")) {
std::string APIData;
std::string tempLine;
std::ifstream fileStream("sdmc:/config/amiigo/API.json");
// Read the file from disk
while (getline(fileStream, tempLine)) {
APIData += tempLine;
}
nlohmann::json APIJson = nlohmann::json::parse(APIData);
fileStream.close();
// Loop over every entry under the AMiibo object
for (int i = 0; i < APIJson["amiibo"].size(); i++) {
// If series matches add it to the list
if (APIJson["amiibo"][i]["amiiboSeries"].get<std::string>() == series) {
// Process the API data the same way Emutool does
// https://github.com/XorTroll/emuiibo/blob/90cbc54a95c0aa4a9ceb6dd55b633de206763094/emutool/emutool/AmiiboUtils.cs#L144
AmiiboCreatorData newAmiibo;
newAmiibo.name = APIJson["amiibo"][i]["name"].get<std::string>();
std::string fullID = APIJson["amiibo"][i]["head"].get<std::string>() + APIJson["amiibo"][i]["tail"].get<std::string>();
// Get strings needed to derive IDs
// Var names taken from emutool
std::string character_game_id_str = fullID.substr(0, 4);
std::string character_variant_str = fullID.substr(4, 2);
std::string figure_type_str = fullID.substr(6, 2);
std::string model_no_str = fullID.substr(8, 4);
std::string series_str = fullID.substr(12, 2);
// Swap endianess for game ID
newAmiibo.game_character_id = shiftAndDec(character_game_id_str);
// Get character variant
newAmiibo.character_variant = static_cast<char>(stoi(character_variant_str, nullptr, 16));
// Get figure type
newAmiibo.figure_type = static_cast<char>(stoi(figure_type_str, nullptr, 16));
// Get model number
newAmiibo.model_number = (unsigned short)stoi(model_no_str, nullptr, 16);
// Get series ID
newAmiibo.series = static_cast<char>(stoi(series_str, nullptr, 16));
// Get the Game series name (only used for categorization)
newAmiibo.gameName = APIJson["amiibo"][i]["gameSeries"].get<std::string>();
// Get the Amiibo series name (only used for categorization)
newAmiibo.amiiboSeries = APIJson["amiibo"][i]["amiiboSeries"].get<std::string>();
// Add new amiibo to list
amiibos.push_back(newAmiibo);
}
}
} else {
return {{"Error, API cache vanished?", 0, 0, 0, 0, 0}};
}
// Sort alphabetically
std::sort(amiibos.begin(), amiibos.end(), [](AmiiboCreatorData amiiboA, AmiiboCreatorData amiiboB)->bool{
int maxLength = (amiiboA.name.length() < amiiboB.name.length()) ? amiiboA.name.length() : amiiboB.name.length();
int iterations = 0;
while (iterations < maxLength) {
if (std::tolower(amiiboA.name[iterations]) != std::tolower(amiiboB.name[iterations]))
return std::tolower(amiiboA.name[iterations]) < std::tolower(amiiboB.name[iterations]);
else
iterations++;
}
return false;
});
return amiibos;
}
void createVirtualAmiibo(AmiiboCreatorData amiibo) {
std::string pathBase = "sdmc:/emuiibo/amiibo/";
switch (Amiigo::Settings::categoryMode) {
case Amiigo::Settings::saveByGameName:
pathBase += amiibo.gameName + "/";
mkdir(pathBase.c_str(), 0);
break;
case Amiigo::Settings::saveByAmiiboSeries:
pathBase += amiibo.amiiboSeries + "/";
mkdir(pathBase.c_str(), 0);
break;
case Amiigo::Settings::saveByCurrentFolder:
if (Amiigo::UI::selectorPath != "Favorites") pathBase = Amiigo::UI::selectorPath + "/";
break;;
}
pathBase += amiibo.name;
mkdir(pathBase.c_str(), 0);
std::ofstream fileStream(pathBase + "/amiibo.flag");
fileStream.close();
fileStream.open(pathBase + "/amiibo.json");
nlohmann::json amiiboJson;
amiiboJson["name"] = amiibo.name;
amiiboJson["write_counter"] = 0;
amiiboJson["version"] = 0;
amiiboJson["mii_charinfo_file"] = "mii-charinfo.bin";
amiiboJson["first_write_date"]["y"] = 2019;
amiiboJson["first_write_date"]["m"] = 1;
amiiboJson["first_write_date"]["d"] = 1;
amiiboJson["last_write_date"]["y"] = 2019;
amiiboJson["last_write_date"]["m"] = 1;
amiiboJson["last_write_date"]["d"] = 1;
amiiboJson["id"]["game_character_id"] = amiibo.game_character_id;
amiiboJson["id"]["character_variant"] = amiibo.character_variant;
amiiboJson["id"]["figure_type"] = amiibo.figure_type;
amiiboJson["id"]["series"] = amiibo.series;
amiiboJson["id"]["model_number"] = amiibo.model_number;
if (!Amiigo::Settings::useRandomisedUUID)
amiiboJson["uuid"] = {rand() % 256, rand() % 256, rand() % 256, rand() % 256, rand() % 256, rand() % 256, rand() % 256, 0, 0, 0};
else
amiiboJson["use_random_uuid"] = true;
fileStream << std::setw(4) << amiiboJson << std::endl;
fileStream.close();
}
void firstTimeSetup() {
// Cache API data
while (!checkIfFileExists("sdmc:/config/amiigo/API.json")) {
if (checkIfFileExists("sdmc:/config/amiigo/API.tmp")) remove("sdmc:/config/amiigo/API.tmp");
// After 5 seconds of no connection unpack stored cache
if (Arriba::time > 5 && !hasNetworkConnection()) {
unzFile zipFile = unzOpen("romfs:/API.cache");
unz_file_info fileInfo;
unzOpenCurrentFile(zipFile);
unzGetCurrentFileInfo(zipFile, &fileInfo, nullptr, 0, nullptr, 0, nullptr, 0);
void* buffer = malloc(398163);
FILE* outFile = fopen("sdmc:/config/amiigo/API.tmp", "wb");
for (int i = unzReadCurrentFile(zipFile, buffer, 398163); i > 0; i = unzReadCurrentFile(zipFile, buffer, 398163)) fwrite(buffer, 1, i, outFile);
fclose(outFile);
free(buffer);
} else if (!retrieveToFile("https://www.amiiboapi.com/api/amiibo", "sdmc:/config/amiigo/API.tmp")) {continue;}
rename("sdmc:/config/amiigo/API.tmp", "sdmc:/config/amiigo/API.json");
// Check file is valid JSON
std::string apiLine = "";
std::string tempLine = "";
std::ifstream apiStream("sdmc:/config/amiigo/API.json");
while (getline(apiStream, tempLine)) apiLine += tempLine;
apiStream.close();
if (!nlohmann::json::accept(apiLine)) remove("sdmc:/config/amiigo/API.json");
}
// Install emuiibo
if (!checkIfFileExists("sdmc:/atmosphere/contents/0100000000000352/exefs.nsp")) {
bool hasValidEmuiiboJSON = false;
nlohmann::json emuiiboInfo;
while (!hasValidEmuiiboJSON) {
printf("Downloading Emuiibo zip\n");
while (!hasNetworkConnection()) continue;
if (checkIfFileExists("sdmc:/config/amiigo/emuiibo.tmp")) remove("sdmc:/config/amiigo/emuiibo.tmp");
// We should probably do this in a more robust way
std::string emuiiboReleaseInfo;
while (!retrieveToString("https://api.github.com/repos/XorTroll/Emuiibo/releases", "application/json", &emuiiboReleaseInfo)) continue;
emuiiboInfo = nlohmann::json::parse(emuiiboReleaseInfo, nullptr, false);
hasValidEmuiiboJSON = !emuiiboInfo.is_discarded();
}
printf("hasValidEmuiiboJSON: %d\n", hasValidEmuiiboJSON);
while (!retrieveToFile(emuiiboInfo[0]["assets"][0]["browser_download_url"].get<std::string>().c_str(), "sdmc:/config/amiigo/emuiibo.tmp")) continue;
printf("Unzipping\n");
// Extract the files from the emuiibo zip
mkdir("sdmc:/atmosphere/contents/", 0);
mkdir("sdmc:/atmosphere/contents/0100000000000352/", 0);
mkdir("sdmc:/atmosphere/contents/0100000000000352/flags/", 0);
std::ofstream fileStream("sdmc:/atmosphere/contents/0100000000000352/flags/boot2.flag");
fileStream.close();
unzFile zipFile = unzOpen("sdmc:/config/amiigo/emuiibo.tmp");
unz_global_info zipInfo;
unzGetGlobalInfo(zipFile, &zipInfo);
for (int i = 0; i < zipInfo.number_entry; i++) {
char fileName[256];
unz_file_info fileInfo;
unzOpenCurrentFile(zipFile);
unzGetCurrentFileInfo(zipFile, &fileInfo, fileName, sizeof(fileName), nullptr, 0, nullptr, 0);
printf("Zip index:%d is %s\n", i, fileName);
if (strcmp("SdOut/atmosphere/contents/0100000000000352/exefs.nsp", fileName) == 0) {
void* buffer = malloc(500000);
FILE* outfile = fopen("sdmc:/atmosphere/contents/0100000000000352/exefs.nsp", "wb");
for (int j = unzReadCurrentFile(zipFile, buffer, 500000); j > 0; j = unzReadCurrentFile(zipFile, buffer, 500000)) {
fwrite(buffer, 1, j, outfile);
}
fclose(outfile);
free(buffer);
break;
}
unzCloseCurrentFile(zipFile);
unzGoToNextFile(zipFile);
}
printf("Unzip done\n");
unzClose(zipFile);
remove("sdmc:/config/amiigo/emuiibo.tmp");
// Launch the sysmodule
pmshellInitialize();
NcmProgramLocation emuiiboLoc = {0x0100000000000352, NcmStorageId_None};
pmshellLaunchProgram(0, &emuiiboLoc, nullptr);
pmshellExit();
}
// If flag exists download update
if (checkIfFileExists("sdmc:/config/amiigo/update.flag")) {
while (!hasNetworkConnection()) continue;
bool DLSuccess = retrieveToFile(Amiigo::Settings::updateURL, "sdmc:/switch/Failed_Amiigo_Update.nro");
if (checkIfFileExists("sdmc:/switch/Failed_Amiigo_Update.nro") && DLSuccess) {
romfsExit();
if (checkIfFileExists(Amiigo::Settings::amiigoPath)) remove(Amiigo::Settings::amiigoPath);
rename("sdmc:/switch/Failed_Amiigo_Update.nro", Amiigo::Settings::amiigoPath);
}
if (Amiigo::Settings::amiigoPath) envSetNextLoad(Amiigo::Settings::amiigoPath, Amiigo::Settings::amiigoPath);
Amiigo::UI::isRunning = 0;
remove("sdmc:/config/amiigo/update.flag");
}
}
bool checkForUpdates() {
// Return false if no internet
printf("Checking for updates\n");
if (!hasNetworkConnection()) {
printf("No connection\b");
return false;
}
printf("Getting network time\n");
timeInitialize();
long unsigned int time = Amiigo::Settings::updateTime;
timeGetCurrentTime(TimeType_NetworkSystemClock, &time);
timeExit();
// Only check for updates once every 24 hours, unless an update is found.
if (Amiigo::Settings::updateTime > time) {
printf("Last check less than 24 hours ago\n");
return false;
}
printf("Getting API data\n");
std::string amiigoReleaseInfo;
bool releaseInfoSuccess = retrieveToString("https://api.github.com/repos/CompSciOrBust/Amiigo/releases", "application/json", &amiigoReleaseInfo);
// User is probably being rate limited
if (amiigoReleaseInfo.size() < 300 || !releaseInfoSuccess) {
printf("%s\n", amiigoReleaseInfo.c_str());
printf("Error, getting Amiigo update info failed\n");
return false;
}
nlohmann::json amiigoInfoParsed = nlohmann::json::parse(amiigoReleaseInfo, nullptr, false);
// If data is corrupt do nothing
if (amiigoInfoParsed.is_discarded()) {
printf("%s\n", amiigoReleaseInfo.c_str());
printf("Error, Amiigo update info corrupt\n");
return false;
}
// If on the latest update wait another 24 hours before checking again
if (amiigoInfoParsed[0]["tag_name"].get<std::string>() == VERSION) {
Amiigo::Settings::updateTime = time + 86400;
Amiigo::Settings::saveSettings();
return false;
} else {Amiigo::Settings::updateURL = amiigoInfoParsed[0]["assets"][0]["browser_download_url"].get<std::string>().c_str();}
return true;
}