🎉 Initial commit

This commit is contained in:
Marcel Kapfer 2024-11-12 22:53:17 +01:00
commit 08714592b3
Signed by: mmk2410
GPG key ID: CADE6F0C09F21B09
10 changed files with 234 additions and 0 deletions

3
.gitignore vendored Executable file
View file

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

7
LICENSE Executable file
View file

@ -0,0 +1,7 @@
Copyright © 2024 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.

26
README.org Executable file
View file

@ -0,0 +1,26 @@
#+title: FreshRSS2Linkding
One-Way-Synchronization of your starred FreshRSS items to Linkding.
* Requirements
- [[https://linkding.link/][Linkding]] instance.
- [[https://www.freshrss.org/][FreshRSS]] instance
- Python 3
* Features
- Adds starred FreshRSS items to your Linkding instance (including title and categories)
- Removes starred items from FreshRSS
* Shortcomings
- None that I'm currently aware of.
* Setup
- 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 freshrss2linkding.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

7
config.example.json Executable file
View file

@ -0,0 +1,7 @@
{
"linkding_url": "https://linkding.example.org",
"linkding_api_key": "Your Linkding API key from the integrations tab in the settings.",
"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 Executable 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
freshrss2linkding.py Executable file
View file

@ -0,0 +1,36 @@
"""Transfer starred items in FreshRSS to Linkding."""
from linkding import Linkding
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 Linkding.")
linkding = Linkding(config['linkding_url'], config['linkding_api_key'])
for item in items:
print(f"Migrating item '{item['title']}'")
linkding.add(
item['url'],
title=item['title'],
tag_names=item['categories']
)
freshrss.unstarr(item['id'])
if __name__ == "__main__":
main()

11
helpers.py Executable 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

49
linkding.py Executable file
View file

@ -0,0 +1,49 @@
"""Linkding API code for FreshRSS2Pocket."""
import requests
import os.path
class Linkding:
"""Linkding API helper class."""
def __init__(self, baseurl, api_key):
self.baseurl = baseurl
self.api_key = api_key
def post_request(self, path, json):
res = requests.post(
f"{self.baseurl}/{path}",
headers={"Authorization": f"Token {self.api_key}"},
json=json,
timeout=15
)
if res.status_code >= 400:
raise ValueError("Response status codes indicates and error!")
return res.json()
def add(self, url, title="", tag_names=""):
"""Add URL to Linkding."""
json = {
"url": url,
"title": "",
"description": "",
"notes": "",
"is_archived": False,
"unread": False,
"shared": False,
"tag_names": []
}
if title:
json['title'] = title
if tag_names:
json['tag_names'] = tag_names.split(",")
self.post_request(
"api/bookmarks/",
json=json
)

1
requirements.txt Executable 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 freshrss2linkding.py