Initial commit

This commit is contained in:
Lucas Verney 2024-03-07 15:43:41 +01:00
commit 5e6d789df5
6 changed files with 221 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
config.ini*

8
LICENSE Normal file
View File

@ -0,0 +1,8 @@
Copyright 2024 Phyks
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

68
README.md Normal file
View File

@ -0,0 +1,68 @@
iCloud to Nextcloud
===================
Apple iCloud "Find My" only lets you see your latest position, but sometimes
you want to scroll back in time and find previous positions. This scripts
autoamtically scrapes your iPhone location from iCloud and stores it in
Nextcloud, so that you get access to the full history.
## Installation
First, git clone and install required dependencies:
```bash
git clone …
cd icloudlocation
python -m venv .venv
./.venv/bin/pip install -r requirements.txt
```
Then, set up the configuration:
```bash
cp config.example.ini config.ini
$EDITOR config.ini
```
Beware that your credentials will be stored in plaintext. You might want to
enable 2FA everywhere and only run it on a trusted machine/environment (disk
encryption, etc.). `cat`ing config in the following commands is here to help
you add an extra layer of security at rest (symmetric GPG, etc.) on your
config file. For the Nextcloud part, you might want to use a dedicated access
token.
Run the program a first time to ensure everything is running smooth:
```bash
cat config.ini | ./.venv/bin/python icloud_to_nextcloud.py
```
_Note:_ If you enabled 2FA on your Apple iCloud account, this first run will
be interactive and requires you explicitly trusting the session from one of
your device.
## Usage
```bash
cat config.ini | ./.venv/bin/python icloud_to_nextcloud.py
```
Use a `cron` daemon to run it periodically at the frequency of your choice.
## License
Code published under an MIT license.
```
Copyright 2024 Phyks
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```

9
config.example.ini Normal file
View File

@ -0,0 +1,9 @@
[apple]
email = apple_icloud_email
password = apple_icloud_password
[nextcloud]
server = https://cloud.example.com
user = nextcloud_user
password = nextcloud_password

134
icloud_to_nextcloud.py Normal file
View File

@ -0,0 +1,134 @@
#!/usr/bin/env python3
import configparser
import logging
import sys
import urllib.parse
import requests
from pyicloud import PyiCloudService
from requests.auth import HTTPBasicAuth
def load_config(config_str=None):
"""
Load and parse config from string provided. Defaults to reading from stdin.
"""
if not config_str:
config_str = sys.stdin.read()
config = configparser.ConfigParser()
config.read_string(config_str)
return config
def get_icloud_location(config):
"""
Fetch latest iPhone location from iCloud
"""
email = config['apple']['email']
password = config['apple']['password']
api = PyiCloudService(email, password)
if api.requires_2fa:
print("Two-factor authentication required.")
code = input(
"Enter the code you received of one of your approved devices: "
)
result = api.validate_2fa_code(code)
print("Code validation result: %s" % result)
if not result:
print("Failed to verify security code")
sys.exit(1)
if not api.is_trusted_session:
print("Session is not trusted. Requesting trust...")
result = api.trust_session()
print("Session trust result %s" % result)
if not result:
print(
"Failed to request trust. "
"You will likely be prompted for the code again "
"in the coming weeks"
)
elif 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)
iphone = next(
device
for device in api.devices
if 'iPhone' in device.status()['name']
)
iphone_location = iphone.location()
iphone_status = iphone.status()
return iphone_location, iphone_status
def store_location_in_nextcloud(config, iphone_location, iphone_status):
"""
Store provided iPhone location to Nextcloud.
"""
nextcloud_location_args = {
"user_agent": iphone_status['name'],
"lat": iphone_location['latitude'],
"lng": iphone_location['longitude'],
"accuracy": iphone_location['horizontalAccuracy'],
"timestamp": iphone_location['timeStamp'] // 1000,
"altitude": iphone_location['altitude'],
"battery": iphone_status['batteryLevel'],
}
logging.info('Got location data from iCloud: %s.', nextcloud_location_args)
logging.debug(
"curl -X POST -u '%s:%s' '%s'",
config['nextcloud']['user'],
config['nextcloud']['password'],
(
'%s?%s' % (
urllib.parse.urljoin(
config['nextcloud']['server'], '/apps/maps/api/1.0/devices'
),
urllib.parse.urlencode(nextcloud_location_args),
)
),
)
r = requests.post(
urllib.parse.urljoin(
config['nextcloud']['server'], '/apps/maps/api/1.0/devices'
),
params=nextcloud_location_args,
auth=HTTPBasicAuth(
config['nextcloud']['user'], config['nextcloud']['password']
)
)
r.raise_for_status()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
config = load_config()
iphone_location, iphone_status = get_icloud_location(config)
store_location_in_nextcloud(config, iphone_location, iphone_status)

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
pyicloud