commit 236194f32b08e2e01048e8a77d4f793fa08e9cda Author: Marcel Kapfer Date: Wed Apr 26 17:42:13 2023 +0200 🎉 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9964ea3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/__pycache__/ +/venv/ +/config.json +/.pocket_access_token diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9b920ff --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright © 2023 Marcel Kapfer + +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. diff --git a/README.org b/README.org new file mode 100644 index 0000000..982f2bc --- /dev/null +++ b/README.org @@ -0,0 +1,27 @@ +#+title: FreshRSS2Pocket + +One-Way-Synchronization of your starred FreshRSS items to Pocket. + +* Requirements + +- Pocket application. +- [[https://www.freshrss.org/][FreshRSS]] instance +- Python 3 + +* Features + +- Adds starred FreshRSS items to your Pocket account (including title and categories) +- Removes starred items from FreshRSS + +* Shortcomings + +- None that I'm currently aware of. + +* Setup + +- Create a new Pocket application in the [[https://getpocket.com/developer/apps/][Pocket developer portal]] of type "Desktop (other)" (not sure if the type really matters) +- Copy =config.example.json= to =config.json= and fill it out +- (optional) Create a Python virtual environment with =python3 -m venv venv= and activate it +- Install Python requirements with =pip install -r requirements.txt= +- Execute the program with =python youtube2freshrss.py= +- (optional) Set up a Cron job for running the =run.sh= (requires virtual environment) once a day with the working directory as first argument diff --git a/config.example.json b/config.example.json new file mode 100644 index 0000000..0afe1c5 --- /dev/null +++ b/config.example.json @@ -0,0 +1,6 @@ +{ + "pocket_consumer_key": "Pocket Application Consumer Key. See step 1 at https://getpocket.com/developer/docs/authentication", + "freshrss_username": "Your FreshRSS user name", + "freshrss_api_password": "Your FreshRSS API password. See https://freshrss.github.io/FreshRSS/en/users/06_Mobile_access.html", + "freshrss_url": "Your FreshRSS URL with trailing slash, e.g. https://rss.example.org/" +} diff --git a/freshrss.py b/freshrss.py new file mode 100644 index 0000000..e8b5376 --- /dev/null +++ b/freshrss.py @@ -0,0 +1,79 @@ +"""Google Reader/FreshRSS API code for Youtube2FreshRSS.""" + +import requests + + +class FreshRss: + """FreshRSS greader API helper class.""" + base_path = "/api/greader.php" + base_api_path = f"{base_path}/reader/api/0/" + + def __init__(self, baseurl, username, password): + self.base_url = baseurl + self.username = username + self.password = password + self.auth_header = "" + + def get_auth_token(self): + "Retrieve greader auth token" + res = requests.post( + f"{self.base_url}{self.base_path}/accounts/ClientLogin", + params={'Email': self.username, 'Passwd': self.password}, + timeout=15 + ) + auth_token = res.text.split("=")[-1].strip() + self.auth_header = f"GoogleLogin auth={auth_token}" + + def post(self, path, params=None, data=None): + "Make a POST request to a greader API." + res = requests.post( + f"{self.base_url}{self.base_api_path}{path}", + data=data, + params=params, + headers={"Authorization": self.auth_header}, + timeout=15 + ) + return res.text + + def get(self, path, params=None): + """Make a GET request to a greader API.""" + res = requests.get( + f"{self.base_url}{self.base_api_path}{path}?output=json", + params=params, + headers={"Authorization": self.auth_header}, + timeout=15 + ) + return res.json() + + def get_starred(self): + """Retrieve starred items.""" + return self.get("/stream/contents/user/-/state/com.google/starred") + + def parse_items(self, items): + """Parse URLs from a list of items.""" + parsed = [] + + for item in items: + cat = ["rss"] + for category in item['categories']: + if category.startswith("user/-/label/"): + cat.append(category[13:]) + + parsed.append({ + "id": item['id'], + "title": item['title'], + "url": item['canonical'][0]['href'], + "categories": ",".join(cat) + }) + + return parsed + + def unstarr(self, item_id): + """Unstar an item given its ID.""" + self.post( + "/edit-tag", + data={ + "i": item_id, + "r": "user/-/state/com.google/starred" + } + ) diff --git a/freshrss2pocket.py b/freshrss2pocket.py new file mode 100644 index 0000000..b22504c --- /dev/null +++ b/freshrss2pocket.py @@ -0,0 +1,36 @@ +"""Transfer YouTube subscriptions to FreshRSS.""" + +from pocket import Pocket +from freshrss import FreshRss +from helpers import read_config_file + + +def main(): + """Entry point.""" + config = read_config_file() + + freshrss = FreshRss( + config['freshrss_url'], + config['freshrss_username'], + config['freshrss_api_password'], + ) + freshrss.get_auth_token() + + starred = freshrss.get_starred()['items'] + items = freshrss.parse_items(starred) + print(f"Found {len(items)} starred items that will be moved to Pocket.") + + pocket = Pocket(config['pocket_consumer_key']) + + for item in items: + print(f"Migrating item '{item['title']}'") + pocket.add( + item['url'], + title=item['title'], + tags=item['categories'] + ) + freshrss.unstarr(item['id']) + + +if __name__ == "__main__": + main() diff --git a/helpers.py b/helpers.py new file mode 100644 index 0000000..4bd7d74 --- /dev/null +++ b/helpers.py @@ -0,0 +1,11 @@ +"""Helper functions for YouTube2FreshRSS.""" + +import json + + +def read_config_file(): + """Read secrets JSON file.""" + with open("config.json", "rb") as config_file: + data = json.load(config_file) + + return data diff --git a/pocket.py b/pocket.py new file mode 100644 index 0000000..9debf24 --- /dev/null +++ b/pocket.py @@ -0,0 +1,97 @@ +"""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 + ) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..f229360 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +requests diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..15566ba --- /dev/null +++ b/run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -euo pipefail + +WORKING_DIR="${1:-.}" + +cd "$WORKING_DIR" || exit + +if [ ! -d "./venv/" ]; then + echo "This is script only works with a python virtual environment setup at $(pwd)/venv" + exit 1 +fi + +source ./venv/bin/activate +./venv/bin/python freshrss2pocket.py