🎉 Initial commit

This commit is contained in:
Marcel Kapfer 2023-04-26 17:42:13 +02:00
commit 236194f32b
Signed by: mmk2410
GPG key ID: CADE6F0C09F21B09
10 changed files with 283 additions and 0 deletions

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
/__pycache__/
/venv/
/config.json
/.pocket_access_token

7
LICENSE Normal file
View file

@ -0,0 +1,7 @@
Copyright © 2023 Marcel Kapfer <opensource@mmk2410.org>
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.

27
README.org Normal file
View file

@ -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

6
config.example.json Normal file
View file

@ -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/"
}

79
freshrss.py Normal file
View file

@ -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"
}
)

36
freshrss2pocket.py Normal file
View file

@ -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()

11
helpers.py Normal file
View file

@ -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

97
pocket.py Normal file
View file

@ -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
)

1
requirements.txt Normal file
View file

@ -0,0 +1 @@
requests

15
run.sh Executable file
View file

@ -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