-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSyncRoot.cpp
More file actions
339 lines (297 loc) · 11.6 KB
/
SyncRoot.cpp
File metadata and controls
339 lines (297 loc) · 11.6 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
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
#include "Callbacks.h"
#include "SyncRoot.h"
#include "stdafx.h"
#include <filesystem>
#include "Logger.h"
#include <iostream>
#include <vector>
namespace fs = std::filesystem;
// variable to disconect
CF_CONNECTION_KEY gloablConnectionKey;
std::map<std::wstring, CF_CONNECTION_KEY> connectionMap;
void TransformInputCallbacksToSyncCallbacks(napi_env env, InputSyncCallbacks input)
{
register_threadsafe_callbacks(env, input);
}
void AddCustomState(
_In_ winrt::IVector<winrt::StorageProviderItemPropertyDefinition> &customStates,
_In_ LPCWSTR displayNameResource,
_In_ int id)
{
winrt::StorageProviderItemPropertyDefinition customState;
customState.DisplayNameResource(displayNameResource);
customState.Id(id);
customStates.Append(customState);
}
void SyncRoot::HydrateFile(const wchar_t *filePath)
{
wprintf(L"Hydration file started %ls\n", filePath);
DWORD attrib = GetFileAttributesW(filePath);
if (!(attrib & FILE_ATTRIBUTE_DIRECTORY))
{
winrt::handle placeholder(CreateFileW(filePath, 0, FILE_READ_DATA, nullptr, OPEN_EXISTING, 0, nullptr));
LARGE_INTEGER offset;
offset.QuadPart = 0;
LARGE_INTEGER length;
GetFileSizeEx(placeholder.get(), &length);
if (attrib & FILE_ATTRIBUTE_PINNED)
{
// if (!(attrib & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS))
// {
Logger::getInstance().log("Hydration file init", LogLevel::INFO);
auto start = std::chrono::steady_clock::now();
HRESULT hr = CfHydratePlaceholder(placeholder.get(), offset, length, CF_HYDRATE_FLAG_NONE, NULL);
if (FAILED(hr))
{
Logger::getInstance().log("Error hydrating file " + Logger::fromWStringToString(filePath), LogLevel::ERROR);
}
else
{
auto end = std::chrono::steady_clock::now();
auto elapsedMilliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
if (elapsedMilliseconds < 200)
{
wprintf(L"Already Hydrated: %d ms\n", elapsedMilliseconds);
}
else
{
wprintf(L"Hydration finished %ls\n", filePath);
}
}
// }
// else
// {
// wprintf(L"File is already hydrated: %ls\n", filePath);
// Logger::getInstance().log("File is already hydrated " + Logger::fromWStringToString(filePath), LogLevel::INFO);
// }
}
}
}
void SyncRoot::DehydrateFile(const wchar_t *filePath)
{
// Logger::getInstance().log("Dehydration file init", LogLevel::INFO);
wprintf(L"Dehydration file init %ls\n", filePath);
DWORD attrib = GetFileAttributesW(filePath);
if (!(attrib & FILE_ATTRIBUTE_DIRECTORY))
{
winrt::handle placeholder(CreateFileW(filePath, 0, FILE_READ_DATA, nullptr, OPEN_EXISTING, 0, nullptr));
LARGE_INTEGER offset;
offset.QuadPart = 0;
LARGE_INTEGER length;
GetFileSizeEx(placeholder.get(), &length);
if (attrib & FILE_ATTRIBUTE_UNPINNED)
{
// Logger::getInstance().log("Dehydrating file " + Logger::fromWStringToString(filePath), LogLevel::INFO);
wprintf(L"Dehydrating file starteeed %ls\n", filePath);
HRESULT hr = CfDehydratePlaceholder(placeholder.get(), offset, length, CF_DEHYDRATE_FLAG_NONE, NULL);
if (FAILED(hr))
{
wprintf(L"Error dehydrating file %ls\n", filePath);
// Logger::getInstance().log("Error dehydrating file " + Logger::fromWStringToString(filePath), LogLevel::ERROR);
}
else
{
wprintf(L"Dehydration finished %ls\n", filePath);
// Logger::getInstance().log("Dehydration finished " + Logger::fromWStringToString(filePath), LogLevel::INFO);
}
}
}
}
HRESULT SyncRoot::RegisterSyncRoot(const wchar_t *syncRootPath, const wchar_t *providerName, const wchar_t *providerVersion, const GUID &providerId, const wchar_t *logoPath)
{
try
{
// Convert GUID to string for syncRootID
wchar_t syncRootID[39];
StringFromGUID2(providerId, syncRootID, 39);
winrt::StorageProviderSyncRootInfo info;
info.Id(syncRootID);
auto folder = winrt::StorageFolder::GetFolderFromPathAsync(syncRootPath).get();
info.Path(folder);
// The string can be in any form acceptable to SHLoadIndirectString.
info.DisplayNameResource(providerName);
std::wstring completeIconResource = std::wstring(logoPath) + L",0";
// This icon is just for the sample. You should provide your own branded icon here
info.IconResource(completeIconResource.c_str());
info.HydrationPolicy(winrt::StorageProviderHydrationPolicy::Full);
info.HydrationPolicyModifier(winrt::StorageProviderHydrationPolicyModifier::None);
info.PopulationPolicy(winrt::StorageProviderPopulationPolicy::AlwaysFull);
info.InSyncPolicy(winrt::StorageProviderInSyncPolicy::FileCreationTime | winrt::StorageProviderInSyncPolicy::DirectoryCreationTime);
info.Version(providerVersion);
info.ShowSiblingsAsGroup(false);
info.HardlinkPolicy(winrt::StorageProviderHardlinkPolicy::None);
winrt::Uri uri(L"https://drive.internxt.com/app/trash");
info.RecycleBinUri(uri);
// Context
std::wstring syncRootIdentity(syncRootPath);
syncRootIdentity.append(L"#intx#");
syncRootIdentity.append(providerName);
winrt::IBuffer contextBuffer = winrt::CryptographicBuffer::ConvertStringToBinary(syncRootIdentity.data(), winrt::BinaryStringEncoding::Utf8);
info.Context(contextBuffer);
winrt::IVector<winrt::StorageProviderItemPropertyDefinition> customStates = info.StorageProviderItemPropertyDefinitions();
AddCustomState(customStates, L"CustomStateName1", 1);
AddCustomState(customStates, L"CustomStateName2", 2);
AddCustomState(customStates, L"CustomStateName3", 3);
winrt::StorageProviderSyncRootManager::Register(info);
Sleep(1000);
return S_OK;
}
catch (...)
{
wprintf(L"Could not register the sync root, hr %08x\n", static_cast<HRESULT>(winrt::to_hresult()));
return E_FAIL;
}
}
std::vector<SyncRoots> SyncRoot::GetRegisteredSyncRoots()
{
std::vector<SyncRoots> syncRootList;
try
{
auto syncRoots = winrt::StorageProviderSyncRootManager::GetCurrentSyncRoots();
printf("Sync roots count: %d\n", syncRoots.Size());
for (auto const &info : syncRoots)
{
auto contextBuffer = info.Context();
std::wstring contextString;
if (contextBuffer)
{
contextString = winrt::CryptographicBuffer::ConvertBinaryToString(
winrt::BinaryStringEncoding::Utf8,
contextBuffer)
.c_str();
}
/**
* v2.5.1 Jonathan Arce
* Sync root register are now filtered using the characters '->' and '#inxt#' to identify our register.
* Currently, we only use '#inxt#' in the register, but to support previous versions, we are still
* including '->' in the filter. In future versions, the filtering by '->' should be removed.
*/
if (contextString.find(L"#inxt#") != std::wstring::npos || contextString.find(L"->") != std::wstring::npos)
{
SyncRoots sr;
sr.id = info.Id();
sr.path = info.Path().Path();
sr.displayName = info.DisplayNameResource();
sr.version = info.Version();
syncRootList.push_back(sr);
}
}
}
catch (...)
{
Logger::getInstance().log("ERROR: getting sync root", LogLevel::INFO);
}
return syncRootList;
}
HRESULT SyncRoot::UnregisterSyncRoot(const GUID &providerId)
{
try
{
// Convert GUID to string for syncRootID
wchar_t syncRootID[39];
StringFromGUID2(providerId, syncRootID, 39);
Logger::getInstance().log("Unregistering sync root.", LogLevel::INFO);
winrt::StorageProviderSyncRootManager::Unregister(syncRootID);
return S_OK;
}
catch (...)
{
wprintf(L"Could not unregister the sync root, hr %08x\n", static_cast<HRESULT>(winrt::to_hresult()));
return E_FAIL;
}
}
HRESULT SyncRoot::ConnectSyncRoot(const wchar_t *syncRootPath, InputSyncCallbacks syncCallbacks, napi_env env, CF_CONNECTION_KEY *connectionKey)
{
try
{
Utilities::AddFolderToSearchIndexer(syncRootPath);
TransformInputCallbacksToSyncCallbacks(env, syncCallbacks);
CF_CALLBACK_REGISTRATION callbackTable[] = {
{CF_CALLBACK_TYPE_NOTIFY_DELETE, notify_delete_callback_wrapper},
{CF_CALLBACK_TYPE_NOTIFY_RENAME, notify_rename_callback_wrapper},
{CF_CALLBACK_TYPE_FETCH_PLACEHOLDERS, fetch_placeholders_callback_wrapper},
{CF_CALLBACK_TYPE_FETCH_DATA, fetch_data_callback_wrapper},
{CF_CALLBACK_TYPE_CANCEL_FETCH_DATA, cancel_fetch_data_callback_wrapper},
CF_CALLBACK_REGISTRATION_END};
HRESULT hr = CfConnectSyncRoot(
syncRootPath,
callbackTable,
nullptr, // Contexto (opcional)
CF_CONNECT_FLAG_REQUIRE_PROCESS_INFO | CF_CONNECT_FLAG_REQUIRE_FULL_FILE_PATH,
connectionKey);
wprintf(L"Connection key: %llu\n", *connectionKey);
if (SUCCEEDED(hr))
{
connectionMap[syncRootPath] = *connectionKey;
}
return hr;
}
catch (const std::exception &e)
{
wprintf(L"Excepción capturada: %hs\n", e.what());
return E_FAIL;
}
catch (...)
{
wprintf(L"Excepción desconocida capturada\n");
return E_FAIL;
}
}
// disconection sync root
HRESULT SyncRoot::DisconnectSyncRoot(const wchar_t *syncRootPath)
{
auto it = connectionMap.find(syncRootPath);
if (it != connectionMap.end())
{
HRESULT hr = CfDisconnectSyncRoot(it->second);
if (SUCCEEDED(hr))
{
connectionMap.erase(it);
}
return hr;
}
return E_FAIL;
}
// struct
struct FileIdentityInfo
{
BYTE *FileIdentity;
size_t FileIdentityLength;
};
void SyncRoot::DeleteFileSyncRoot(const wchar_t *path)
{
try
{
// Mostrar el archivo a eliminar
wprintf(L"Intentando eliminar: %ls\n", path);
// Verificar si el archivo es un directorio o un archivo regular
bool isDirectory = fs::is_directory(path);
wprintf(L"Es directorio: %d\n", isDirectory);
// Si es un directorio, eliminar recursivamente
if (isDirectory)
{
fs::remove_all(path); // Esta línea reemplaza la función personalizada DeleteFileOrDirectory
wprintf(L"Directorio eliminado con éxito: %ls\n", path);
}
else
{
// Si es un archivo, simplemente eliminar
if (!DeleteFileW(path))
{
wprintf(L"No se pudo eliminar el archivo: %ls\n", path);
}
else
{
wprintf(L"Archivo eliminado con éxito: %ls\n", path);
}
}
}
catch (const std::exception &e)
{
wprintf(L"Excepción capturada: %hs\n", e.what());
}
catch (...)
{
wprintf(L"Excepción desconocida capturada\n");
}
}