-
Notifications
You must be signed in to change notification settings - Fork 113
/
NSFW.cpp
359 lines (294 loc) · 9.5 KB
/
NSFW.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
#include "../includes/NSFW.h"
Napi::FunctionReference NSFW::constructor;
std::size_t NSFW::instanceCount = 0;
bool NSFW::gcEnabled = false;
NSFW::NSFW(const Napi::CallbackInfo &info):
Napi::ObjectWrap<NSFW>(info),
mDebounceMS(0),
mInterface(nullptr),
mQueue(std::make_shared<EventQueue>()),
mPath(""),
mRunning(false)
{
auto env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
throw Napi::TypeError::New(env, "Must pass a string path as the first argument to NSFW.");
}
mPath = info[0].ToString();
if (info.Length() < 2 || !info[1].IsFunction()) {
throw Napi::TypeError::New(env, "Must pass an event callback as the second parameter to NSFW.");
}
mEventCallback = Napi::ThreadSafeFunction::New(
env,
info[1].As<Napi::Function>(),
"nsfw",
0,
1
);
if (info.Length() >= 3) {
if (!info[2].IsObject()) {
throw Napi::TypeError::New(env, "If the third parameter to NSFW is provided, it must be an object.");
}
Napi::Object options = info[2].ToObject();
Napi::Value maybeDebounceMS = options["debounceMS"];
if (options.Has("debounceMS") && !maybeDebounceMS.IsNumber()) {
throw Napi::TypeError::New(env, "options.debounceMS must be a number.");
}
if (maybeDebounceMS.IsNumber()) {
Napi::Number temp = maybeDebounceMS.ToNumber();
double bounds = temp.DoubleValue();
if (bounds < 1 || bounds > 60000) {
throw Napi::TypeError::New(env, "options.debounceMS must be >= 1 and <= 60000.");
}
mDebounceMS = temp;
}
Napi::Value maybeErrorCallback = options["errorCallback"];
if (options.Has("errorCallback") && !maybeErrorCallback.IsFunction()) {
throw Napi::TypeError::New(env, "options.errorCallback must be a function.");
}
mErrorCallback = Napi::ThreadSafeFunction::New(
env,
maybeErrorCallback.IsFunction()
? maybeErrorCallback.As<Napi::Function>()
: Napi::Function::New(env, [](const Napi::CallbackInfo &info) {}),
"nsfw",
0,
1
);
}
if (gcEnabled) {
instanceCount++;
}
}
NSFW::~NSFW() {
mErrorCallback.Release();
mEventCallback.Release();
if (gcEnabled) {
instanceCount--;
}
}
NSFW::StartWorker::StartWorker(Napi::Env env, NSFW *nsfw):
Napi::AsyncWorker(env, "nsfw"),
mDeferred(Napi::Promise::Deferred::New(env)),
mNSFW(nsfw),
mStatus(JOB_NOT_EXECUTED_YET)
{}
Napi::Promise NSFW::StartWorker::RunJob() {
mNSFW->Ref();
this->Queue();
return mDeferred.Promise();
}
void NSFW::StartWorker::Execute() {
std::lock_guard<std::mutex> lock(mNSFW->mInterfaceLock);
if (mNSFW->mInterface) {
mStatus = ALREADY_RUNNING;
return;
}
mNSFW->mQueue->clear();
mNSFW->mInterface.reset(new NativeInterface(mNSFW->mPath, mNSFW->mQueue));
if (mNSFW->mInterface->isWatching()) {
mStatus = STARTED;
mNSFW->mRunning = true;
mNSFW->mErrorCallback.Acquire();
mNSFW->mEventCallback.Acquire();
mNSFW->mPollThread = std::thread([] (NSFW *nsfw) { nsfw->pollForEvents(); }, mNSFW);
} else {
mStatus = COULD_NOT_START;
mNSFW->mInterface.reset(nullptr);
}
}
void NSFW::StartWorker::OnOK() {
std::lock_guard<std::mutex> lock(mNSFW->mInterfaceLock);
auto env = Env();
switch (mStatus) {
case ALREADY_RUNNING:
mNSFW->Unref();
mDeferred.Reject(Napi::Error::New(env, "This NSFW cannot be started, because it is already running.").Value());
break;
case COULD_NOT_START:
mNSFW->Unref();
mDeferred.Reject(Napi::Error::New(env, "NSFW was unable to start watching that directory.").Value());
break;
case STARTED:
mDeferred.Resolve(env.Undefined());
break;
default:
mNSFW->Unref();
mDeferred.Reject(Napi::Error::New(
env,
"Execute did not run, but OnOK fired. This should never have happened."
).Value());
}
}
Napi::Value NSFW::Start(const Napi::CallbackInfo &info) {
return (new StartWorker(info.Env(), this))->RunJob();
}
NSFW::StopWorker::StopWorker(Napi::Env env, NSFW *nsfw):
Napi::AsyncWorker(env, "nsfw"),
mDeferred(Napi::Promise::Deferred::New(env)),
mDidStopWatching(false),
mNSFW(nsfw)
{}
Napi::Promise NSFW::StopWorker::RunJob() {
this->Queue();
return mDeferred.Promise();
}
void NSFW::StopWorker::Execute() {
{
std::lock_guard<std::mutex> lock(mNSFW->mInterfaceLock);
if (!mNSFW->mInterface) {
return;
}
}
mDidStopWatching = true;
mNSFW->mRunning = false;
mNSFW->mPollThread.join();
std::lock_guard<std::mutex> lock(mNSFW->mInterfaceLock);
mNSFW->mInterface.reset(nullptr);
mNSFW->mQueue->clear();
}
void NSFW::StopWorker::OnOK() {
std::lock_guard<std::mutex> lock(mNSFW->mInterfaceLock);
if (mDidStopWatching) {
mNSFW->Unref();
mDeferred.Resolve(Env().Undefined());
} else {
mDeferred.Reject(Napi::Error::New(Env(), "This NSFW cannot be stopped, because it is not running.").Value());
}
}
Napi::Value NSFW::Stop(const Napi::CallbackInfo &info) {
return (new StopWorker(info.Env(), this))->RunJob();
}
NSFW::PauseWorker::PauseWorker(Napi::Env env, NSFW *nsfw):
Napi::AsyncWorker(env, "nsfw"),
mDeferred(Napi::Promise::Deferred::New(env)),
mDidPauseEvents(false),
mNSFW(nsfw)
{}
Napi::Promise NSFW::PauseWorker::RunJob() {
this->Queue();
return mDeferred.Promise();
}
void NSFW::PauseWorker::Execute() {
mDidPauseEvents = true;
mNSFW->pauseQueue();
}
void NSFW::PauseWorker::OnOK() {
if (mDidPauseEvents) {
mDeferred.Resolve(Env().Undefined());
} else {
mDeferred.Reject(Napi::Error::New(Env(), "This NSFW could not be paused.").Value());
}
}
Napi::Value NSFW::Pause(const Napi::CallbackInfo &info) {
return (new PauseWorker(info.Env(), this))->RunJob();
}
NSFW::ResumeWorker::ResumeWorker(Napi::Env env, NSFW *nsfw):
Napi::AsyncWorker(env, "nsfw"),
mDeferred(Napi::Promise::Deferred::New(env)),
mDidResumeEvents(false),
mNSFW(nsfw)
{}
Napi::Promise NSFW::ResumeWorker::RunJob() {
this->Queue();
return mDeferred.Promise();
}
void NSFW::ResumeWorker::Execute() {
mDidResumeEvents = true;
mNSFW->resumeQueue();
}
void NSFW::ResumeWorker::OnOK() {
if (mDidResumeEvents) {
mDeferred.Resolve(Env().Undefined());
} else {
mDeferred.Reject(Napi::Error::New(Env(), "This NSFW could not be resumed.").Value());
}
}
Napi::Value NSFW::Resume(const Napi::CallbackInfo &info) {
return (new ResumeWorker(info.Env(), this))->RunJob();
}
void NSFW::pauseQueue() {
mQueue->pause();
}
void NSFW::resumeQueue() {
mQueue->resume();
}
void NSFW::pollForEvents() {
while (mRunning) {
uint32_t sleepDuration = 50;
{
std::lock_guard<std::mutex> lock(mInterfaceLock);
if (mInterface->hasErrored()) {
const std::string &error = mInterface->getError();
mErrorCallback.NonBlockingCall([error](Napi::Env env, Napi::Function jsCallback) {
Napi::Value jsError = Napi::Error::New(env, error).Value();
jsCallback.Call({ jsError });
});
mRunning = false;
break;
}
if (mQueue->count() != 0) {
auto events = mQueue->dequeueAll();
if (events != nullptr) {
sleepDuration = mDebounceMS;
auto callback = [](Napi::Env env, Napi::Function jsCallback, std::vector<std::unique_ptr<Event>> *eventsRaw) {
std::unique_ptr<std::vector<std::unique_ptr<Event>>> events(eventsRaw);
eventsRaw = nullptr;
int numEvents = events->size();
Napi::Array eventArray = Napi::Array::New(env, numEvents);
for (int i = 0; i < numEvents; ++i) {
auto event = Napi::Object::New(env);
event["action"] = Napi::Number::New(env, (*events)[i]->type);
event["directory"] = Napi::String::New(env, (*events)[i]->fromDirectory);
if ((*events)[i]->type == RENAMED) {
event["oldFile"] = Napi::String::New(env, (*events)[i]->fromFile);
event["newDirectory"] = Napi::String::New(env, (*events)[i]->toDirectory);
event["newFile"] = Napi::String::New(env, (*events)[i]->toFile);
} else {
event["file"] = Napi::String::New(env, (*events)[i]->fromFile);
}
eventArray[(uint32_t)i] = event;
}
jsCallback.Call({ eventArray });
};
mEventCallback.NonBlockingCall(events.release(), callback);
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(sleepDuration));
}
mErrorCallback.Release();
mEventCallback.Release();
}
Napi::Value NSFW::InstanceCount(const Napi::CallbackInfo &info) {
return Napi::Number::New(info.Env(), instanceCount);
}
Napi::Object NSFW::Init(Napi::Env env, Napi::Object exports) {
gcEnabled = ((Napi::Value)env.Global()["gc"]).IsFunction();
Napi::Function nsfwConstructor = DefineClass(env, "NSFW", {
InstanceMethod("start", &NSFW::Start),
InstanceMethod("stop", &NSFW::Stop),
InstanceMethod("pause", &NSFW::Pause),
InstanceMethod("resume", &NSFW::Resume)
});
if (gcEnabled) {
nsfwConstructor.DefineProperty(Napi::PropertyDescriptor::Function(
"getAllocatedInstanceCount",
&NSFW::InstanceCount,
napi_static
));
}
#ifdef NSFW_TEST_SLOW_1
nsfwConstructor.DefineProperty(Napi::PropertyDescriptor::Value(
"NSFW_TEST_SLOW",
Napi::Boolean::New(env, true)
));
#endif
constructor = Napi::Persistent(nsfwConstructor);
constructor.SuppressDestruct();
return nsfwConstructor;
}
static Napi::Object Init(Napi::Env env, Napi::Object exports) {
return NSFW::Init(env, exports);
}
NODE_API_MODULE(nsfw, Init)