forked from Bart274/icloudplatform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
icloud.py
956 lines (860 loc) · 39.9 KB
/
icloud.py
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
"""
Platform that supports scanning iCloud.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/icloud/
"""
import logging
from datetime import datetime, timedelta
from math import floor
import random
import voluptuous as vol
from pytz import timezone
import pytz
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD
from homeassistant.helpers.entity import (Entity, generate_entity_id)
from homeassistant.components.device_tracker import see
from homeassistant.helpers.event import (track_state_change,
track_utc_time_change)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import slugify
import homeassistant.util.dt as dt_util
from homeassistant.util.location import distance
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pyicloud==0.9.1']
DEPENDENCIES = ['zone', 'device_tracker']
CONF_EVENTS = 'events'
DEFAULT_EVENTS = False
CONF_IGNORED_DEVICES = 'ignored_devices'
CONF_GMTT = 'google_maps_travel_time'
CONF_COOKIEDIRECTORY = 'cookiedirectory'
# entity attributes
ATTR_ACCOUNTNAME = 'account_name'
ATTR_INTERVAL = 'interval'
ATTR_DEVICENAME = 'device_name'
ATTR_BATTERY = 'battery'
ATTR_DISTANCE = 'distance'
ATTR_STARTTIME = 'start_time'
ATTR_ENDTIME = 'end_time'
ATTR_DURATION = 'duration'
ATTR_REMAINING = 'remaining_time'
ATTR_DEVICESTATUS = 'device_status'
ATTR_LOWPOWERMODE = 'low_power_mode'
ATTR_BATTERYSTATUS = 'battery_status'
ATTR_LOCATION = 'location'
ATTR_FRIENDLY_NAME = 'friendly_name'
ATTR_GOOGLE_MAPS_TRAVEL_TIME = 'google_maps_travel_time'
ATTR_GOOGLE_MAPS_TRAVEL_TIME_DURATION = 'gmtt_duration'
ATTR_GOOGLE_MAPS_TRAVEL_TIME_ORIGIN = 'gmtt_origin'
ATTR_CURRENT_EVENTS = 'current_events'
ATTR_NEXT_EVENTS = 'next_events'
TYPE_CURRENT = 'currentevent'
TYPE_NEXT = 'nextevent'
ICLOUDTRACKERS = {}
DOMAIN = 'icloud'
DOMAIN2 = 'idevice'
DOMAIN3 = 'ievent'
ENTITY_ID_FORMAT_ICLOUD = DOMAIN + '.{}'
ENTITY_ID_FORMAT_DEVICE = DOMAIN2 + '.{}'
ENTITY_ID_FORMAT_EVENT = DOMAIN3 + '.{}'
DEVICESTATUSSET = ['features', 'maxMsgChar', 'darkWake', 'fmlyShare',
'deviceStatus', 'remoteLock', 'activationLocked',
'deviceClass', 'id', 'deviceModel', 'rawDeviceModel',
'passcodeLength', 'canWipeAfterLock', 'trackingInfo',
'location', 'msg', 'batteryLevel', 'remoteWipe',
'thisDevice', 'snd', 'prsId', 'wipeInProgress',
'lowPowerMode', 'lostModeEnabled', 'isLocating',
'lostModeCapable', 'mesg', 'name', 'batteryStatus',
'lockedTimestamp', 'lostTimestamp', 'locationCapable',
'deviceDisplayName', 'lostDevice', 'deviceColor',
'wipedTimestamp', 'modelDisplayName', 'locationEnabled',
'isMac', 'locFoundEnabled']
SERVICE_SCHEMA = vol.Schema({
vol.Optional(ATTR_ACCOUNTNAME): cv.string,
vol.Optional(ATTR_DEVICENAME): cv.string,
vol.Optional(ATTR_INTERVAL): cv.positive_int,
})
ACCOUNT_SCHEMA = vol.Schema({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_COOKIEDIRECTORY, default=None): cv.string,
vol.Optional(CONF_EVENTS, default=DEFAULT_EVENTS): cv.boolean,
vol.Optional(CONF_IGNORED_DEVICES, default=[]):
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_GMTT, default={}):
vol.Schema({cv.string: cv.string}),
}, extra=vol.ALLOW_EXTRA)
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(cv.slug): ACCOUNT_SCHEMA,
})
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config): # pylint: disable=too-many-locals,too-many-branches
"""Set up the iCloud Scanner."""
for account, account_config in config[DOMAIN].items():
# Get the username and password from the configuration
username = account_config.get(CONF_USERNAME)
password = account_config.get(CONF_PASSWORD)
cookiedirectory = account_config.get(CONF_COOKIEDIRECTORY)
getevents = account_config.get(CONF_EVENTS, DEFAULT_EVENTS)
ignored_devices = []
ignored_dev = account_config.get(CONF_IGNORED_DEVICES)
for each_dev in ignored_dev:
ignored_devices.append(each_dev)
googletraveltime = {}
gttconfig = account_config.get(CONF_GMTT)
for google, googleconfig in gttconfig.items():
googletraveltime[google] = googleconfig
icloudaccount = Icloud(hass, username, password, cookiedirectory,
account, ignored_devices, getevents,
googletraveltime)
icloudaccount.update_ha_state()
ICLOUDTRACKERS[account] = icloudaccount
if ICLOUDTRACKERS[account].api is not None:
for device in ICLOUDTRACKERS[account].devices:
iclouddevice = ICLOUDTRACKERS[account].devices[device]
devicename = iclouddevice.devicename.lower()
track_state_change(hass,
'device_tracker.' + devicename,
iclouddevice.devicechanged)
if not ICLOUDTRACKERS:
_LOGGER.error("No ICLOUDTRACKERS added")
return False
randomseconds = random.randint(10, 59)
def lost_iphone(call):
"""Call the lost iphone function if the device is found."""
accountname = call.data.get(ATTR_ACCOUNTNAME)
devicename = call.data.get(ATTR_DEVICENAME)
if accountname is None:
for account in ICLOUDTRACKERS:
ICLOUDTRACKERS[account].lost_iphone(devicename)
elif accountname in ICLOUDTRACKERS:
ICLOUDTRACKERS[accountname].lost_iphone(devicename)
hass.services.register(DOMAIN, 'lost_iphone',
lost_iphone)
def update_icloud(call):
"""Call the update function of an icloud account."""
accountname = call.data.get(ATTR_ACCOUNTNAME)
devicename = call.data.get(ATTR_DEVICENAME)
if accountname is None:
for account in ICLOUDTRACKERS:
ICLOUDTRACKERS[account].update_icloud(devicename)
elif accountname in ICLOUDTRACKERS:
ICLOUDTRACKERS[accountname].update_icloud(devicename)
hass.services.register(DOMAIN,
'update_icloud', update_icloud)
def keep_alive(now):
"""Keep the api logged in of all account."""
for accountname in ICLOUDTRACKERS:
try:
ICLOUDTRACKERS[accountname].keep_alive()
except ValueError:
_LOGGER.error("something went wrong for account %s, " +
"retrying in a minute", accountname)
track_utc_time_change(
hass, keep_alive,
second=randomseconds
)
def setinterval(call):
"""Call the update function of an icloud account."""
accountname = call.data.get(ATTR_ACCOUNTNAME)
interval = call.data.get(ATTR_INTERVAL)
devicename = call.data.get(ATTR_DEVICENAME)
if accountname is None:
for account in ICLOUDTRACKERS:
ICLOUDTRACKERS[account].setinterval(interval, devicename)
elif accountname in ICLOUDTRACKERS:
ICLOUDTRACKERS[accountname].setinterval(interval, devicename)
hass.services.register(DOMAIN,
'setinterval', setinterval)
# Tells the bootstrapper that the component was successfully initialized
return True
class IDevice(Entity): # pylint: disable=too-many-instance-attributes
"""Represent an iDevice in Home Assistant."""
def __init__(self, hass, icloudobject, name, identifier, googletraveltime):
"""Initialize the iDevice."""
# pylint: disable=too-many-arguments
self.hass = hass
self.icloudobject = icloudobject
self.devicename = name
self.identifier = identifier
self._request_interval_seconds = 60
self._interval = 1
self.api = icloudobject.api
self._distance = None
self._battery = None
self._overridestate = None
self._devicestatuscode = None
self._devicestatus = None
self._lowpowermode = None
self._batterystatus = None
self._googletraveltime = googletraveltime
self._gttduration = None
self._gttorigin = None
self.entity_id = generate_entity_id(
ENTITY_ID_FORMAT_DEVICE, self.devicename,
hass=self.hass)
@property
def state(self):
"""Return the state of the iDevice."""
return self._interval
@property
def unit_of_measurement(self):
"""Unit of measurement of this entity."""
return "minutes"
@property
def state_attributes(self):
"""Return the friendlyname of the iDevice."""
if self._googletraveltime is None:
return {
ATTR_DEVICENAME: self.devicename,
ATTR_BATTERY: self._battery,
ATTR_DISTANCE: self._distance,
ATTR_DEVICESTATUS: self._devicestatus,
ATTR_LOWPOWERMODE: self._lowpowermode,
ATTR_BATTERYSTATUS: self._batterystatus,
ATTR_GOOGLE_MAPS_TRAVEL_TIME: self._googletraveltime
}
else:
return {
ATTR_DEVICENAME: self.devicename,
ATTR_BATTERY: self._battery,
ATTR_DISTANCE: self._distance,
ATTR_DEVICESTATUS: self._devicestatus,
ATTR_LOWPOWERMODE: self._lowpowermode,
ATTR_BATTERYSTATUS: self._batterystatus,
ATTR_GOOGLE_MAPS_TRAVEL_TIME: self._googletraveltime,
ATTR_GOOGLE_MAPS_TRAVEL_TIME_DURATION:
self._gttduration,
ATTR_GOOGLE_MAPS_TRAVEL_TIME_ORIGIN:
self._gttorigin
}
@property
def icon(self):
"""Return the icon to use for device if any."""
return 'mdi:cellphone-iphone'
def keep_alive(self):
"""Keep the api alive."""
currentminutes = dt_util.now().hour * 60 + dt_util.now().minute
if currentminutes % self._interval == 0:
self.update_icloud()
elif self._interval > 10 and currentminutes % self._interval in [2, 4]:
self.update_icloud()
self._gttduration = None
self._gttorigin = None
if self._googletraveltime is not None:
gttstate = self.hass.states.get(self._googletraveltime)
if gttstate is not None:
if 'origin_addresses' in gttstate.attributes:
self._gttduration = gttstate.state
self._gttorigin = gttstate.attributes['origin_addresses']
self.update_ha_state()
def lost_iphone(self):
"""Call the lost iphone function if the device is found."""
if self.api is not None:
self.api.authenticate()
self.identifier.play_sound()
@staticmethod
def data_is_accurate(data):
"""Check if location data is accurate."""
if not data:
return False
elif not data['locationFinished']:
return False
return True
def update_icloud(self, ):
"""Authenticate against iCloud and scan for devices."""
if self.api is not None:
from pyicloud.exceptions import PyiCloudNoDevicesException
try:
# Loop through every device registered with the iCloud account
status = self.identifier.status(DEVICESTATUSSET)
dev_id = slugify(status['name'].replace(' ', '', 99))
self._devicestatuscode = status['deviceStatus']
if self._devicestatuscode == '200':
self._devicestatus = 'online'
elif self._devicestatuscode == '201':
self._devicestatus = 'offline'
elif self._devicestatuscode == '203':
self._devicestatus = 'pending'
elif self._devicestatuscode == '204':
self._devicestatus = 'unregistered'
else:
self._devicestatus = 'error'
self._lowpowermode = status['lowPowerMode']
self._batterystatus = status['batteryStatus']
self.update_ha_state()
status = self.identifier.status(DEVICESTATUSSET)
battery = status['batteryLevel']*100
location = status['location']
if location:
see(
hass=self.hass,
dev_id=dev_id,
host_name=status['name'],
gps=(location['latitude'],
location['longitude']),
battery=battery,
gps_accuracy=location['horizontalAccuracy']
)
except PyiCloudNoDevicesException:
_LOGGER.error('No iCloud Devices found!')
def get_default_interval(self):
"""Get default interval of iDevice."""
devid = 'device_tracker.' + self.devicename
devicestate = self.hass.states.get(devid)
self._overridestate = None
self.devicechanged(self.devicename, None, devicestate)
def setinterval(self, interval=None):
"""Set interval of iDevice."""
if interval is not None:
devid = 'device_tracker.' + self.devicename
devicestate = self.hass.states.get(devid)
if devicestate is not None:
self._overridestate = devicestate.state
self._interval = interval
else:
self.get_default_interval()
self.update_ha_state()
self.update_icloud()
def devicechanged(self, entity, old_state, new_state):
"""Calculate new interval."""
# pylint: disable=too-many-branches
if entity is None:
return
self._distance = None
if 'latitude' in new_state.attributes:
device_state_lat = new_state.attributes['latitude']
device_state_long = new_state.attributes['longitude']
zone_state = self.hass.states.get('zone.home')
zone_state_lat = zone_state.attributes['latitude']
zone_state_long = zone_state.attributes['longitude']
self._distance = distance(device_state_lat, device_state_long,
zone_state_lat, zone_state_long)
self._distance = round(self._distance / 1000, 1)
if 'battery' in new_state.attributes:
self._battery = new_state.attributes['battery']
if new_state.state == self._overridestate:
self.update_ha_state()
return
self._overridestate = None
if new_state.state != 'not_home':
self._interval = 30
self.update_ha_state()
else:
if self._distance is None:
self.update_ha_state()
return
if self._distance > 100:
self._interval = round(self._distance, 0)
if self._googletraveltime is not None:
gttstate = self.hass.states.get(self._googletraveltime)
if gttstate is not None:
self._interval = round(float(gttstate.state) - 10, 0)
elif self._distance > 50:
self._interval = 30
elif self._distance > 25:
self._interval = 15
elif self._distance > 10:
self._interval = 5
else:
self._interval = 1
if self._battery is not None:
if self._battery <= 33 and self._distance > 3:
self._interval = self._interval * 2
self.update_ha_state()
class IEvent(Entity): # pylint: disable=too-many-instance-attributes
"""Represent an icloud calendar event in Home Assistant."""
def __init__(self, hass, icloudobject, name, typeevent=None):
"""Initialize an iEvent."""
# pylint: disable=too-many-arguments
self.hass = hass
self.icloudobject = icloudobject
self.api = icloudobject.api
self.eventguid = name
self._starttime = None
self._starttext = None
self._endtime = None
self._endtext = None
self._duration = None
self._title = None
self._remaining = 0
self._remainingtext = None
self._location = None
self._type = typeevent
self._tz = None
self.entity_id = generate_entity_id(
ENTITY_ID_FORMAT_EVENT, self.eventguid,
hass=self.hass)
@property
def state(self):
"""Return the state of the icloud event."""
return self._title
@property
def state_attributes(self):
"""Return the attributes of the icloud event."""
return {
ATTR_STARTTIME: self._starttext,
ATTR_ENDTIME: self._endtext,
ATTR_DURATION: self._duration,
ATTR_REMAINING: self._remainingtext,
ATTR_LOCATION: self._location,
ATTR_FRIENDLY_NAME: self._type
}
@property
def icon(self):
"""Return the icon to use for device if any."""
if self._type == TYPE_CURRENT:
return 'mdi:calendar'
elif self._type == TYPE_NEXT:
return 'mdi:calendar-clock'
def keep_alive(self, starttime, endtime, duration, title, tzone, location):
"""Keep the api alive."""
# pylint: disable=too-many-arguments,too-many-branches
current = self._type == TYPE_CURRENT
nextev = self._type == TYPE_NEXT
self._remaining = 0
tempnow = dt_util.now(tzone)
if tzone is None:
self._tz = pytz.utc
else:
self._tz = tzone
if starttime is None:
self._starttime = None
self._starttext = None
else:
self._starttime = datetime(starttime[1], starttime[2],
starttime[3], starttime[4],
starttime[5], 0, 0, self._tz)
self._starttext = self._starttime.strftime("%A %d %B %Y %H.%M.%S")
if nextev:
self._remaining = self._starttime - tempnow
remainingdays = self._remaining.days
remainingseconds = (self._starttime.hour * 3600 +
self._starttime.minute * 60 +
self._starttime.second -
tempnow.hour * 3600 -
tempnow.minute * 60 -
tempnow.second)
if ((self._starttime.year > tempnow.year or
self._starttime.month > tempnow.month or
self._starttime.day > tempnow.day) and
remainingseconds < 0):
remainingseconds = 86400 + remainingseconds
self._remaining = (remainingdays * 1440 +
round(remainingseconds / 60, 0))
if endtime is None:
self._endtime = None
self._endtext = None
else:
self._endtime = datetime(endtime[1], endtime[2], endtime[3],
endtime[4], endtime[5], 0, 0,
self._tz)
self._endtext = self._endtime.strftime("%A %d %B %Y %H.%M.%S")
if current:
self._remaining = self._endtime - tempnow
remainingdays = self._remaining.days
remainingseconds = (self._endtime.hour * 3600 +
self._endtime.minute * 60 +
self._endtime.second -
tempnow.hour * 3600 -
tempnow.minute * 60 -
tempnow.second)
if ((self._endtime.year > tempnow.year or
self._endtime.month > tempnow.month or
self._endtime.day > tempnow.day) and
remainingseconds < 0):
remainingseconds = 86400 + remainingseconds
self._remaining = (remainingdays * 1440 +
round(remainingseconds / 60, 0))
self._duration = duration
self._title = title
if (current or nextev) and title is None:
self._title = 'Free'
self._location = location
tempdays = floor(self._remaining / 1440)
temphours = floor((self._remaining % 1440) / 60)
tempminutes = floor(self._remaining % 60)
self._remainingtext = (str(tempdays) + "d " +
str(temphours) + "h " +
str(tempminutes) + "m")
if self._remaining <= 0:
self.hass.states.remove(self.entity_id)
else:
self.update_ha_state()
def check_alive(self):
"""Check if event is over."""
current = self._type == TYPE_CURRENT
nextev = self._type == TYPE_NEXT
self._remaining = 0
tempnow = dt_util.now(self._tz)
if self._starttime is not None:
if nextev:
self._remaining = self._starttime - tempnow
remainingdays = self._remaining.days
remainingseconds = (self._starttime.hour * 3600 +
self._starttime.minute * 60 +
self._starttime.second -
tempnow.hour * 3600 -
tempnow.minute * 60 -
tempnow.second)
if ((self._starttime.year > tempnow.year or
self._starttime.month > tempnow.month or
self._starttime.day > tempnow.day) and
remainingseconds < 0):
remainingseconds = 86400 + remainingseconds
self._remaining = (remainingdays * 1440 +
round(remainingseconds / 60, 0))
if self._endtime is not None:
if current:
self._remaining = self._endtime - tempnow
remainingdays = self._remaining.days
remainingseconds = (self._endtime.hour * 3600 +
self._endtime.minute * 60 +
self._endtime.second -
tempnow.hour * 3600 -
tempnow.minute * 60 -
tempnow.second)
if ((self._endtime.year > tempnow.year or
self._endtime.month > tempnow.month or
self._endtime.day > tempnow.day) and
remainingseconds < 0):
remainingseconds = 86400 + remainingseconds
self._remaining = (remainingdays * 1440 +
round(remainingseconds / 60, 0))
tempdays = floor(self._remaining / 1440)
temphours = floor((self._remaining % 1440) / 60)
tempminutes = floor(self._remaining % 60)
self._remainingtext = (str(tempdays) + "d " +
str(temphours) + "h " +
str(tempminutes) + "m")
if self._remaining <= 0:
self.hass.states.remove(self.entity_id)
else:
self.update_ha_state()
class Icloud(Entity): # pylint: disable=too-many-instance-attributes
"""Represent an icloud account in Home Assistant."""
def __init__(self, hass, username, password, cookiedirectory, name,
ignored_devices, getevents, googletraveltime):
"""Initialize an iCloud account."""
# pylint: disable=too-many-arguments,too-many-branches
# pylint: disable=too-many-statements,too-many-locals
self.hass = hass
self.username = username
self.password = password
self.cookiedir = cookiedirectory
self.accountname = name
self._max_wait_seconds = 120
self._request_interval_seconds = 10
self._interval = 1
self.api = None
self.devices = {}
self.getevents = getevents
self.events = {}
self.currentevents = {}
self.nextevents = {}
self._ignored_devices = ignored_devices
self._ignored_identifiers = {}
self.googletraveltime = googletraveltime
self._currentevents = 0
self._nextevents = 0
self.entity_id = generate_entity_id(
ENTITY_ID_FORMAT_ICLOUD, self.accountname,
hass=self.hass)
if self.username is None or self.password is None:
_LOGGER.error('Must specify a username and password')
else:
from pyicloud import PyiCloudService
from pyicloud.exceptions import PyiCloudFailedLoginException
try:
# Attempt the login to iCloud
self.api = PyiCloudService(self.username,
self.password,
cookie_directory=self.cookiedir,
verify=True)
for device in self.api.devices:
status = device.status(DEVICESTATUSSET)
devicename = slugify(status['name'].replace(' ', '', 99))
if (devicename not in self.devices and
devicename not in self._ignored_devices):
gtt = None
if devicename in self.googletraveltime:
gtt = self.googletraveltime[devicename]
idevice = IDevice(self.hass, self, devicename, device,
gtt)
idevice.update_ha_state()
self.devices[devicename] = idevice
elif devicename in self._ignored_devices:
self._ignored_identifiers[devicename] = device
if self.getevents:
from_dt = dt_util.now()
to_dt = from_dt + timedelta(days=7)
events = self.api.calendar.events(from_dt, to_dt)
new_events = sorted(events, key=self.get_key)
for event in new_events:
tzone = event['tz']
if tzone is None:
tzone = pytz.utc
else:
tzone = timezone(tzone)
tempnow = dt_util.now(tzone)
guid = event['guid']
starttime = event['startDate']
startdate = datetime(starttime[1], starttime[2],
starttime[3], starttime[4],
starttime[5], 0, 0, tzone)
endtime = event['endDate']
enddate = datetime(endtime[1], endtime[2], endtime[3],
endtime[4], endtime[5], 0, 0, tzone)
duration = event['duration']
title = event['title']
location = event['location']
strnow = tempnow.strftime("%Y%m%d%H%M%S")
strstart = startdate.strftime("%Y%m%d%H%M%S")
strend = enddate.strftime("%Y%m%d%H%M%S")
if strnow > strstart and strend > strnow:
ievent = IEvent(self.hass, self, guid,
TYPE_CURRENT)
ievent.update_ha_state()
self.currentevents[guid] = ievent
self.currentevents[guid].keep_alive(starttime,
endtime,
duration,
title,
tzone,
location)
for event in new_events:
tzone = event['tz']
if tzone is None:
tzone = pytz.utc
else:
tzone = timezone(tzone)
tempnow = dt_util.now(tzone)
guid = event['guid']
starttime = event['startDate']
startdate = datetime(starttime[1],
starttime[2],
starttime[3],
starttime[4],
starttime[5], 0, 0, tzone)
endtime = event['endDate']
enddate = datetime(endtime[1], endtime[2],
endtime[3], endtime[4],
endtime[5], 0, 0, tzone)
duration = event['duration']
title = event['title']
location = event['location']
strnow = tempnow.strftime("%Y%m%d%H%M%S")
strstart = startdate.strftime("%Y%m%d%H%M%S")
strend = enddate.strftime("%Y%m%d%H%M%S")
if strnow < strstart:
ievent = IEvent(self.hass, self, guid,
TYPE_NEXT)
ievent.update_ha_state()
self.nextevents[guid] = ievent
self.nextevents[guid].keep_alive(starttime,
endtime,
duration,
title,
tzone,
location)
except PyiCloudFailedLoginException as error:
_LOGGER.error('Error logging into iCloud Service: %s',
error)
@property
def state(self):
"""Return the state of the icloud account."""
return self.api is not None
@property
def state_attributes(self):
"""Return the attributes of the icloud account."""
if self.getevents:
return {
ATTR_ACCOUNTNAME: self.accountname,
ATTR_CURRENT_EVENTS: self._currentevents,
ATTR_NEXT_EVENTS: self._nextevents
}
else:
return {
ATTR_ACCOUNTNAME: self.accountname
}
@property
def icon(self):
"""Return the icon to use for device if any."""
return 'mdi:account'
@staticmethod
def get_key(item):
"""Sort key of events."""
return item.get('startDate')
def keep_alive(self):
"""Keep the api alive."""
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
if self.api is None:
from pyicloud import PyiCloudService
from pyicloud.exceptions import PyiCloudFailedLoginException
try:
# Attempt the login to iCloud
self.api = PyiCloudService(self.username,
self.password,
cookie_directory=self.cookiedir,
verify=True)
except PyiCloudFailedLoginException as error:
_LOGGER.error('Error logging into iCloud Service: %s',
error)
if self.api is not None:
if not self.getevents:
self.api.authenticate()
for devicename in self.devices:
self.devices[devicename].keep_alive()
if self.getevents:
from_dt = dt_util.now()
to_dt = from_dt + timedelta(days=7)
events = self.api.calendar.events(from_dt, to_dt)
new_events = sorted(events, key=self.get_key)
for event in new_events:
tzone = event['tz']
if tzone is None:
tzone = pytz.utc
else:
tzone = timezone(tzone)
tempnow = dt_util.now(tzone)
guid = event['guid']
starttime = event['startDate']
startdate = datetime(starttime[1], starttime[2],
starttime[3], starttime[4],
starttime[5], 0, 0, tzone)
endtime = event['endDate']
enddate = datetime(endtime[1], endtime[2], endtime[3],
endtime[4], endtime[5], 0, 0, tzone)
duration = event['duration']
title = event['title']
location = event['location']
strnow = tempnow.strftime("%Y%m%d%H%M%S")
strstart = startdate.strftime("%Y%m%d%H%M%S")
strend = enddate.strftime("%Y%m%d%H%M%S")
if strnow > strstart and strend > strnow:
if guid not in self.currentevents:
ievent = IEvent(self.hass, self, guid,
TYPE_CURRENT)
ievent.update_ha_state()
self.currentevents[guid] = ievent
self.currentevents[guid].keep_alive(starttime,
endtime,
duration,
title,
tzone,
location)
for addedevent in self.currentevents:
found = False
eventguid = self.currentevents[addedevent].eventguid
for event in new_events:
if event['guid'] == eventguid:
found = True
if not found:
ent_id = generate_entity_id(ENTITY_ID_FORMAT_EVENT,
eventguid,
hass=self.hass)
self.hass.states.remove(ent_id)
del self.currentevents[addedevent]
else:
self.currentevents[addedevent].check_alive()
for event in new_events:
tzone = event['tz']
if tzone is None:
tzone = pytz.utc
else:
tzone = timezone(tzone)
tempnow = dt_util.now(tzone)
guid = event['guid']
starttime = event['startDate']
startdate = datetime(starttime[1],
starttime[2],
starttime[3],
starttime[4],
starttime[5], 0, 0, tzone)
endtime = event['endDate']
enddate = datetime(endtime[1], endtime[2],
endtime[3], endtime[4],
endtime[5], 0, 0, tzone)
duration = event['duration']
title = event['title']
location = event['location']
strnow = tempnow.strftime("%Y%m%d%H%M%S")
strstart = startdate.strftime("%Y%m%d%H%M%S")
strend = enddate.strftime("%Y%m%d%H%M%S")
if strnow < strstart:
if guid not in self.nextevents:
ievent = IEvent(self.hass, self, guid,
TYPE_NEXT)
ievent.update_ha_state()
self.nextevents[guid] = ievent
self.nextevents[guid].keep_alive(starttime,
endtime,
duration,
title,
tzone,
location)
for addedevent in self.nextevents:
found = False
eventguid = self.nextevents[addedevent].eventguid
for event in new_events:
if event['guid'] == eventguid:
found = True
if not found:
ent_id = generate_entity_id(ENTITY_ID_FORMAT_EVENT,
eventguid,
hass=self.hass)
self.hass.states.remove(ent_id)
del self.nextevents[addedevent]
else:
self.nextevents[addedevent].check_alive()
self._currentevents = 0
self._nextevents = 0
for entity_id in self.hass.states.entity_ids('ievent'):
state = self.hass.states.get(entity_id)
friendlyname = state.attributes.get(ATTR_FRIENDLY_NAME)
if friendlyname == 'nextevent':
self._nextevents = self._nextevents + 1
elif friendlyname == 'currentevent':
self._currentevents = self._currentevents + 1
self.update_ha_state()
def lost_iphone(self, devicename):
"""Call the lost iphone function if the device is found."""
if self.api is not None:
self.api.authenticate()
if devicename is not None:
if devicename in self.devices:
self.devices[devicename].lost_iphone()
else:
_LOGGER.error("devicename %s unknown for account %s",
devicename, self.accountname)
else:
for device in self.devices:
self.devices[device].lost_iphone()
def update_icloud(self, devicename=None):
"""Authenticate against iCloud and scan for devices."""
if self.api is not None:
from pyicloud.exceptions import PyiCloudNoDevicesException
try:
# The session timeouts if we are not using it so we
# have to re-authenticate. This will send an email.
self.api.authenticate()
if devicename is not None:
if devicename in self.devices:
self.devices[devicename].update_icloud()
else:
_LOGGER.error("devicename %s unknown for account %s",
devicename, self.accountname)
else:
for device in self.devices:
self.devices[device].update_icloud()
except PyiCloudNoDevicesException:
_LOGGER.error('No iCloud Devices found!')
def setinterval(self, interval=None, devicename=None):
"""Set the interval of the given devices."""
if devicename is None:
for device in self.devices:
self.devices[device].setinterval(interval)
self.devices[device].update_icloud()
elif devicename in self.devices:
self.devices[devicename].setinterval(interval)
self.devices[devicename].update_icloud()