-
Notifications
You must be signed in to change notification settings - Fork 14
/
lgkemilv3child.groovy
717 lines (592 loc) · 26 KB
/
lgkemilv3child.groovy
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
714
715
716
717
/**
* simple sendmail .. lg kahn [email protected]
* child sendmail device
*/
attribute "lastCommand", "string"
attribute "myHostName", "string"
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import groovy.transform.Field
import groovy.xml.XmlUtil
@Field static java.util.concurrent.Semaphore lastStateMutex = new java.util.concurrent.Semaphore(1)
preferences {
}
metadata {
definition (name: "LGK Sendmail V3 Child", namespace: "lgkapps", author: "larry kahn [email protected]") {
}
}
def installed() {
initialize()
}
def updated() {
initialize()
}
def configure()
{
initialize()
}
def logsOff()
{
log.debug "Turning off Logging!"
device.updateSetting("debug",[value:"false",type:"bool"])
}
def forceFailure()
{
// used for testing for a bad state
synchronized (lastStateMutex) { state.lastCommand = "Failed" }
sendEvent(name: "lastCommand", value: "Failed")
}
def initialize() {
state.debug = false
state.descLog = false
state.lastMsg = ""
state.LastCode = 0
state.EmailBody = ""
state.lastCommand = "quit"
def ld = parent.getDebug()
state.debug = ld
state.descLog = parent.getDescLog()
if (state.debug) log.debug "in child initialize"
if (state.debug)
{
log.debug "parent debug = ${parent.getDebug()}"
log.debug "parent host = ${parent.getMyHostName()}"
}
def myHostname = parent.getMyHostName()
if ((!myHostName) || (myHostName == ""))
{
if (state.debug) log.info "User specified hostname is blank using IP instead."
def hub = location.hubs[0]
def myName = "[" + hub.getDataValue("localIP") + "]"
state.myHostName = myName
sendEvent(name: "myHostName", value: myName)
}
else
{
state.myHostName = myHostName
sendEvent(name: "myHostName", value: myHostName)
}
if (state.debug || state.descLog)
{
if (state.descLog) log.info "Descriptive Text logging is on."
else log.info "Description Text logging is off."
}
if (state.debug)
{
log.info "Debug logging is on. Turning off debug logging in 1/2 hour."
runIn(1800,logsOff)
}
else if (state.debug) log.info "Debug logging is off."
}
int DnitoID()
{
// get my id and store in the state to use to past back status to parent.
String dni = device.deviceNetworkId
// no parse it
def pair = dni.split("-")
def String myId = pair[1]
def int intid = myId.toInteger()
return intid
}
def sendMessage(String message)
{
def ld = parent.getDebug()
state.debug = ld
state.descLog = parent.getDescLog()
deviceNotification(message)
}
def cleanUp()
{
if (state.debug) log.debug "In cleanup ... called from parent!"
unschedule()
sendEvent(name: "lastCommand", value: "Force Closed")
synchronized (lastStateMutex) { state.lastCommand = "Force Closed" }
initialize()
}
def resetData()
{
unschedule()
sendEvent(name: "lastCommand", value: "Force Closed")
synchronized (lastStateMutex) { state.lastCommand = "Force Closed" }
//uppdate status of parent.
def int intId = DnitoID()
if (state.debug) log.debug "My internal id = $intId"
parent.updateStatus(intId,"Failed")
// if debuging on redo the job to turn off
if (state.debug)
{
log.info "Debug logging is on. Turning off debug logging in 1/2 hour."
runIn(1800,logsOff)
}
}
def deviceNotification(String message) {
def version = parent.getVersion()
def Boolean goOn = true
state.messageSent = false
sendEvent(name: "telnet", value: "Ok")
synchronized (lastStateMutex)
{
if (state.lastCommand == null) state.lastCommand = "quit"
}
if (state.debug) log.debug "-------> In lgk sendmail Version ($version)"
// lgk now check if we are already in middle of a message and if so wait for a minute.. if after that we still are force close the connection and resume this
// message
def oldState
synchronized (lastStateMutex) { oldState = state.lastCommand }
if (state.debug) log.debug "Initial state found: ($oldState)"
if (!((oldState == "Sent Ok") || (oldState == "Send Failed") || (oldState == "Connection Closed") || (oldState == "quit") || (oldState == "Force Closed")))
{
log.info "Existing state ($oldState) is incorrect for processing. Resetting and aborting!"
resetData()
goOn = false
}
if (goOn)
{
if (state.debug) log.debug "Found ok initial state ($oldState) ... going on!"
synchronized (lastStateMutex) { state.lastCommand = "initialConnect"
sendEvent(name: "lastCommand", value: "initialConnect")
}
if (state.debug) synchronized (lastStateMutex) { log.debug "set last command to $state.lastCommand" }
state.EmailBody = "${message}"
state.LastCode = 0
def String EmailServer = parent.getEmailServer()
def String EmailPort = parent.getEmailPort()
if (state.debug) log.debug "Connecting to ${EmailServer}:${EmailPort}"
// handle failed connect probabaly due to bad ip address
try {
closeConnection()
telnetConnect(EmailServer, EmailPort.toInteger(), null, null)
} catch(e) {
log.error "Connect failed. Either your internet is down or check the ip address of your Server:Port: $EmailServer:$EmailPort !"
resetData()
}
}
}
def sendData(String msg, Integer millsec) {
if (state.debug) log.debug "$msg"
def hubCmd = sendHubCommand(new hubitat.device.HubAction("${msg}", hubitat.device.Protocol.TELNET))
pauseExecution(millsec)
return hubCmd
}
def parse(String msg) {
def lastCommand
def String Username = parent.getUsername()
def String Password = parent.getPassword()
def boolean Authenticate = parent.getAuthenticate()
synchronized (lastStateMutex) { lastCommand = state.lastCommand }
if (state.debug) {
log.debug "In parse - ${msg}"
log.debug "lastCommand = $lastCommand"
}
def first4 = msg.substring(0,4)
if ((first4 == "250-") || (first4 == "220-"))
{
if (state.debug) log.debug "Skipping informational command: $msg."
}
else
{
def pair = msg.split(" ")
def response = pair[0]
def value = pair[1]
if (state.debug) log.debug "Got server response $response value = $value lastCommand = ($lastCommand)"
if (lastCommand == "initialConnect")
{
if (state.debug) log.debug "In initialConnect case"
if (response == "220")
{
sendEvent([name: "telnet", value: "Ok"])
if (parent.getRequiresEHLO())
{
if (state.debug) log.debug "Using EHLO instead of HELO!"
synchronized (lastStateMutex) { state.lastCommand = "ehlo" }
sendEvent(name: "lastCommand", value: "ehlo")
def res1 = sendData("ehlo $state.myHostName",500)
}
else
{
synchronized (lastStateMutex) { state.lastCommand = "helo" }
sendEvent(name: "lastCommand", value: "helo")
def res1 = sendData("helo $state.myHostName",500)
}
}
else
{
closeOnError()
}
}
else if (lastCommand == "Auth")
{
if (state.debug) log.debug "In auth response looking for 334"
if (response == "334")
{
if (state.debug) log.debug "Got auth response now sending username"
synchronized (lastStateMutex) { state.lastCommand = "Username" }
sendEvent(name: "lastCommand", value: "Username")
def res1 = sendData("$Username",500)
}
else
{
log.debug "Got bad response for auth = $response"
synchronized (lastStateMutex) { state.lastCommand = "Send Failed" }
sendEvent(name: "lastCommand", value: "Send Failed")
closeConnection()
}
}
else if (lastCommand == "Username")
{
if (state.debug) log.debug "In Username response looking for 334"
if (response == "334")
{
if (state.debug) log.debug "Got username response now sending password"
synchronized (lastStateMutex) { state.lastCommand = "Password" }
sendEvent(name: "lastCommand", value: "Password")
def res1 = sendData("$Password",500)
}
else
{
log.debug "Got bad response for Username = $response"
synchronized (lastStateMutex) { state.lastCommand = "Send Failed" }
sendEvent(name: "lastCommand", value: "Send Failed")
closeConnection()
}
}
else if ((lastCommand == "helo") || (lastCommand == "ehlo") || (lastCommand == "Password"))
{
if (state.debug) log.debug "In helo/ehlo/Password case"
if ((response == "250") || (response == "235"))
{
if (((lastCommand == "helo") || (lastCommand == "ehlo")) && (Authenticate) && (Username) && (Password))
{
if (state.debug) log.debug "Trying authentication"
synchronized (lastStateMutex) { state.lastCommand = "Auth" }
sendEvent(name: "lastCommand", value: "Auth")
def res1 = sendData("auth login",500)
}
else
{
if (state.debug) log.debug "Either got 250 for helo or 235 for password, Now Sending Message or ehlo"
synchronized (lastStateMutex) { state.lastCommand = "sendmessage" }
sendEvent(name: "lastCommand", value: "sendmessage")
def msgData = "${state.EmailBody}"
def emlBody = ""
def emlSubject = ""
def emlDateTime = new Date().format('EEE, dd MMM YYYY H:mm:ss Z',location.timeZone)
def String idP1 = now()
def String idP2 = java.util.UUID.randomUUID().toString().replaceAll('-', '')
def String msgId = '<' + idP2 + "." + idP1 + "@2LGKSendmailV3>"
def String Subject = parent.getSubject()
def String From = parent.getFrom()
def String To = parent.getTo()
def toReplaced = false
def cc = ""
def ccFound = false
/* if(msgData.substring(0,1) == "{") {
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(msgData)
emlBody = result.Body
emlSubject = (result.Subject != null ? result.Subject : "")
} else {
*/
emlBody = msgData
emlSubject = (Subject != null ? "${Subject}" : "")
// }
// note order is important here from, to, subject,cc
if (state.debug) log.debug "before check for header replacment, subject = $emlSubject, body = $emlBody, from = $From, To = $To"
if (emlBody.startsWith("rh-From:") && emlBody.indexOf(",") > -1)
{
def io = emlBody.indexOf(",")
def len = emlBody.length()
if (state.debug) log.debug "found replace header for From! index = $io, len = $len"
def newFrom = emlBody.substring(0,io)
def messageSplit = emlBody.substring(io+1,len)
From = newFrom.replace("rh-From: ", "").replace("rh-From:", "")
emlBody = messageSplit.trim()
}
if (emlBody.startsWith("rh-To:") && emlBody.indexOf(",") > -1)
{
def io = emlBody.indexOf(",")
def len = emlBody.length()
if (state.debug) log.debug "found replace header for To! index = $io, len = $len"
def newTo = emlBody.substring(0,io)
def messageSplit = emlBody.substring(io+1,len)
To = newTo.replace("rh-To: ", "").replace("rh-To:", "")
emlBody = messageSplit.trim()
toReplaced = true
}
if (emlBody.startsWith("rh-Subject:") && emlBody.indexOf(",") > -1)
{
def io = emlBody.indexOf(",")
def len = emlBody.length()
if (state.debug) log.debug "found replace header for Subject!"
def newSubject = emlBody.substring(0,io)
def messageSplit = emlBody.substring(io+1,len)
emlSubject = newSubject.replace("rh-Subject: ", "").replace("rh-Subject:", "")
emlBody = messageSplit.trim()
}
if (emlBody.startsWith("Subject:") && emlBody.indexOf(",") > -1)
{
def io = emlBody.indexOf(",")
def len = emlBody.length()
if (state.debug) log.debug "found replace header for Subject!"
def newSubject = emlBody.substring(0,io)
def messageSplit = emlBody.substring(io+1,len)
emlSubject = newSubject.replace("Subject: ", "").replace("Subject:", "")
emlBody = messageSplit.trim()
}
if (emlBody.startsWith("rh-CC:") && emlBody.indexOf(",") > -1)
{
def io = emlBody.indexOf(",")
def len = emlBody.length()
if (state.debug) log.debug "found replace header for CC!"
def newCC = emlBody.substring(0,io)
def messageSplit = emlBody.substring(io+1,len)
cc = newCC.replace("rh-CC: ", "")replace("rh-CC:", "")
emlBody = messageSplit.trim()
ccFound = true
}
if (state.debug) log.debug "After check new subject = *${emlSubject}*, new body = $emlBody, newTo = *${To}*, new From = *${From}*, CC = *${cc}"
// handle bracket case for ehader replacement
if (emlBody.startsWith("{"))
{
def newFrom = ""
def newTo = ""
def newCC = ""
def newSubject = ""
def newMessage = ""
def headers = ""
def body = ""
if (state.debug) log.debug "found header directive start {."
// now find end and separate
def sMsg = emlBody.split("}")
emlBody = emlBody.replace("{", "")
if (state.debug) log.debug "size = ${sMsg.size()}"
if (sMsg.size() == 2)
{
// now strip out comma on message
def cMsg = sMsg[1].split(",")
headers = sMsg[0]
body = cMsg[1]
if (state.debug) log.debug "left side (headers) = $headers, right side (msg} = ${cMsg[1]}, body = $body"
}
else
{
// message must be inside
headers = sMsg[0]
if (state.debug) log.debug "left side (headers) = $headers, right side blank (message must be in options)!"
}
//emlBody = cMSg[1]
headers = headers.replace("}", "")
headers = headers.replace("{", "")
def headerSplit = headers.split(",")
if (state.debug) log.debug "header split = ${headerSplit} size = ${headerSplit.size()}"
for (int i = 0; i < headerSplit.size(); i++)
{
def headerPart = headerSplit[i]
def headerPartSplit = headerPart.split(":")
if (state.debug) log.debug "part = ${headerPart}"
if (headerPart.contains("To"))
{
def dh = headerPart.split(":")
if (dh.size() == 2) newTo = dh[1].trim()
}
if (headerPart.contains("Subject"))
{
def dh = headerPart.split(":")
if (dh.size() == 2) newSubject = dh[1].trim()
}
if (headerPart.contains("From"))
{
def dh = headerPart.split(":")
if (dh.size() == 2) newFrom = dh[1].trim()
}
if (headerPart.contains("CC"))
{
def dh = headerPart.split(":")
if (dh.size() == 2) newCC = dh[1].trim()
}
if (headerPart.contains("Message"))
{
def dh = headerPart.split(":")
if (dh.size() == 2) newMessage = dh[1].trim()
}
} // loop
if (state.debug) log.debug "newFrom = *${newFrom}*, newTo = *${newTo}*, newSubject = *${newSubject}* newCC = *${newCC}* newMessage = *${newMessage}*"
// now handle using the new fields if there
if (newFrom != "") From = newFrom
if (newTo != "") To = newTo
if (newSubject != "") emlSubject = newSubject
if (newMessage != "") emlBody = newMessage
else emlBody = body
if (newCC != "")
{
cc = newCC
ccFound = true
}
} // starts with }
def toList = To.split(",")
def toListSize = toList.size()
if (state.debug) log.debug "Number of To addresses = $toListSize"
if (state.debug) log.debug "From = ${From}, To = ${To}, Subject = ${emlSubject}"
def sndMsg =[
"MAIL FROM: <${From}>" ]
if (toListSize > 1)
{
for (ctr= 0; ctr < toListSize; ctr++)
{
def oneToAddress = toList[ctr].replaceAll(' ','')
if (state.debug) log.debug "one email address = *$oneToAddress*"
sndMsg = sndMsg + [ "RCPT TO: <${oneToAddress}>" ]
}
}
else
{
sndMsg = sndMsg + [ "RCPT TO: <${To}>" ]
}
if (ccFound)
{
sndMsg = sndMsg + [ "RCPT TO: <${cc}>" ]
sndMsg = sndMsg +
[ "DATA"
, "From: ${From}"
, "To: ${To}"
, "CC: ${cc}"
, "Date: ${emlDateTime}"
, "Message-ID: ${msgId}"
, "Subject: ${emlSubject}"
, "MIME-Version: 1.0"
, 'Content-Type: text/plain; charset="utf-8"'
, "Content-Transfer-Encoding: quoted-printable\r\n"
, ""
, "${emlBody}"
, ""
, "."
, "quit"
]
}
else
{
sndMsg = sndMsg +
[ "DATA"
, "From: ${From}"
, "To: ${To}"
, "Date: ${emlDateTime}"
, "Message-ID: ${msgId}"
, "Subject: ${emlSubject}"
, "MIME-Version: 1.0"
, 'Content-Type: text/plain; charset="utf-8"'
, "Content-Transfer-Encoding: quoted-printable\r\n"
, ""
, "${emlBody}"
, ""
, "."
, "quit"
]
}
def res1 = seqSend(sndMsg,500)
state.messageSent = true
if (state.debug || state.descLog) log.info "Sent Message: $emlBody"
// call parent to update status
def int intId = DnitoID()
if (state.debug) log.debug "My internal id = $intId"
parent.updateStatus(intId,"Completed")
}
}
else
{
closeOnError()
}
}
else if (lastCommand == "sendmessage")
{
if (state.debug) log.debug "In send message case"
if ((response == "220") || (response == "250"))
{
if (state.debug) log.info "sending quit"
synchronized (lastStateMutex) { state.lastCommand = "quit" }
sendEvent(name: "lastCommand", value: "quit")
def res1 = sendData("quit",500)
}
else
{
closeOnError()
}
}
else if ((lastCommand == "quit") || ((response == "221") && (lastCommand == "other")))
//&& ((value == "bye") || (value == "2.0.0") || (value = "Goodbye"))))
{
if (state.debug) log.debug "In quit case"
if (response == "220" || response == "221" || response == "250")
{
if (state.messageSent)
{
synchronized (lastStateMutex) { state.lastCommand = "Sent Ok" }
sendEvent(name: "lastCommand", value: "Sent Ok")
}
closeConnection()
}
else
{
closeOnError()
}
}
else
{
if (response == "250" || response == "354")
//|| response == "221")
{
synchronized (lastStateMutex) { state.lastCommand = "other" }
sendEvent(name: "lastCommand", value: "other")
}
else
{
closeOnError()
}
}
}
}
def telnetStatus(status) {
// comment out telent status as it is not working correctly and the system is telling me the socket is closed and other
// response are still returned on the socket after. ignore stream is closed errors.
if (status != "receive error: Stream is closed")
{
if (state.debug) synchronized (lastStateMutex) { log.debug "telnetStatus: ${status} lastcommand is ($state.lastCommand)" }
sendEvent([name: "telnet", value: "${status}"])
}
}
def closeConnection()
{
if (closeTelnet){
try {
log.error "Calling telnet close now!!!!"
telnetClose()
synchronized (lastStateMutex) { state.lastCommand = "Connection Closed" }
sendEvent(name: "lastCommand", value: "Connection Closed")
} catch(e) {
if (state.debug) log.debug("Connection Closed")
}
}
}
boolean seqSend(msgs, Integer millisec)
{
if (state.debug) log.debug "in sendData, message = ${msgs}"
msgs.each {
sendData("${it}",millisec)
}
seqSent = true
return seqSent
}
def closeOnError()
{
log.debug "Got bad response = $response"
synchronized (lastStateMutex) { state.lastCommand = "Send Failed" }
sendEvent(name: "lastCommand", value: "Send Failed")
closeConnection()
}
void uninstalled() {
try {
log.debug("Child: ${device.getName()} - (${device.getDeviceNetworkId()}) Deleted.");
}
catch (Exception e) {
log.error("Exception in uninstalled(): ${e}");
}
}