-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.cpp
443 lines (396 loc) · 17.5 KB
/
plugin.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
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
#include <stdio.h>
#include <Shlobj.h>
#include <cpr\cpr.h>
#include <SKSE_HTTP_TypedDictionary.h>
#include <nlohmann\json.hpp>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/msvc_sink.h>
using json = nlohmann::json;
using namespace SKSE_HTTP_TypedDictionary;
void InitializeLogging() {
WCHAR userpath[MAX_PATH];
SHGetFolderPathW(NULL, CSIDL_MYDOCUMENTS, NULL, 0, userpath);
// Force proper path, otherwise the files end up in 'Skyrim.INI/SKSE'
std::filesystem::path path(userpath);
path /= "Skyrim Special Edition/SKSE/SKSE_HTTP.log";
auto sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(path.string(), true);
std::shared_ptr<spdlog::logger> log = std::make_shared<spdlog::logger>("global log"s, std::move(sink));
//log = std::make_shared<spdlog::logger>("Global", std::make_shared<spdlog::sinks::basic_file_sink_mt>(path->string(), true));
log->set_level(spdlog::level::trace);
log->flush_on(spdlog::level::trace);
spdlog::set_default_logger(std::move(log));
spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%n] [%l] [%t] [%s:%#] %v");
//spdlog::set_pattern("[%T.%e] [%=5t] [%L] %v"s);
}
void toLowerCase(std::string* input) {
std::transform(input->begin(), input->end(), input->begin(), [](unsigned char c) { return std::tolower(c); });
};
bool test_utf8(std::string input) {
try {
json test = {"test", input};
test.dump();
return true;
} catch (...) {
return false;
}
};
json getJsonFromHandle(int typedDictionaryHandle)
{
std::shared_ptr<TypedDictionary> dict = SKSE_HTTP_TypedDictionary::dicNestedDictionariesValues[typedDictionaryHandle];
json jsonToUse;
if (dict) {
for (auto& [key, value] : dict->_dicElements) {
std::string valueType = value->getTypeName();
if (valueType == "string")
jsonToUse[key] = dict->getString(key);
else if (valueType == "int")
jsonToUse[key] = dict->getInt(key);
else if (valueType == "float")
jsonToUse[key] = dict->getFloat(key);
else if (valueType == "bool")
jsonToUse[key] = dict->getBool(key);
else if (valueType == "stringArray")
jsonToUse[key] = dict->getStringArray(key);
else if (valueType == "intArray")
jsonToUse[key] = dict->getIntArray(key);
else if (valueType == "floatArray")
jsonToUse[key] = dict->getFloatArray(key);
else if (valueType == "boolArray")
jsonToUse[key] = dict->getBoolArray(key);
else if (valueType == "NestedDictionary") {
int handle = dict->getNestedDictionary(key);
jsonToUse[key] = getJsonFromHandle(handle);
} else if (valueType == "NestedDictionaryArray") {
std::vector<int> handles = dict->getArrayOfNestedDictionaries(key);
auto jsonObjects = json::array();
size_t sizeOfHandles = handles.size();
for (auto i = 0; i < sizeOfHandles; ++i) {
jsonObjects.push_back(getJsonFromHandle(handles[i]));
}
jsonToUse[key] = jsonObjects;
}
}
}
return jsonToUse;
};
int generateDictionaryFromJson(json jsonToUse)
{
int handle = SKSE_HTTP_TypedDictionary::createDictionary();
for (auto& el : jsonToUse.items())
{
std::string key = el.key();
toLowerCase(&key);
if (el.value().is_string())
SKSE_HTTP_TypedDictionary::setString(handle, key, el.value());
else if (el.value().is_number_integer())
SKSE_HTTP_TypedDictionary::setInt(handle, key, el.value());
else if (el.value().is_number_float())
SKSE_HTTP_TypedDictionary::setFloat(handle, key, el.value());
else if (el.value().is_boolean())
SKSE_HTTP_TypedDictionary::setBool(handle, key, el.value());
else if (el.value().is_object())
{
json nested = el.value();
int subHandle = generateDictionaryFromJson(nested);
SKSE_HTTP_TypedDictionary::setNestedDictionary(handle, key, subHandle);
}
else if (el.value().is_array())
{
if(std::all_of(el.value().begin(),el.value().end(), [](const json& elSub){ return elSub.is_string(); }))
SKSE_HTTP_TypedDictionary::setStringArray(handle, key, el.value());
else if(std::all_of(el.value().begin(),el.value().end(), [](const json& elSub){ return elSub.is_number_integer(); }))
SKSE_HTTP_TypedDictionary::setIntArray(handle, key, el.value());
else if(std::all_of(el.value().begin(),el.value().end(), [](const json& elSub){ return elSub.is_number_float(); }))
SKSE_HTTP_TypedDictionary::setFloatArray(handle, key, el.value());
else if(std::all_of(el.value().begin(),el.value().end(), [](const json& elSub){ return elSub.is_boolean(); }))
SKSE_HTTP_TypedDictionary::setBoolArray(handle, key, el.value());
else if(std::all_of(el.value().begin(),el.value().end(), [](const json& elSub){ return elSub.is_object(); }))
{
std::vector<int> handles;
for (auto& elSub : el.value().items())
{
json nested = elSub.value();
int subHandle = generateDictionaryFromJson(nested);
handles.push_back(subHandle);
}
SKSE_HTTP_TypedDictionary::setArrayOfNestedDictionaries(handle, key, handles);
}
}
}
return handle;
};
int sendHttpRequestResultToSkyrimEvent(std::string completeReply, RE::BSFixedString papyrusFunctionToCall) {
try {
json reply = json::parse(completeReply);
int newHandle = generateDictionaryFromJson(reply);
auto* vm = RE::BSScript::Internal::VirtualMachine::GetSingleton();
auto eventArgs = RE::MakeFunctionArguments((int)newHandle);
RE::BSTSmartPointer<RE::BSScript::IStackCallbackFunctor> callback;
RE::BSFixedString Skse_Http = "SKSE_HTTP";
vm->DispatchStaticCall(Skse_Http, papyrusFunctionToCall, eventArgs, callback);
return 0;
} catch (...) {
return 1;
}
};
void postCallbackMethod(cpr::Response response)
{
if (response.status_code == 200)
{
RE::BSFixedString onHttpReplyReceived = "raiseOnHttpReplyReceived";
sendHttpRequestResultToSkyrimEvent(response.text, onHttpReplyReceived);
}
else
{
json jsonToUse;
jsonToUse["SKSE_HTTP_error"] = response.error.message;
RE::BSFixedString onHttpErrorReceived = "raiseOnHttpErrorReceived";
sendHttpRequestResultToSkyrimEvent(jsonToUse.dump(), onHttpErrorReceived);
}
}
void sendLocalhostHttpRequest(RE::StaticFunctionTag*, int typedDictionaryHandle, int port, std::string route, int timeout)
{
try {
toLowerCase(&route);
auto start_jsonfromhandle = std::chrono::steady_clock::now();
json newJson = getJsonFromHandle(typedDictionaryHandle);
auto start_send = std::chrono::steady_clock::now();
std::string textToSend = newJson.dump();
std::string url = "http://localhost:" + std::to_string(port) + "/" + route;
cpr::PostCallback(postCallbackMethod, cpr::Url{url}, cpr::ConnectTimeout{timeout},
cpr::Authentication{"user", "pass", cpr::AuthMode::BASIC},
cpr::Header{{"Content-Type", "application/json"}},
cpr::Header{{"accept", "application/json"}}, cpr::Body{textToSend});
} catch (...) {
}
};
void clearAllDictionaries(RE::StaticFunctionTag*) { clearAll(); };
int createDictionaryRelay(RE::StaticFunctionTag*) { return createDictionary(); };
// Returns the value associated with the @key. If not, returns @default value
std::string getStringRelay(RE::StaticFunctionTag*, int object, std::string key, std::string defaultValue) {
toLowerCase(&key);
return getString(object, key, defaultValue);
};
int getIntRelay(RE::StaticFunctionTag*, int object, std::string key, int defaultValue) {
toLowerCase(&key);
return getInt(object, key, defaultValue);
};
float getFloatRelay(RE::StaticFunctionTag*, int object, std::string key, float defaultValue) {
toLowerCase(&key);
return getFloat(object, key, defaultValue);
};
bool getBoolRelay(RE::StaticFunctionTag*, int object, std::string key, bool defaultValue) {
toLowerCase(&key);
return getBool(object, key, defaultValue);
};
int getNestedDictionaryRelay(RE::StaticFunctionTag*, int object, std::string key, int defaultValue) {
toLowerCase(&key);
return getNestedDictionary(object, key, defaultValue);
};
std::vector<std::string> getStringArrayRelay(RE::StaticFunctionTag*, int object, std::string key) {
toLowerCase(&key);
return getStringArray(object, key);
};
std::vector<int> getIntArrayRelay(RE::StaticFunctionTag*, int object, std::string key) {
toLowerCase(&key);
return getIntArray(object, key);
};
std::vector<float> getFloatArrayRelay(RE::StaticFunctionTag*, int object, std::string key) {
toLowerCase(&key);
return getFloatArray(object, key);
};
std::vector<bool> getBoolArrayRelay(RE::StaticFunctionTag*, int object, std::string key) {
toLowerCase(&key);
return getBoolArray(object, key);
};
std::vector<int> getNestedDictionariesArrayRelay(RE::StaticFunctionTag*, int object, std::string key) {
toLowerCase(&key);
return getArrayOfNestedDictionaries(object, key);
};
bool setStringRelay(RE::StaticFunctionTag*, int object, std::string key, std::string value) {
toLowerCase(&key);
if (!test_utf8(value)) return false;
setString(object, key, value);
return true;
};
void setIntRelay(RE::StaticFunctionTag*, int object, std::string key, int value) {
toLowerCase(&key);
setInt(object, key, value);
};
void setFloatRelay(RE::StaticFunctionTag*, int object, std::string key, float value) {
toLowerCase(&key);
setFloat(object, key, value);
};
void setBoolRelay(RE::StaticFunctionTag*, int object, std::string key, bool value) {
toLowerCase(&key);
setBool(object, key, value);
};
void setNestedDictionaryRelay(RE::StaticFunctionTag*, int object, std::string key, int value) {
toLowerCase(&key);
setNestedDictionary(object, key, value);
};
bool setStringArrayRelay(RE::StaticFunctionTag*, int object, std::string key,
const std::vector< std::string > value) {
toLowerCase(&key);
std::vector<std::string> vector;
bool result = true;
try {
for (int i = 0; i < value.size(); ++i) {
if (test_utf8(value[i])) {
vector.push_back(value[i]);
} else {
result = false;
}
}
} catch (...) {
}
setStringArray(object, key, vector);
return true;
};
void setIntArrayRelay(RE::StaticFunctionTag*, int object, std::string key, const std::vector<int> value) {
toLowerCase(&key);
std::vector<int> vector;
try {
for (int i = 0; i < value.size(); ++i) vector.push_back(value[i]);
} catch (...) {
}
setIntArray(object, key, vector);
};
void setFloatArrayRelay(RE::StaticFunctionTag*, int object, std::string key, const std::vector<float> value) {
toLowerCase(&key);
std::vector<float> vector;
try {
for (int i = 0; i < value.size(); ++i) vector.push_back(value[i]);
} catch (...) {
}
setFloatArray(object, key, vector);
};
void setBoolArrayRelay(RE::StaticFunctionTag*, int object, std::string key, std::vector<bool> value) {
toLowerCase(&key);
std::vector<bool> vector;
try {
for (int i = 0; i < value.size(); ++i) vector.push_back(value[i]);
} catch (...) {
}
setBoolArray(object, key, vector);
};
void setNestedDictionariesArrayRelay(RE::StaticFunctionTag*, int object, std::string key,
const std::vector<int> value) {
toLowerCase(&key);
std::vector<int> vector;
try {
for (int i = 0; i < value.size(); ++i) vector.push_back(value[i]);
} catch (...) {
}
setArrayOfNestedDictionaries(object, key, vector);
};
void TakeScreenShot(RE::StaticFunctionTag* ) {
INPUT keyEvent[2];
WORD wkey = 0x2C; // Prtscreen
SKSE::log::info("Screenshot");
keyEvent[0].type = INPUT_KEYBOARD;
keyEvent[0].ki.wVk = 0;
keyEvent[0].ki.dwFlags = 0;
keyEvent[0].ki.time = 0;
keyEvent[0].ki.dwExtraInfo = GetMessageExtraInfo();
keyEvent[0].ki.wScan = (WORD)0xb7;
UINT ret = SendInput(1, keyEvent, sizeof(INPUT));
Sleep(20);
keyEvent[0].type = INPUT_KEYBOARD;
keyEvent[0].ki.wVk = 0;
keyEvent[0].ki.dwFlags = KEYEVENTF_KEYUP;
keyEvent[0].ki.time = 0;
keyEvent[0].ki.dwExtraInfo = GetMessageExtraInfo();
keyEvent[0].ki.wScan = (WORD)0xb7;
ret = SendInput(1, keyEvent, sizeof(INPUT));
}
void RenameScreenshot(RE::StaticFunctionTag*, std::string newname) {
RE::INISettingCollection* ini = RE::INIPrefSettingCollection::GetSingleton();
RE::Setting *ssIndex = ini->GetSetting("iScreenShotIndex:Display");
char exe_path[_MAX_PATH];
if (ssIndex != nullptr) {
int SSidx = ssIndex->GetUInt() - 1;
GetModuleFileNameA(NULL, exe_path, _MAX_PATH); // Skyrim exe
std::filesystem::path app_path(exe_path);
std::filesystem::path base_path(app_path.remove_filename());
std::filesystem::path src_path(base_path / std::format("ScreenShot{:d}.png", SSidx));
std::filesystem::path dst_path(base_path / newname);
DeleteFile(dst_path.c_str());
MoveFile(src_path.c_str(), dst_path.c_str());
}
}
RE::BGSVoiceType* GetVoiceType(RE::StaticFunctionTag*, RE::Actor* actor) {
RE::TESActorBase* actorBase = actor->GetActorBase();
RE::BGSVoiceType* voiceType = actorBase->voiceType;
return voiceType;
}
void SetVoiceType(RE::StaticFunctionTag*, RE::Actor* actor, RE::BGSVoiceType* voice) {
RE::TESActorBase* actorBase = actor->GetActorBase();
actorBase->voiceType = voice;
}
RE::BGSVoiceType* GetRaceDefaultVoiceType(RE::StaticFunctionTag*, RE::Actor* actor) {
try {
if (actor->GetActorBase()->GetSex() == RE::SEX::kMale) {
RE::BGSVoiceType* voiceType = actor->GetRace()->defaultVoiceTypes[0];
return voiceType;
} else {
RE::BGSVoiceType* voiceType = actor->GetRace()->defaultVoiceTypes[1];
return voiceType;
}
} catch (...) {
RE::TESActorBase* actorBase = actor->GetActorBase();
RE::BGSVoiceType* voiceType = actorBase->voiceType;
return voiceType;
}
}
void SetRaceDefaultVoiceType(RE::StaticFunctionTag*, RE::Actor* actor, RE::BGSVoiceType* voice) {
try {
if (actor->GetActorBase()->GetSex() == RE::SEX::kMale)
actor->GetRace()->defaultVoiceTypes[0] = voice;
else
actor->GetRace()->defaultVoiceTypes[1] = voice;
} catch (...) {
}
}
// Returns true, if the container has @key: value pair
bool hasKeyRelay(RE::StaticFunctionTag*, int object, std::string key) { return hasKey(object, key); };
bool Bind(RE::BSScript::IVirtualMachine* vm) {
std::string className = "SKSE_HTTP";
vm->RegisterFunction("sendLocalhostHttpRequest", className, sendLocalhostHttpRequest);
vm->RegisterFunction("createDictionary", className, createDictionaryRelay);
vm->RegisterFunction("clearAllDictionaries", className, clearAllDictionaries);
vm->RegisterFunction("getString", className, getStringRelay);
vm->RegisterFunction("getInt", className, getIntRelay);
vm->RegisterFunction("getFloat", className, getFloatRelay);
vm->RegisterFunction("getBool", className, getBoolRelay);
vm->RegisterFunction("getNestedDictionary", className, getNestedDictionaryRelay);
vm->RegisterFunction("getStringArray", className, getStringArrayRelay);
vm->RegisterFunction("getIntArray", className, getIntArrayRelay);
vm->RegisterFunction("getFloatArray", className, getFloatArrayRelay);
vm->RegisterFunction("getBoolArray", className, getBoolArrayRelay);
vm->RegisterFunction("getNestedDictionariesArray", className, getNestedDictionariesArrayRelay);
vm->RegisterFunction("setString", className, setStringRelay);
vm->RegisterFunction("setInt", className, setIntRelay);
vm->RegisterFunction("setFloat", className, setFloatRelay);
vm->RegisterFunction("setBool", className, setBoolRelay);
vm->RegisterFunction("setNestedDictionary", className, setNestedDictionaryRelay);
vm->RegisterFunction("setStringArray", className, setStringArrayRelay);
vm->RegisterFunction("setIntArray", className, setIntArrayRelay);
vm->RegisterFunction("setFloatArray", className, setFloatArrayRelay);
vm->RegisterFunction("setBoolArray", className, setBoolArrayRelay);
vm->RegisterFunction("setNestedDictionariesArray", className, setNestedDictionariesArrayRelay);
vm->RegisterFunction("TakeScreenShot", className, TakeScreenShot);
vm->RegisterFunction("GetVoiceType", className, GetVoiceType);
vm->RegisterFunction("SetVoiceType", className, SetVoiceType);
vm->RegisterFunction("RenameScreenshot", className, RenameScreenshot);
vm->RegisterFunction("GetRaceDefaultVoiceType", className, GetRaceDefaultVoiceType);
vm->RegisterFunction("SetRaceDefaultVoiceType", className, SetRaceDefaultVoiceType);
vm->RegisterFunction("hasKey", className, hasKeyRelay);
return true;
};
SKSEPluginLoad(const SKSE::LoadInterface* skse) {
SKSE::Init(skse);
//InitializeLogging();
SKSE::GetPapyrusInterface()->Register(Bind);
return true;
};