Last active
August 13, 2020 08:53
-
-
Save alexpyoung/7e241a8f3f805630f0f66a1cf0763675 to your computer and use it in GitHub Desktop.
Import Safari Reading List Into Pocket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import logging | |
import os | |
import plistlib | |
import requests | |
import sys | |
import webbrowser | |
CONSUMER_KEY = os.environ["POCKET_CONSUMER_KEY"] | |
BASE_URL = "https://getpocket.com" | |
REDIRECT_URL = "localhost" | |
logger = logging.getLogger(__name__) | |
urls = [] | |
def extract_urls(node): | |
children = node.get("Children", []) | |
url = node.get("URLString") | |
if url: | |
urls.append(url) | |
for child in children: | |
extract_urls(child) | |
def read_plist(): | |
filename = os.path.expanduser("~/Library/Safari/Bookmarks.plist") | |
with open(filename, 'rb') as handler: | |
plist = plistlib.load(handler) | |
extract_urls(plist) | |
def post(url, data): | |
headers = { | |
"x-accept": "application/json", | |
} | |
response = requests.post(url, data=data, headers=headers) | |
error = response.headers.get("X-Error") | |
if error: | |
logger.error(f"{response.status_code}, {error}") | |
response.raise_for_status() | |
else: | |
return response.json() | |
def request_code(): | |
payload = { | |
"consumer_key": CONSUMER_KEY, | |
"redirect_uri": REDIRECT_URL, | |
} | |
response = post(f"{BASE_URL}/v3/oauth/request", payload) | |
return response["code"] | |
def request_access_token(code): | |
payload = { | |
"consumer_key": CONSUMER_KEY, | |
"code": code, | |
} | |
response = post(f"{BASE_URL}/v3/oauth/authorize", payload) | |
return response["access_token"] | |
def request_authorization(code): | |
url = f"{BASE_URL}/auth/authorize?request_token={code}&redirect_uri={REDIRECT_URL}" | |
webbrowser.open(url, new=2) | |
def authenticate_pocket(): | |
code = request_code() | |
request_authorization(code) | |
input("Press any key after authorizing app...") | |
return request_access_token(code) | |
def add_item(url, token): | |
payload = { | |
"url": url, | |
"consumer_key": CONSUMER_KEY, | |
"access_token": token, | |
} | |
return post("https://getpocket.com/v3/add", payload) | |
def main(): | |
read_plist() | |
access_token = authenticate_pocket() | |
logger.info("Successfully authenticated with Pocket") | |
for url in urls: | |
add_item(url, access_token) | |
logger.info(f"Added {len(urls)} urls to Pocket!") | |
if __name__ == '__main__': | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment