-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclsFSWatcher.cls
More file actions
713 lines (571 loc) · 26.3 KB
/
Copy pathclsFSWatcher.cls
File metadata and controls
713 lines (571 loc) · 26.3 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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "clsFSWatcher"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
' =====================================================
' WRAPPER VBA PARA COMPONENTE COM FolderWatcher
' =====================================================
' Este módulo envuelve el componente COM FolderWatcherCOM.dll
' escrito en VB.NET (.NET Framework 4.0).
'
' CARGA DEL COM SIN REGISTRO:
' -------------------------------------------------------------------------------------
' El COM se carga usando Activation Context API.
' Esto permite usar el COM sin registrarlo en Windows (sin permisos admin).
' Los archivos necesarios (DLL y manifest) deben estar en la carpeta de AddIns.
'
' GESTIÓN DE RECURSOS:
' -------------------------------------------------------------------------------------
' El COM implementa correctamente IDisposable (ver FolderWatcher.vb):
' - Dispose() llama a EnableRaisingEvents = False antes de liberar cada watcher
' - Finalize() actúa como safety net si Dispose() no se llama
' - GC.SuppressFinalize(Me) evita doble limpieza
'
' IMPORTANTE: Desde VBA, llamar siempre a StopWatching o usar el método
' Dispose() de esta clase ANTES de hacer Set = Nothing, para garantizar
' que el COM libere correctamente los FileSystemWatcher internos.
'
' NOTA SOBRE RECURSOS COM:
' El componente FolderWatcherCOM.dll (.NET Framework 4.0) usa FileSystemWatcher
' que puede quedarse residente si no se libera correctamente.
' Ver clsFolderWatch.cls para documentacion detallada y recomendaciones
' para el codigo VB.NET del COM.
'
' SOLUCION IMPLEMENTADA:
' - clsFolderWatch.Dispose() libera todos los recursos
' - clsAplicacion.Terminate() llama a Dispose antes de Set = Nothing
' =====================================================
'@Folder "2-Servicios.Archivos.Supervision"
Option Explicit
' =====================================================
' ENUMERACIONES (deben coincidir con FolderWatcher.vb)
' =====================================================
Public Enum FileFilterType
None = 0
FileSize = 1
fileDate = 2
FileAttributes = 4
foldersOnly = 8
FilesOnly = 16
End Enum
Public Enum AutoActionType
None = 0
MoveFile = 1
CopyFile = 2
Archive = 3
Delete = 4
LogOnly = 5
End Enum
Public Enum DateCompareMode
CreatedAfter = 1
CreatedBefore = 2
ModifiedAfter = 3
ModifiedBefore = 4
End Enum
' =====================================================
' WRAPPER VBA PARA COMPONENTE COM
' =====================================================
Private WithEvents fw As FolderWatcher
Attribute fw.VB_VarHelpID = -1
Private mInitialized As Boolean
Private mDisposed As Boolean ' Flag para evitar doble limpieza
Private mWatchedFolders As Object ' Dictionary de carpetas monitoreadas
Private Const MODULE_NAME As String = "clsFolderWatch"
' =====================================================
' EVENTOS PÚBLICOS (se propagan a clsAplicacion)
' =====================================================
Public Event FileCreated(ByVal folder As String, ByVal fileName As String)
Public Event FileDeleted(ByVal folder As String, ByVal fileName As String)
Public Event FileChanged(ByVal folder As String, ByVal fileName As String)
Public Event FileRenamed(ByVal folder As String, ByVal oldName As String, ByVal newName As String)
Public Event Heartbeat(ByVal folder As String, ByVal lastUpdate As Date)
Public Event ErrorOccurred(ByVal folder As String, ByVal errorMessage As String)
' Nuevos eventos para subcarpetas
Public Event SubfolderCreated(ByVal parentFolder As String, ByVal subfolderName As String)
Public Event SubfolderDeleted(ByVal parentFolder As String, ByVal subfolderName As String)
Public Event SubfolderRenamed(ByVal parentFolder As String, ByVal oldName As String, ByVal newName As String)
' Eventos de reconexión automática para carpetas de red
Public Event WatcherReconnected(ByVal folder As String, ByVal attempts As Long)
Public Event WatcherReconnectionFailed(ByVal folder As String, ByVal reason As String)
' =====================================================
' INICIALIZACIÓN Y LIMPIEZA
' =====================================================
Private Sub Class_Initialize()
LogInfo MODULE_NAME, "[Class_Initialize] - Inicializando wrapper VBA para FolderWatcher COM"
On Error GoTo ErrHandler
mDisposed = False
Set mWatchedFolders = CreateObject("Scripting.Dictionary")
If Not CrearCOMConActivationContext() Then
' Si falla, intentar con CreateObject normal (COM registrado)
LogWarning MODULE_NAME, "Activation Context falló, intentando con COM registrado"
On Error GoTo ErrHandlerCOM
Set fw = CreateObject("FolderWatcher.Monitor")
End If
If fw Is Nothing Then
LogError MODULE_NAME, "[Class_Initialize] - No se pudo crear el objeto COM FolderWatcher"
mInitialized = False
Exit Sub
End If
mInitialized = True
LogDebug MODULE_NAME, "[Class_Initialize] - Componente COM conectado: " & fw.GetConfiguration()
Exit Sub
ErrHandlerCOM:
LogError MODULE_NAME, "[Class_Initialize] - Error creando COM (ni Activation Context ni registro)", Err.Number, Err.Description
mInitialized = False
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[Class_Initialize] - Error en inicialización COM", Err.Number, Err.Description
mInitialized = False
End Sub
'@Description: Intenta crear el COM usando Activation Context (sin registro)
Private Function CrearCOMConActivationContext() As Boolean
On Error GoTo ErrHandler
' Verificar si los archivos existen
If Not ComprobarArchivosCOM() Then
LogWarning MODULE_NAME, "[CrearCOMConActivationContext] - Archivos COM no encontrados en: " & Application.UserLibraryPath
CrearCOMConActivationContext = False
Exit Function
End If
' Intentar crear el COM usando Activation Context (sin registro)
' Inicializar Activation Context
With VBA.CreateObject("Microsoft.Windows.ActCtx")
.Manifest = ObtenerRutaManifest 'ObtenerRutaCOM '
Set fw = .CreateObject("FolderWatcher.Monitor")
End With
If fw Is Nothing Then
CrearCOMConActivationContext = False
Else
LogDebug MODULE_NAME, "[CrearCOMConActivationContext] - COM creado exitosamente con Activation Context"
CrearCOMConActivationContext = True
End If
Exit Function
ErrHandler:
LogError MODULE_NAME, "[CrearCOMConActivationContext] - Error", Err.Number, Err.Description
CrearCOMConActivationContext = False
End Function
Private Sub Class_Terminate()
LogInfo MODULE_NAME, "[Class_Terminate] - Iniciando limpieza"
Dispose
End Sub
'@Description: Limpia explicitamente todos los recursos del FolderWatcher
'@Note: Llamar este metodo ANTES de Set obj = Nothing para garantizar limpieza
Public Sub Dispose()
On Error Resume Next ' Asegurar que la limpieza continua aunque haya errores
' Evitar doble limpieza
If mDisposed Then
LogDebug MODULE_NAME, "[Dispose] - Ya fue ejecutado, omitiendo"
Exit Sub
End If
LogDebug MODULE_NAME, "[Dispose] - Iniciando limpieza de recursos"
' 1. Detener todos los monitoreos activos
If Not mWatchedFolders Is Nothing Then
Dim carpeta As Variant
Dim countFolders As Long
countFolders = mWatchedFolders.Count
For Each carpeta In mWatchedFolders.Keys
If mInitialized And Not fw Is Nothing Then
LogDebug MODULE_NAME, "[Dispose] - Deteniendo monitoreo de: " & CStr(carpeta)
fw.StopWatching CStr(carpeta)
End If
Next carpeta
mWatchedFolders.RemoveAll
LogDebug MODULE_NAME, "[Dispose] - " & countFolders & " carpetas liberadas"
End If
' 2. Liberar referencia al COM
If Not fw Is Nothing Then
LogDebug MODULE_NAME, "[Dispose] - Liberando referencia COM"
Set fw = Nothing
End If
' 3. Liberar diccionario
If Not mWatchedFolders Is Nothing Then
Set mWatchedFolders = Nothing
End If
mInitialized = False
mDisposed = True
LogInfo MODULE_NAME, "[Dispose] - Limpieza completada"
End Sub
'@Description: Indica si el objeto ha sido liberado
Public Property Get IsDisposed() As Boolean
IsDisposed = mDisposed
End Property
'@Description: Indica si el COM esta inicializado correctamente
Public Property Get IsInitialized() As Boolean
IsInitialized = mInitialized And Not mDisposed
End Property
' =====================================================
' MÉTODOS PRINCIPALES
' =====================================================
'@Description: Inicia monitoreo de una carpeta
'@Scope: público
'@ArgumentDescriptions:
' folderPath: ruta completa de la carpeta a monitorear
' includeSubdirs: monitorear subcarpetas recursivamente
' filterPattern: patrones de archivo separados por ; (ej: "*.xlsx;*.xlsm")
' eventsToWatch: array de eventos a monitorear ("Created","Deleted","Changed","Renamed")
' inactivityMinutes: tiempo de inactividad antes de reinicio automático
' foldersOnly: TRUE para monitorear solo cambios en subcarpetas, no archivos
Public Sub IniciarMonitoreo(ByVal folderPath As String, _
Optional ByVal includeSubdirs As Boolean = True, _
Optional ByVal filterPattern As String = "*.*", _
Optional ByVal eventsToWatch As Variant = Empty, _
Optional ByVal inactivityMinutes As Double = -1, _
Optional ByVal foldersOnly As Boolean = False)
On Error GoTo ErrHandler
If Not mInitialized Or mDisposed Then
Err.Raise vbObjectError + 600, MODULE_NAME, "Componente COM no inicializado o ya liberado"
End If
' Normalizar ruta
If Right(folderPath, 1) = "\" Then
folderPath = Left(folderPath, Len(folderPath) - 1)
End If
' Verificar que la carpeta existe
If Not RutaExiste(folderPath) Then
LogWarning MODULE_NAME, "[IniciarMonitoreo] - Ruta no existe, omitiendo monitoreo: " & folderPath
Exit Sub
End If
' Preparar eventos a monitorear
Dim eventos As Variant
If IsEmpty(eventsToWatch) Or Not IsArray(eventsToWatch) Then
eventos = Array("Created", "Deleted", "Renamed")
Else
eventos = eventsToWatch
End If
' Llamar al componente COM
fw.WatchFolder folderPath, includeSubdirs, filterPattern, eventos, inactivityMinutes, foldersOnly
' Registrar en diccionario local
If Not mWatchedFolders.Exists(folderPath) Then
mWatchedFolders.Add folderPath, Now
End If
LogDebug MODULE_NAME, "[IniciarMonitoreo] - Monitoreo iniciado: " & folderPath & IIf(foldersOnly, " (solo subcarpetas)", "")
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[IniciarMonitoreo] - Error al iniciar monitoreo de: " & folderPath, Err.Number, Err.Description
RaiseEvent ErrorOccurred(folderPath, Err.Description)
End Sub
'@Description: Detiene el monitoreo de una carpeta específica
Public Sub DetenerMonitoreo(ByVal folderPath As String)
On Error Resume Next
If mInitialized And Not mDisposed And Not fw Is Nothing Then
fw.StopWatching folderPath
End If
If Not mWatchedFolders Is Nothing Then
If mWatchedFolders.Exists(folderPath) Then
mWatchedFolders.Remove folderPath
End If
End If
LogInfo MODULE_NAME, "[DetenerMonitoreo] - Monitoreo detenido: " & folderPath
End Sub
'@Description: Detiene todos los monitoreos activos
'@Note: Este metodo es llamado por Dispose, usar Dispose para limpieza completa
Public Sub DetenerTodo()
On Error Resume Next
If mDisposed Then
LogDebug MODULE_NAME, "[DetenerTodo] - Objeto ya liberado"
Exit Sub
End If
If Not mWatchedFolders Is Nothing Then
Dim carpeta As Variant
Dim countStopped As Long
countStopped = 0
For Each carpeta In mWatchedFolders.Keys
If mInitialized And Not fw Is Nothing Then
fw.StopWatching CStr(carpeta)
countStopped = countStopped + 1
End If
Next carpeta
mWatchedFolders.RemoveAll
LogInfo MODULE_NAME, "[DetenerTodo] - " & countStopped & " monitoreos detenidos"
End If
End Sub
' =====================================================
' CONFIGURACIÓN DE FILTROS
' =====================================================
'@Description: Configura filtro por tamaño de archivo
Public Sub ConfigurarFiltroTamaño(ByVal folderPath As String, _
ByVal minSize As Long, _
ByVal maxSize As Long)
On Error GoTo ErrHandler
If Not mInitialized Or mDisposed Then Exit Sub
fw.SetFilter folderPath, FileFilterType.FileSize, minSize, maxSize
LogDebug MODULE_NAME, "[ConfigurarFiltroTamaño] - Filtro de tamaño: " & folderPath & " [" & minSize & "-" & maxSize & "]"
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[ConfigurarFiltroTamaño] - Error: " & folderPath, Err.Number, Err.Description
End Sub
'@Description: Configura filtro por fecha de archivo
Public Sub ConfigurarFiltroFecha(ByVal folderPath As String, _
ByVal compareDate As Date, _
ByVal dateMode As DateCompareMode)
On Error GoTo ErrHandler
If Not mInitialized Or mDisposed Then Exit Sub
fw.SetFilter folderPath, FileFilterType.fileDate, 0, 0, compareDate, dateMode
Dim strFilt
Select Case dateMode
Case CreatedAfter: strFilt = "creac. > " & compareDate
Case CreatedBefore: strFilt = "modif. < " & compareDate
Case ModifiedAfter: strFilt = "creac. > " & compareDate
Case ModifiedBefore: strFilt = "modif. < " & compareDate
End Select
LogDebug MODULE_NAME, "[ConfigurarFiltroFecha] - Filtro de fecha configurado, " & strFilt & " en: " & folderPath
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[ConfigurarFiltroFecha] - Error: " & folderPath, Err.Number, Err.Description
End Sub
'@Description: Configura filtro para monitorear solo carpetas
Public Sub ConfigurarFiltroSoloCarpetas(ByVal folderPath As String)
On Error GoTo ErrHandler
If Not mInitialized Or mDisposed Then Exit Sub
fw.SetFilter folderPath, FileFilterType.foldersOnly
LogDebug MODULE_NAME, "[ConfigurarFiltroSoloCarpetas] - Filtro solo carpetas en: " & folderPath
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[ConfigurarFiltroSoloCarpetas] - Error: " & folderPath, Err.Number, Err.Description
End Sub
'@Description: Limpia todos los filtros de una carpeta
Public Sub LimpiarFiltros(ByVal folderPath As String)
On Error Resume Next
If mInitialized And Not mDisposed Then fw.ClearFilter folderPath
End Sub
' =====================================================
' CONFIGURACIÓN DE ACCIONES AUTOMÁTICAS
' =====================================================
'@Description: Configura acción de mover archivos automáticamente
Public Sub ConfigurarAccionMover(ByVal folderPath As String, _
ByVal targetFolder As String)
On Error GoTo ErrHandler
If Not mInitialized Or mDisposed Then Exit Sub
fw.SetAutoAction folderPath, AutoActionType.MoveFile, targetFolder
LogDebug MODULE_NAME, "[ConfigurarAccionMover] - Accion mover configurada: " & folderPath & " -> " & targetFolder
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[ConfigurarAccionMover] - Error", Err.Number, Err.Description
End Sub
'@Description: Configura acción de copiar archivos automáticamente
Public Sub ConfigurarAccionCopiar(ByVal folderPath As String, _
ByVal targetFolder As String)
On Error GoTo ErrHandler
If Not mInitialized Or mDisposed Then Exit Sub
fw.SetAutoAction folderPath, AutoActionType.CopyFile, targetFolder
LogDebug MODULE_NAME, "[ConfigurarAccionCopiar] - Accion copiar configurada: " & folderPath & " -> " & targetFolder
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[ConfigurarAccionCopiar] - Error", Err.Number, Err.Description
End Sub
'@Description: Configura acción de archivar con timestamp
Public Sub ConfigurarAccionArchivar(ByVal folderPath As String, _
ByVal archiveFolder As String)
On Error GoTo ErrHandler
If Not mInitialized Or mDisposed Then Exit Sub
fw.SetAutoAction folderPath, AutoActionType.Archive, archiveFolder
LogDebug MODULE_NAME, "[ConfigurarAccionArchivar] - Accion archivar configurada: " & folderPath & " -> " & archiveFolder
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[ConfigurarAccionArchivar] - Error", Err.Number, Err.Description
End Sub
'@Description: Limpia acciones automáticas de una carpeta
Public Sub LimpiarAcciones(ByVal folderPath As String)
On Error Resume Next
If mInitialized And Not mDisposed Then fw.ClearAutoAction folderPath
End Sub
' =====================================================
' PROPIEDADES Y CONSULTAS
' =====================================================
Public Property Get Configuracion() As String
On Error Resume Next
If mInitialized And Not mDisposed Then
Configuracion = fw.GetConfiguration()
Else
Configuracion = "(no inicializado o liberado)"
End If
End Property
Public Property Get CarpetasMonitoreadas() As Long
If mWatchedFolders Is Nothing Then
CarpetasMonitoreadas = 0
Else
CarpetasMonitoreadas = mWatchedFolders.Count
End If
End Property
Public Function CarpetasActivas() As Variant
On Error Resume Next
If mInitialized And Not mDisposed Then
CarpetasActivas = fw.ActiveFolders
Else
CarpetasActivas = Array()
End If
End Function
Public Function ObtenerHistorial(Optional ByVal lastMinutes As Long = 0, _
Optional ByVal eventType As String = "") As Variant
On Error Resume Next
If mInitialized And Not mDisposed Then
ObtenerHistorial = fw.GetEventHistory(lastMinutes, eventType)
Else
ObtenerHistorial = Array()
End If
End Function
Public Function ObtenerEstadisticas(ByVal folderPath As String) As Variant
On Error Resume Next
If mInitialized And Not mDisposed Then
ObtenerEstadisticas = fw.GetStatistics(folderPath)
Else
ObtenerEstadisticas = Array()
End If
End Function
Public Sub LimpiarHistorial()
On Error Resume Next
If mInitialized And Not mDisposed Then fw.ClearHistory
End Sub
' =====================================================
' MANEJADORES DE EVENTOS COM (propagan a VBA)
' =====================================================
Private Sub fw_FileCreated(ByVal folder As String, ByVal fileName As String)
LogDebug MODULE_NAME, "[callback: FolderWatcher.Monitor FileCreated] - " & fileName & " en " & folder
RaiseEvent FileCreated(folder, fileName)
End Sub
Private Sub fw_FileDeleted(ByVal folder As String, ByVal fileName As String)
LogDebug MODULE_NAME, "[callback: FolderWatcher.Monitor FileDeleted] - " & fileName & " en " & folder
RaiseEvent FileDeleted(folder, fileName)
End Sub
Private Sub fw_FileChanged(ByVal folder As String, ByVal fileName As String)
LogDebug MODULE_NAME, "[callback: FolderWatcher.Monitor FileChanged] - " & fileName & " en " & folder
RaiseEvent FileChanged(folder, fileName)
End Sub
Private Sub fw_FileRenamed(ByVal folder As String, ByVal oldName As String, ByVal newName As String)
LogDebug MODULE_NAME, "[callback: FolderWatcher.Monitor FileRenamed] - " & oldName & " -> " & newName & " en " & folder
RaiseEvent FileRenamed(folder, oldName, newName)
End Sub
Private Sub fw_Heartbeat(ByVal folder As String, ByVal lastUpdate As Date)
' Heartbeat es muy frecuente, no logear para evitar ruido
RaiseEvent Heartbeat(folder, lastUpdate)
End Sub
Private Sub fw_ErrorOccurred(ByVal folder As String, ByVal errorMessage As String)
LogError MODULE_NAME, "[callback: FolderWatcher.Monitor ErrorOccurred] - Error COM en " & folder & ": " & errorMessage
RaiseEvent ErrorOccurred(folder, errorMessage)
End Sub
' Manejadores para eventos de subcarpetas
Private Sub fw_SubfolderCreated(ByVal parentFolder As String, ByVal subfolderName As String)
LogDebug MODULE_NAME, "[callback: FolderWatcher.Monitor SubfolderCreated] - " & subfolderName & " en " & parentFolder
RaiseEvent SubfolderCreated(parentFolder, subfolderName)
End Sub
Private Sub fw_SubfolderDeleted(ByVal parentFolder As String, ByVal subfolderName As String)
LogDebug MODULE_NAME, "[callback: FolderWatcher.Monitor SubfolderDeleted] - " & subfolderName & " en " & parentFolder
RaiseEvent SubfolderDeleted(parentFolder, subfolderName)
End Sub
Private Sub fw_SubfolderRenamed(ByVal parentFolder As String, ByVal oldName As String, ByVal newName As String)
LogDebug MODULE_NAME, "[callback: FolderWatcher.Monitor SubfolderRenamed] - " & oldName & " -> " & newName & " en " & parentFolder
RaiseEvent SubfolderRenamed(parentFolder, oldName, newName)
End Sub
' Manejadores para eventos de reconexión automática
Private Sub fw_WatcherReconnected(ByVal folder As String, ByVal attempts As Long)
LogDebug MODULE_NAME, "[callback: FolderWatcher.Monitor WatcherReconnected] - " & folder & " (tras " & attempts & " intento(s))"
RaiseEvent WatcherReconnected(folder, attempts)
End Sub
Private Sub fw_WatcherReconnectionFailed(ByVal folder As String, ByVal reason As String)
LogError MODULE_NAME, "[callback: FolderWatcher.Monitor WatcherReconnectionFailed] - " & folder & " - " & reason
RaiseEvent WatcherReconnectionFailed(folder, reason)
End Sub
' =====================================================
' FUNCIONES DE UTILIDAD
' =====================================================
'@Description: Obtiene la ruta donde debería estar el COM (carpeta AddIns)
Private Function ObtenerRutaCOM() As String
ObtenerRutaCOM = Application.UserLibraryPath & FOLDERWATCHERCOM_NAME
End Function
'@Description: Obtiene la ruta donde debería estar el manifest (carpeta AddIns)
Private Function ObtenerRutaManifest() As String
ObtenerRutaManifest = Application.UserLibraryPath & FOLDERWATCHERCOM_NAME & ".manifest"
End Function
'@Description: Verifica si los archivos del COM están presentes
Private Function ComprobarArchivosCOM() As Boolean
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
ComprobarArchivosCOM = fso.FileExists(ObtenerRutaCOM()) And _
fso.FileExists(ObtenerRutaManifest())
Set fso = Nothing
End Function
' =====================================================
' FUNCIONES DE TEST Y DEBUGGING
' =====================================================
'@Description: Test de monitoreo de subcarpetas
Public Sub Test_MonitoreoSubcarpetas()
Dim rutaTest As String
rutaTest = Environ("TEMP") & "\TestFolderWatcher"
' Crear carpeta de test si no existe
If Not RutaExiste(rutaTest) Then
MkDir rutaTest
End If
' Configurar monitoreo
IniciarMonitoreo _
folderPath:=rutaTest, _
includeSubdirs:=False, _
filterPattern:="*", _
eventsToWatch:=Array("Created", "Deleted", "Renamed"), _
inactivityMinutes:=5, _
foldersOnly:=True
ConfigurarFiltroSoloCarpetas rutaTest
MsgBox "Monitoreo de test iniciado en:" & vbCrLf & rutaTest & vbCrLf & vbCrLf & _
"Ahora crea, renombra o elimina subcarpetas para probar.", vbInformation
End Sub
'@Description: Test de filtros de tamaño
Public Sub Test_FiltroTamaño()
Dim rutaTest As String
rutaTest = Environ("TEMP") & "\TestFiltros"
If Not RutaExiste(rutaTest) Then
MkDir rutaTest
End If
' Monitorear solo archivos mayores a 1 KB
IniciarMonitoreo _
folderPath:=rutaTest, _
includeSubdirs:=False, _
filterPattern:="*.*", _
eventsToWatch:=Array("Created"), _
inactivityMinutes:=5
ConfigurarFiltroTamaño rutaTest, 1024, 999999999
MsgBox "Monitoreo con filtro de tamaño iniciado en:" & vbCrLf & rutaTest & vbCrLf & vbCrLf & _
"Solo detectará archivos mayores a 1 KB", vbInformation
End Sub
'@Description: Test de acción automática de mover
Public Sub Test_AccionMover()
Dim rutaOrigen As String, rutaDestino As String
rutaOrigen = Environ("TEMP") & "\TestOrigen"
rutaDestino = Environ("TEMP") & "\TestDestino"
' Crear carpetas si no existen
If Not RutaExiste(rutaOrigen) Then MkDir rutaOrigen
If Not RutaExiste(rutaDestino) Then MkDir rutaDestino
' Configurar monitoreo con acción de mover
IniciarMonitoreo _
folderPath:=rutaOrigen, _
includeSubdirs:=False, _
filterPattern:="*.txt", _
eventsToWatch:=Array("Created"), _
inactivityMinutes:=5
ConfigurarAccionMover rutaOrigen, rutaDestino
MsgBox "Test de acción automática iniciado:" & vbCrLf & _
"Origen: " & rutaOrigen & vbCrLf & _
"Destino: " & rutaDestino & vbCrLf & vbCrLf & _
"Los archivos .txt se moverán automáticamente", vbInformation
End Sub
'@Description: Test completo del sistema
Public Sub Test_SistemaCompleto()
Debug.Print "==== TEST COMPLETO FOLDERWATCHER ===="
Debug.Print "Configuración: " & Configuracion
Dim carpetas As Variant
carpetas = CarpetasActivas()
Debug.Print "Carpetas monitoreadas: " & IIf(IsArray(carpetas), UBound(carpetas) + 1, 0)
If IsArray(carpetas) Then
Dim i As Long
For i = LBound(carpetas) To UBound(carpetas)
Debug.Print " " & i & ": " & carpetas(i)
Dim stats As Variant
stats = ObtenerEstadisticas(CStr(carpetas(i)))
If IsArray(stats) Then
Debug.Print " Eventos: " & stats(1) & " | Última actividad: " & stats(6)
End If
Next i
End If
Debug.Print "==== FIN TEST ===="
End Sub