freshrss2pocket/pocket.py
2023-04-26 17:42:13 +02:00

97 lines
2.5 KiB
Python

"""Pocket API code for FreshRSS2Pocket."""
import requests
import os.path
class Pocket:
"""Pocket API helper class."""
base_api_path = "https://getpocket.com/v3"
request_token = ""
access_token = ""
def __init__(self, consumer_key):
self.consumer_key = consumer_key
if not self.access_token_stored():
self.get_request_token()
self.authenticate_app()
self.get_access_tocken()
else:
self.read_access_token()
def post_request(self, path, json):
res = requests.post(
f"{self.base_api_path}/{path}",
headers={"X-Accept": "application/json"},
json=json,
timeout=15
)
if res.status_code >= 400:
raise ValueError("Response status codes indicates and error!")
return res.json()
def get_request_token(self):
"""Request a request token."""
json = {
"consumer_key": self.consumer_key,
"redirect_uri": "http://localhost"
}
data = self.post_request(
"oauth/request",
json
)
self.request_token = data['code']
def authenticate_app(self):
print("Paste the following URL in your browser to authorize freshrss2pocket")
print(f"https://getpocket.com/auth/authorize?request_token={self.request_token}&redirect_uri=http%3A%2F%2Flocalhost")
input("Press Enter if done...")
def get_access_tocken(self):
json = {
"consumer_key": self.consumer_key,
"code": self.request_token
}
data = self.post_request(
"oauth/authorize",
json
)
self.access_token = data['access_token']
self.write_access_token()
def access_token_stored(self):
return os.path.isfile(".pocket_access_token")
def read_access_token(self):
with open(".pocket_access_token", "r") as token_file:
self.access_token = token_file.read().strip()
def write_access_token(self):
with open(".pocket_access_token", "w") as token_file:
token_file.write(self.access_token)
def add(self, url, title="", tags=""):
"""Add URL to Pocket's save list."""
json = {
"consumer_key": self.consumer_key,
"access_token": self.access_token,
"url": url
}
if title:
json['title'] = title
if tags:
json['tags'] = tags
self.post_request(
"add",
json=json
)