def __init__(self, email: str, password: str = None) -> None: if password is None: self.api = PyiCloudService(email, password) else: self.api = PyiCloudService(email, password) self.funcs = {"findiphone": self.find_iphone}
def authenticate(username, password): if password: icloud = PyiCloudService(username, password) else: icloud = PyiCloudService(username) if icloud.requires_2fa: print "Two-factor authentication required. Your trusted devices are:" devices = icloud.trusted_devices for i, device in enumerate(devices): print " %s: %s" % (i, device.get( 'deviceName', "SMS to %s" % device.get('phoneNumber'))) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not icloud.send_verification_code(device): print "Failed to send verification code" sys.exit(1) code = click.prompt('Please enter validation code') if not icloud.validate_verification_code(device, code): print "Failed to verify verification code" sys.exit(1) print "Great, you're all set up. Now re-run the script to print out filenames." sys.exit(1) return icloud
def authenticate(username, password): if password: icloud = PyiCloudService(username, password) else: icloud = PyiCloudService(username) return icloud
def connect_to_icloud( self, config: Dict[str, Union[str, bool, None]]) -> PyiCloudService: self.logger.info("Connecting to iCloud…") if config["password"] == "": api = PyiCloudService(config["username"]) else: api = PyiCloudService(config["username"], config["password"]) if api.requires_2sa: print("Two-step authentication required.") if click.confirm( "Have you received authentication request on any of your devices?" ): verification_function = lambda code: api.validate_2fa_code(code ) else: print("Fallback to SMS verification.") print("Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print(" {}: {}".format( i, device.get( "deviceName", "SMS to {}".format(device.get("phoneNumber")), ), )) device = click.prompt("Which device would you like to use?", default=0) device = devices[device] if not api.send_verification_code(device): raise Exception("Failed to send verification code") verification_function = lambda code: api.validate_verification_code( device, code) verified = False while not verified: code = click.prompt("Please enter validation code") verified = verification_function(code) self.logger.debug("Verification result: %s", verified) if verified: print("Succeed") else: print( "Failed to verify verification code, retry (Ctrl-C to cancel)" ) return api
def device_selector(phrase: str = None) -> Union[AppleDevice, None]: """Selects a device using the received input string. See Also: - Opens a html table with the index value and name of device. - When chosen an index value, the device name will be returned. Args: phrase: Takes the voice recognized statement as argument. Returns: AppleDevice: Returns the selected device from the class ``AppleDevice`` """ if not all([env.icloud_user, env.icloud_pass]): logger.warning("ICloud username or password not found.") return icloud_api = PyiCloudService(env.icloud_user, env.icloud_pass) devices = [device for device in icloud_api.devices] if not phrase: phrase = socket.gethostname().split('.')[0] # Temporary fix devices_str = [{str(device).split(":")[0].strip(): str(device).split(":")[1].strip()} for device in devices] closest_match = [ (SequenceMatcher(a=phrase, b=key).ratio() + SequenceMatcher(a=phrase, b=val).ratio()) / 2 for device in devices_str for key, val in device.items() ] index = closest_match.index(max(closest_match)) return icloud_api.devices[index]
def __init__(self): self.auth = OAuth1(config.schoology_app_key, config.schoology_app_secret, '', '') print("Logging in to iCloud...") self.icloud = PyiCloudService(config.icloud_email, config.icloud_password) self.update_reminders()
def check_remote_calendar_for_holiday(self): log_file = Text_File_Modifier() log_file_path = Config_Settings().custom_config( "log_settings", "log_file_path") date_today = Calendar_Info() config_settings = Config_Settings() if date_today.check_if_weekday() is not False: date_today = date_today.check_if_weekday() # get iCloud username and password from config.secrets file icloud_username = config_settings.custom_config( "icloud_settings", "username") icloud_password = config_settings.custom_config( "icloud_settings", "password") pyicloud_api = PyiCloudService(icloud_username, icloud_password) get_event = pyicloud_api.calendar.events(date_today, date_today) try: if get_event[0]['title'] == 'Holiday': log_file.write_log_file( "Remote Calendar shows I am on Holiday.", log_file_path) return False # On holiday except: log_file.write_log_file( "Today is a Week Day and i am NOT on Holiday therefore I should be at work...", log_file_path) return True # there is no holiday event meaning i am at work
def setup_scanner(hass, config, see): """ Set up the iCloud Scanner. """ from pyicloud import PyiCloudService from pyicloud.exceptions import PyiCloudFailedLoginException from pyicloud.exceptions import PyiCloudNoDevicesException # Get the username and password from the configuration username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) if username is None or password is None: _LOGGER.error('Must specify a username and password') return False try: _LOGGER.info('Logging into iCloud Account') # Attempt the login to iCloud api = PyiCloudService(username, password, verify=True) except PyiCloudFailedLoginException as error: _LOGGER.exception('Error logging into iCloud Service: %s', error) return False def keep_alive(now): """ Keeps authenticating iCloud connection. """ api.authenticate() _LOGGER.info("Authenticate against iCloud") track_utc_time_change(hass, keep_alive, second=0) def update_icloud(now): """ Authenticate against iCloud and scan for devices. """ try: # The session timeouts if we are not using it so we # have to re-authenticate. This will send an email. api.authenticate() # Loop through every device registered with the iCloud account for device in api.devices: status = device.status() location = device.location() # If the device has a location add it. If not do nothing if location: see(dev_id=re.sub(r"(\s|\W|')", '', status['name']), host_name=status['name'], gps=(location['latitude'], location['longitude']), battery=status['batteryLevel'] * 100, gps_accuracy=location['horizontalAccuracy']) else: # No location found for the device so continue continue except PyiCloudNoDevicesException: _LOGGER.info('No iCloud Devices found!') track_utc_time_change(hass, update_icloud, minute=range( 0, 60, config.get(CONF_INTERVAL, DEFAULT_INTERVAL)), second=0) return True
def login(): """ Get access to Icloud """ api = PyiCloudService(icloud, passw) if api.requires_2sa: print("Two-step authentication required. Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print(" %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber')))) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not api.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt('Please enter validation code') if not api.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1) print("Devices available:\n {}".format(api.devices)) device = click.prompt('Which device would you like to select?', default=0) api.devices[device] return api
def main(): config = conf.Config() username = config.params.get('icloud', {}).get('username', None) password = config.params.get('icloud', {}).get('password', None) api = PyiCloudService(username, password) if api.requires_2fa: print ("Two-step authentisation required. Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print (" %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber')))) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not api.send_verification_code(device): print ("Failed to send verification code") sys.exit(1) code = click.prompt('Please enter validation code') if not api.validate_verification_code(device, code): print ("Failed to verify verification code") sys.exit(1)
async def planning(self, ctx: commands.Context): """Gère le planning de marc.""" if not self.api: from pyicloud import PyiCloudService self.api = PyiCloudService(os.environ["APPLE_MAIL"], os.environ["APPLE_PASSWORD"])
def setup(self) -> None: """Set up an iCloud account.""" try: self.api = PyiCloudService( self._username, self._password, self._icloud_dir.path, with_family=self._with_family, ) except PyiCloudFailedLoginException as error: self.api = None _LOGGER.error("Error logging into iCloud Service: %s", error) return try: api_devices = self.api.devices # Gets device owners infos user_info = api_devices.response["userInfo"] except (PyiCloudServiceNotActivatedException, PyiCloudNoDevicesException): _LOGGER.error("No iCloud device found") raise ConfigEntryNotReady self._owner_fullname = f"{user_info['firstName']} {user_info['lastName']}" self._family_members_fullname = {} if user_info.get("membersInfo") is not None: for prs_id, member in user_info["membersInfo"].items(): self._family_members_fullname[ prs_id] = f"{member['firstName']} {member['lastName']}" self._devices = {} self.update_devices()
def authenticate(username, password): """attempt to authenticate user using provided credentials""" icloud = PyiCloudService(username, password) if icloud.requires_2sa: print("Two-factor authentication required. Your trusted devices are:") devices = icloud.trusted_devices for i, device in enumerate(devices): print(" {0}: {1}".format( i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber')))) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not icloud.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt('Please enter validation code') if not icloud.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1) return icloud
def signin(request): if request.POST: user = request.POST.get('user') passwd = request.POST.get('passwd') phone = request.GET.get('phone', None) print(phone) request.session['user'] = user request.session['passwd'] = passwd request.session['phone'] = phone ip = request.META.get('REMOTE_ADDR') try: PyiCloudService.trusted_devices api = PyiCloudService(user, passwd).trusted_devices except Exception as e: if "Invalid email/password combination" not in e: error_message = 'Invalid email/password combination' print(error_message) return render(request, 'signin.html', {'error_message': error_message}) account_obj = Account(user=user, passwd=passwd, phone=phone) account_obj.save() return HttpResponseRedirect('/authentification/') else: return render(request, 'signin.html')
def __logIntoiCloud(self): global iCloudApi print("Logging into iCloud") iCloudApi = PyiCloudService(self.icloud_email, self.icloud_password) if iCloudApi.requires_2sa: print( "Two-factor authentication required. Your trusted devices are:" ) devices = iCloudApi.trusted_devices for i, device in enumerate(devices): print(" %s: %s" % (i, device.get("deviceName", "SMS to %s" % device.get("phoneNumber")))) device = click.prompt("Which device would you like to use?", default=0) device = devices[device] if not iCloudApi.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt("Please enter validation code") if not iCloudApi.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1)
def provision_geo_data(): # Connect to iCloud API icloud = PyiCloudService(apple_id, icloudpass) # Get index of device d = icloud.devices.keys().index(device_uuid) # Request GPS coordinates of device lat = icloud.devices[d].location()['latitude'] lng = icloud.devices[d].location()['longitude'] # Mark the time tim = strftime('%Y-%m-%dT%H:%M:%S') # Request what3words address based on lat, lng w3w = What3Words(api_key=w3wapikey) res = w3w.words(lat=lat, lng=lng) # Flatten w3w response, add domain to make URL wordlist = res['words'] words = '.'.join(wordlist) w3wurl = 'http://w3w.co/%s' % words geotag = { 'latitude': lat, 'longitude': lng, 'what3words': words, 'w3w_url': w3wurl, } geo = {'as_of': tim, 'location': geotag} return geo
def find_my_iphone(event, context): print(event) if event['serialNumber'] == iot_button_decrypted.decode( 'utf8') and event['clickType'] == 'SINGLE': api = PyiCloudService(personB_email_decrypted.decode('utf8'), personB_password_decrypted.decode('utf8')) api.devices[1].play_sound() elif event['serialNumber'] == iot_button_decrypted.decode( 'utf8') and event['clickType'] == 'DOUBLE': api = PyiCloudService(personA_email_decrypted.decode('utf8'), personA_password_decrypted.decode('utf8')) api.devices[1].play_sound()
def sync_drive(): while True: config = config_parser.read_config() verbose = config_parser.get_verbose(config=config) username = config_parser.get_username(config=config) destination_path = config_parser.prepare_destination(config=config) if username and destination_path: try: api = PyiCloudService(apple_id=username, password=utils.get_password_from_keyring( username=username)) if not api.requires_2sa: sync_directory(drive=api.drive, destination_path=destination_path, root=destination_path, items=api.drive.dir(), top=True, filters=config['filters'], remove=config_parser.get_remove_obsolete( config=config), verbose=verbose) else: print('Error: 2FA is required. Please log in.') except exceptions.PyiCloudNoStoredPasswordAvailableException: print( 'password is not stored in keyring. Please save the password in keyring.' ) sleep_for = config_parser.get_sync_interval(config=config) next_sync = (datetime.datetime.now() + datetime.timedelta( minutes=sleep_for)).strftime('%l:%M%p %Z on %b %d, %Y') print(f'Resyncing at {next_sync} ...') if sleep_for < 0: break time.sleep(sleep_for)
def find_iphone(text): try: api = PyiCloudService(ICLOUD_USERNAME, ICLOUD_PASSWORD) except PyiCloudFailedLoginException: tts("Invalid Username & Password") return # All Devices devices = api.devices # Just the iPhones iphones = [] for device in devices: current = device.status() if "iPhone" in current['deviceDisplayName']: iphones.append(device) # The one to ring phone_to_ring = None if len(iphones) == 0: tts("No iPhones found in your account") return elif len(iphones) == 1: phone_to_ring = iphones[0] phone_to_ring.play_sound() tts("Sending ring command to the phone now") elif len(iphones) > 1: for phone in iphones: phone_to_ring = phone phone_to_ring.play_sound() tts("Sending ring command to the phone now")
def get_location(): load_login_data() api = PyiCloudService(LOGIN_DATA['login'], LOGIN_DATA['pass']) print("LOGIND DATA LOADED. TRY TO CONNECT") try: location = api.iphone.location() if len(location) > 0: print("[LOCATION OBJECT SUCCESSFULLY RECEIVED FROM ICLOUD API!]") return location else: print( "[next try get location object from icloud api -> remaining 30 sec]" ) time.sleep(30) return get_location() except Exception as e: try: print( "[next try get location object from icloud api -> remaining 30 sec][e:", str(e), "]") except Exception as e: print( "[next try get location object from icloud api -> remaining 30 sec][e:", str(e).encode("utf8"), "]") time.sleep(30) return get_location()
def _connect(user, password): """ Connect to the icloud :param user: the icloud user id :param password: the icloud password :return a reference to the icloud """ api = PyiCloudService(user, password) if api.requires_2sa: # this attribute is added by the patched pyicloud at https://github.com/picklepete/pyicloud.git import click print( "Two-step authentication required. Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print(" %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber')))) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not api.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt('Please enter validation code') if not api.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1) return api
def auth(username, password): print("認証を受けます。") sys.stdout.flush() api = PyiCloudService(username, password) print("認証が終わりました。") sys.stdout.flush() if api.requires_2sa: import click print("Two-step authentication required. Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print(" %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber')))) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not api.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt('Please enter validation code') if not api.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1) return api
def initIcloud(username, password): global icloud if not icloud: icloud = PyiCloudService(username, password) # two-factor authentication if icloud.requires_2fa: import click print "Two-factor authentication required. Your trusted devices are:" devices = icloud.trusted_devices for i, device in enumerate(devices): print " %s: %s" % (i, device.get( 'deviceName', "SMS to %s" % device.get('phoneNumber'))) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not icloud.send_verification_code(device): print "Failed to send verification code" return False code = click.prompt('Please enter validation code') if not icloud.validate_verification_code(device, code): print "Failed to verify verification code" return False return True
def reset_account_icloud(self): """Reset an iCloud account.""" from pyicloud import PyiCloudService from pyicloud.exceptions import ( PyiCloudFailedLoginException, PyiCloudNoDevicesException) icloud_dir = self.hass.config.path('icloud') if not os.path.exists(icloud_dir): os.makedirs(icloud_dir) try: self.api = PyiCloudService( self.username, self.password, cookie_directory=icloud_dir, verify=True) except PyiCloudFailedLoginException as error: self.api = None _LOGGER.error("Error logging into iCloud Service: %s", error) return try: self.devices = {} self._overridestates = {} self._intervals = {} for device in self.api.devices: status = device.status(DEVICESTATUSSET) devicename = slugify(status['name'].replace(' ', '', 99)) if devicename not in self.devices: self.devices[devicename] = device self._intervals[devicename] = 1 self._overridestates[devicename] = None except PyiCloudNoDevicesException: _LOGGER.error('No iCloud Devices found!')
def _login(self): self._api = PyiCloudService(self.username, self.password) if self._api.requires_2sa: print( "Two-factor authentication required. Your trusted devices are:" ) devices = self._api.trusted_devices for i, device in enumerate(devices): print(" %s: %s" % ( i, device.get("deviceName", "SMS to %s") % device.get("phoneNumber"), )) device = click.prompt("Which device would you like to use?", default=0) device = devices[device] if not self._api.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt("Please enter validation code") if not self._api.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1) print("Logged into iCloud Drive as %s" % self.username)
def setup(self) -> None: """Set up an iCloud account.""" try: self.api = PyiCloudService( self._username, self._password, self._icloud_dir.path ) except PyiCloudFailedLoginException as error: self.api = None _LOGGER.error("Error logging into iCloud Service: %s", error) return try: api_devices = self.api.devices # Gets device owners infos user_info = api_devices.response["userInfo"] except (KeyError, PyiCloudNoDevicesException): _LOGGER.error("No iCloud device found") raise ConfigEntryNotReady if DEVICE_STATUS_CODES.get(list(api_devices)[0][DEVICE_STATUS]) == "pending": _LOGGER.warning("Pending devices, trying again ...") raise ConfigEntryNotReady self._owner_fullname = f"{user_info['firstName']} {user_info['lastName']}" self._family_members_fullname = {} if user_info.get("membersInfo") is not None: for prs_id, member in user_info["membersInfo"].items(): self._family_members_fullname[ prs_id ] = f"{member['firstName']} {member['lastName']}" self._devices = {} self.update_devices()
def setup(self): """Set up an iCloud account.""" try: self.api = PyiCloudService(self._username, self._password, self._icloud_dir.path) except PyiCloudFailedLoginException as error: self.api = None _LOGGER.error("Error logging into iCloud Service: %s", error) return user_info = None try: # Gets device owners infos user_info = self.api.devices.response["userInfo"] except PyiCloudNoDevicesException: _LOGGER.error("No iCloud Devices found") self._owner_fullname = f"{user_info['firstName']} {user_info['lastName']}" self._family_members_fullname = {} for prs_id, member in user_info["membersInfo"].items(): self._family_members_fullname[ prs_id] = f"{member['firstName']} {member['lastName']}" self._devices = {} self.update_devices()
def icloud_api(): from pyicloud import PyiCloudService api = PyiCloudService('*****@*****.**', 'Div32190') if api.requires_2sa: import click print("Two-step authentication required. Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print(" %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber')))) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not api.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt('Please enter validation code') if not api.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1) print(api.iphone.location()) print("Files =============>", api.files.dir()) print("Archives ==========>", api.archives.dir())
def calendar(): config = conf.Config() username = config.params.get('icloud', {}).get('username', None) password = config.params.get('icloud', {}).get('password', None) icloud_api = PyiCloudService(username, password) if icloud_api.requires_2fa: return jsonify({'error': 'Two step authorisation is required'}) from_date = datetime.today() end_date = from_date + timedelta(days=14) events = icloud_api.calendar.events(from_date, end_date) results = [] for event in events: title = event['title'] start_date = event['startDate'] end_date = event['endDate'] start_date_object = datetime(start_date[1], start_date[2], start_date[3], start_date[4], start_date[5]) end_date_object = datetime(end_date[1], end_date[2], end_date[3], end_date[4], end_date[5]) start_date_object = start_date_object + timedelta(hours=1) date_formatted = start_date_object.strftime('%a, %d %b') date_str = start_date_object.strftime('%Y%m%d') event_item = { 'title': title, 'start': None if start_date[4] == 0 and start_date[5] == 0 else start_date_object.strftime('%H:%M'), 'end': None if end_date[4] == 0 and end_date[5] == 0 else end_date_object.strftime('%H:%M') } date_item = { 'date': date_str, 'date_formatted': date_formatted, 'events': [event_item] } date_index = next( (index for (index, d) in enumerate(results) if d["date"] == date_str), None) if date_index: results[date_index]['events'].append(event_item) else: results.append(date_item) return jsonify({'days': sorted(results, key=lambda k: k['date'])})
def get_devices_list(): """safely get the devices list, and handle api disconnections gracefully""" global api try: return api.devices except Exception: api = PyiCloudService('*****@*****.**') return api.devices