Compare commits

..

No commits in common. "0302eb5e7beb398c4c9a2d6218d7addbff9d83bc" and "36da56f04a4124d579b83006f7a6af459acb4bb7" have entirely different histories.

7 changed files with 1124 additions and 159 deletions

23
.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# Python virtual environment
.venv/
venv/
env/
# Secrets
.env
# Local import state
imported-osmcal-events.json
*.json.broken
# Python cache
__pycache__/
*.pyc
# Local logs
*.log
# Mobilizon setup/token files
mobilizon-app.json
mobilizon-token.json
mobilizon-device.json

156
LICENSE
View File

@ -1,156 +0,0 @@
Creative Commons Attribution 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
Section 1 Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. Downstream recipients.
A. Offer from the Licensor Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
Section 5 Disclaimer of Warranties and Limitation of Liability.
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@ -1,3 +0,0 @@
# OSMcal_Mobilizon_Import
Zapft die API von osmcal.org an, liest die Veranstaltungen im Umkreis aus und postet über die API von Mobilizon Veranstaltungen zur Veranstaltungsseite als Benutzer oder Gruppe.

664
import-osmcal-to-mobilizon.py Executable file
View File

@ -0,0 +1,664 @@
#!/usr/bin/env python3
"""
Importiert OSMCal-Veranstaltungen im angegebenen Umkreis um Heidelberg nach Mobilizon.
Datenquellen:
- OSMCal API:
https://osmcal.org/api/v2/events/?in=de
Liefert Titel, Datum, Ort, Koordinaten und Event-URL.
- OSMCal Einzel-ICS:
https://osmcal.org/event/<ID>.ics
Liefert die Originalbeschreibung über DESCRIPTION.
Ziel:
- Mobilizon GraphQL API:
https://rheinneckar.events/api
Hinweise:
- Das Script importiert nur neue Events.
- Bereits importierte Events werden in imported-osmcal-events.json gespeichert.
- Bestehende Mobilizon-Entwürfe werden NICHT aktualisiert oder veröffentlicht.
- Veranstaltungsende wird immer auf Startzeit + 3 Stunden gesetzt.
Voraussetzungen:
vor Ausführung Api-Schlüssel in die .env Datei speichern
Ausführen:
source .venv/bin/activate
pip install requests python-dotenv icalendar
"""
import os
import re
import json
import html
import hashlib
from datetime import datetime, timedelta
from math import radians, sin, cos, sqrt, atan2
from pathlib import Path
import requests
from dotenv import load_dotenv
from icalendar import Calendar
# ------------------------------------------------------------
# .env laden
# ------------------------------------------------------------
SCRIPT_DIR = Path(__file__).resolve().parent
load_dotenv(SCRIPT_DIR / ".env")
# ------------------------------------------------------------
# Konfiguration
# ------------------------------------------------------------
# Zentrum: Heidelberg
CENTER_LAT = 49.4094
CENTER_LON = 8.6947
# Radius in Kilometern
RADIUS_KM = 18.0
# True = als Entwurf importieren
# False = direkt veröffentlichen
DRAFT = False
# Feste Dauer je Veranstaltung
EVENT_DURATION_HOURS = 3
# OSMCal API für kommende Veranstaltungen in Deutschland
OSMCAL_API = "https://osmcal.org/api/v2/events/?in=de"
# Mobilizon-Instanz aus .env oder Standardwert
MOBILIZON_INSTANCE = os.environ.get("MOBILIZON_INSTANCE", "https://rheinneckar.events")
MOBILIZON_API = f"{MOBILIZON_INSTANCE.rstrip('/')}/api"
# Diese Werte müssen in .env stehen
MOBILIZON_TOKEN = os.environ["MOBILIZON_TOKEN"]
ORGANIZER_ACTOR_ID = os.environ["MOBILIZON_ORGANIZER_ACTOR_ID"]
ATTRIBUTED_TO_ID = os.environ["MOBILIZON_ATTRIBUTED_TO_ID"]
# Datei zum Vermeiden von Duplikaten, hier werden bearbeitete Veranstaltungen gespeichert.
# vorher leeren wenn alle Veranstaltungen neu importiert werden sollen, mit
# echo '{}' > imported-osmcal-events.json
STATE_FILE = SCRIPT_DIR / "imported-osmcal-events.json"
# ------------------------------------------------------------
# Mobilizon GraphQL Mutation
# ------------------------------------------------------------
CREATE_EVENT_MUTATION = """
mutation createEvent(
$organizerActorId: ID!
$title: String!
$attributedToId: ID
$description: String!
$beginsOn: DateTime!
$endsOn: DateTime
$status: EventStatus
$visibility: EventVisibility
$joinOptions: EventJoinOptions
$draft: Boolean
$tags: [String]
$onlineAddress: String
$physicalAddress: AddressInput
$options: EventOptionsInput
) {
createEvent(
organizerActorId: $organizerActorId
attributedToId: $attributedToId
title: $title
description: $description
beginsOn: $beginsOn
endsOn: $endsOn
status: $status
visibility: $visibility
joinOptions: $joinOptions
draft: $draft
tags: $tags
onlineAddress: $onlineAddress
physicalAddress: $physicalAddress
options: $options
) {
id
uuid
title
url
}
}
"""
# ------------------------------------------------------------
# Allgemeine Hilfsfunktionen
# ------------------------------------------------------------
def clean_text(value):
"""
Wandelt Werte in saubere Strings um.
Gibt None zurück, wenn der Wert leer ist.
"""
if value is None:
return None
value = str(value).strip()
if not value:
return None
return value
def add_hours_to_iso_datetime(iso_datetime, hours):
"""
Addiert Stunden auf eine ISO-Datetime-Zeichenkette.
Beispiel:
2026-05-18T19:00:00+02:00
-> 2026-05-18T22:00:00+02:00
"""
dt = datetime.fromisoformat(iso_datetime)
return (dt + timedelta(hours=hours)).isoformat()
def distance_km(lat1, lon1, lat2, lon2):
"""
Berechnet die Distanz zwischen zwei Koordinaten per Haversine-Formel.
Rückgabe: Kilometer.
"""
earth_radius_km = 6371.0
dlat = radians(lat2 - lat1)
dlon = radians(lon2 - lon1)
a = (
sin(dlat / 2) ** 2
+ cos(radians(lat1))
* cos(radians(lat2))
* sin(dlon / 2) ** 2
)
return 2 * earth_radius_km * atan2(sqrt(a), sqrt(1 - a))
def extract_osmcal_event_id(event_url):
"""
Extrahiert die numerische OSMCal-ID aus URLs wie:
https://osmcal.org/event/4742/
"""
if not event_url:
return None
match = re.search(r"/event/(\d+)/?", event_url)
if not match:
return None
return match.group(1)
def osmcal_event_ics_url(event_url):
"""
Wandelt eine OSMCal-Web-URL in die Einzel-ICS-URL um.
Beispiel:
https://osmcal.org/event/4742/
-> https://osmcal.org/event/4742.ics
"""
event_id = extract_osmcal_event_id(event_url)
if not event_id:
return None
return f"https://osmcal.org/event/{event_id}.ics"
# ------------------------------------------------------------
# Statusdatei
# ------------------------------------------------------------
def save_state(state):
"""
Speichert die Liste bereits importierter Events.
"""
STATE_FILE.write_text(
json.dumps(state, indent=2, ensure_ascii=False),
encoding="utf-8",
)
def load_state():
"""
Lädt die lokale Import-Statusdatei.
Verhalten:
- Datei fehlt: wird mit {} angelegt.
- Datei ist leer: wird mit {} ersetzt.
- Datei ist kaputt: wird gesichert und neu mit {} angelegt.
"""
if not STATE_FILE.exists():
save_state({})
return {}
content = STATE_FILE.read_text(encoding="utf-8").strip()
if not content:
save_state({})
return {}
try:
return json.loads(content)
except json.JSONDecodeError:
backup_file = STATE_FILE.with_suffix(".json.broken")
STATE_FILE.rename(backup_file)
print(f"Warnung: {STATE_FILE.name} war kein gültiges JSON.")
print(f"Defekte Datei wurde gesichert als: {backup_file.name}")
print(f"{STATE_FILE.name} wird neu mit {{}} angelegt.")
save_state({})
return {}
def osmcal_event_key(event):
"""
Erzeugt einen stabilen Schlüssel für die Duplikatvermeidung.
Primär wird die OSMCal-URL genutzt.
Falls sie fehlt, wird ein Hash aus Titel, Startzeit und Ort gebildet.
"""
if event.get("url"):
return event["url"]
raw = "|".join(
[
str(event.get("name", "")),
str(event.get("date", {}).get("start", "")),
str(event.get("location", {}).get("short", "")),
]
)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
# ------------------------------------------------------------
# OSMCal lesen
# ------------------------------------------------------------
def fetch_osmcal_events():
"""
Holt kommende OSMCal-Events für Deutschland.
"""
response = requests.get(
OSMCAL_API,
headers={
"Accept-Language": "de",
"Client-App": "rheinneckar-events-import/0.6",
},
timeout=30,
)
response.raise_for_status()
events = response.json()
if not isinstance(events, list):
raise RuntimeError("OSMCal-Antwort ist keine Event-Liste.")
return events
def is_near_heidelberg(event):
"""
Prüft, ob ein Event im konfigurierten Radius um Heidelberg liegt.
OSMCal liefert coords als [lon, lat].
"""
location = event.get("location") or {}
coords = location.get("coords")
if not coords or len(coords) != 2:
return False
try:
lon = float(coords[0])
lat = float(coords[1])
except (TypeError, ValueError):
return False
distance = distance_km(CENTER_LAT, CENTER_LON, lat, lon)
return distance <= RADIUS_KM
def event_distance(event):
"""
Gibt die Entfernung eines Events zu Heidelberg zurück.
Rückgabe: gerundete Kilometer oder None.
"""
location = event.get("location") or {}
coords = location.get("coords")
if not coords or len(coords) != 2:
return None
try:
lon = float(coords[0])
lat = float(coords[1])
except (TypeError, ValueError):
return None
return round(distance_km(CENTER_LAT, CENTER_LON, lat, lon), 1)
def fetch_osmcal_ics_description(event_url):
"""
Holt die Originalbeschreibung aus der Einzel-ICS-Datei.
OSMCal-API liefert in der Eventliste keine Beschreibung.
Die Einzel-ICS enthält aber normalerweise DESCRIPTION.
"""
ics_url = osmcal_event_ics_url(event_url)
if not ics_url:
return None
response = requests.get(
ics_url,
headers={
"Accept-Language": "de",
"Client-App": "rheinneckar-events-import/0.6",
},
timeout=30,
)
response.raise_for_status()
calendar = Calendar.from_ical(response.content)
for component in calendar.walk():
if component.name != "VEVENT":
continue
description = component.get("DESCRIPTION")
if description:
return str(description).strip()
return None
# ------------------------------------------------------------
# Umwandlung OSMCal -> Mobilizon
# ------------------------------------------------------------
def mobilizon_address_from_osmcal(event):
"""
Wandelt OSMCal-Ortsdaten in Mobilizon AddressInput um.
Wichtig:
physicalAddress.description ist ein String, keine Liste.
"""
location = event.get("location") or {}
coords = location.get("coords")
if not coords or len(coords) != 2:
return None
try:
lon = float(coords[0])
lat = float(coords[1])
except (TypeError, ValueError):
return None
venue = clean_text(location.get("venue"))
short = clean_text(location.get("short"))
detailed = clean_text(location.get("detailed"))
description = venue or short or detailed or "Ort"
address = {
"description": description,
"geom": f"{lon};{lat}",
"country": "DE",
}
if short:
address["locality"] = short
if detailed:
address["street"] = detailed
return address
def mobilizon_description_from_osmcal(event):
"""
Baut die Mobilizon-Beschreibung.
Reihenfolge:
1. Originalbeschreibung aus der OSMCal-ICS
2. Trennlinie
3. Importhinweis und Metadaten
Links werden als HTML erzeugt, nicht als Markdown.
"""
name = clean_text(event.get("name")) or "OSMCal-Veranstaltung"
escaped_name = html.escape(name)
url = clean_text(event.get("url"))
escaped_url = html.escape(url) if url else None
location = event.get("location") or {}
location_text = clean_text(
location.get("venue")
or location.get("detailed")
or location.get("short")
)
distance = event_distance(event)
original_description = clean_text(
event.get("description")
or event.get("details")
or event.get("body")
or event.get("text")
or event.get("summary")
or event.get("content")
)
if not original_description and url:
try:
original_description = fetch_osmcal_ics_description(url)
except Exception as exc:
print(f"Warnung: Beschreibung konnte nicht aus ICS gelesen werden: {url} - {exc}")
parts = []
if original_description:
escaped_description = html.escape(original_description).replace("\n", "<br>")
parts.append(f"<p>{escaped_description}</p>")
parts.append("<hr>")
parts.append("<p>Diese Veranstaltung wurde aus dem OpenStreetMap Calendar importiert.</p>")
if escaped_url:
parts.append(
f'<p><strong>Quelle:</strong> <a href="{escaped_url}">{escaped_url}</a></p>'
)
if location_text:
parts.append(
f"<p><strong>Ort:</strong> {html.escape(location_text)}</p>"
)
if distance is not None:
parts.append(
f"<p><strong>Entfernung von Heidelberg:</strong> {distance} km</p>"
)
parts.append(f"<p><em>Originaltitel:</em> {escaped_name}</p>")
return "\n".join(parts)
# ------------------------------------------------------------
# Mobilizon schreiben
# ------------------------------------------------------------
def create_mobilizon_event(event):
"""
Legt ein Event in Mobilizon an.
Gruppenposting:
- organizerActorId = Profil-ID
- attributedToId = Gruppen-ID
Ende:
- OSMCal-Endzeit wird ignoriert.
- Mobilizon-Endzeit wird immer auf Startzeit + EVENT_DURATION_HOURS gesetzt.
"""
title = clean_text(event.get("name")) or "OSMCal-Veranstaltung"
date = event.get("date") or {}
begins_on = clean_text(date.get("start"))
if not begins_on:
raise ValueError(f"Event ohne Startzeit: {json.dumps(event, ensure_ascii=False)}")
ends_on = add_hours_to_iso_datetime(begins_on, EVENT_DURATION_HOURS)
variables = {
"organizerActorId": ORGANIZER_ACTOR_ID,
"attributedToId": ATTRIBUTED_TO_ID,
"title": title,
"description": mobilizon_description_from_osmcal(event),
"beginsOn": begins_on,
"endsOn": ends_on,
"status": "CONFIRMED",
"visibility": "PUBLIC",
"joinOptions": "FREE",
"draft": DRAFT,
"tags": ["osm", "openstreetmap", "rheinneckar"],
"onlineAddress": clean_text(event.get("url")),
"physicalAddress": mobilizon_address_from_osmcal(event),
"options": {
"commentModeration": "CLOSED",
"showStartTime": True,
"showEndTime": True,
},
}
# None-Werte entfernen, damit Mobilizon keine unnötigen Nullfelder bekommt.
variables = {
key: value
for key, value in variables.items()
if value is not None
}
response = requests.post(
MOBILIZON_API,
headers={
"Authorization": f"Bearer {MOBILIZON_TOKEN}",
"Content-Type": "application/json",
},
json={
"query": CREATE_EVENT_MUTATION,
"variables": variables,
},
timeout=30,
)
try:
payload = response.json()
except Exception:
print("Mobilizon hat keine JSON-Antwort geliefert:")
print(response.text)
raise
if response.status_code >= 400 or payload.get("errors"):
print()
print("Mobilizon-Fehler beim Import dieses Events:")
print(json.dumps(event, indent=2, ensure_ascii=False))
print()
print("Gesendete Variablen:")
print(json.dumps(variables, indent=2, ensure_ascii=False))
print()
print("Antwort von Mobilizon:")
print(json.dumps(payload, indent=2, ensure_ascii=False))
raise RuntimeError("Mobilizon-Import fehlgeschlagen.")
return payload["data"]["createEvent"]
# ------------------------------------------------------------
# Hauptprogramm
# ------------------------------------------------------------
def main():
state = load_state()
events = fetch_osmcal_events()
nearby_events = []
for event in events:
if event.get("cancelled", False):
continue
if is_near_heidelberg(event):
nearby_events.append(event)
print(f"{len(events)} Veranstaltungen aus OSMCal geladen")
print(f"{len(nearby_events)} Veranstaltungen im {RADIUS_KM:g}-km-Umkreis um Heidelberg")
imported = 0
skipped = 0
for event in nearby_events:
key = osmcal_event_key(event)
if key in state:
skipped += 1
continue
created = create_mobilizon_event(event)
state[key] = {
"osmcal_url": event.get("url"),
"mobilizon_id": created.get("id"),
"mobilizon_uuid": created.get("uuid"),
"mobilizon_url": created.get("url"),
"title": event.get("name"),
"start": event.get("date", {}).get("start"),
"distance_km": event_distance(event),
"draft": DRAFT,
"duration_hours": EVENT_DURATION_HOURS,
}
save_state(state)
imported += 1
print(
"Importiert:",
event.get("name"),
"->",
created.get("url") or created.get("uuid") or created.get("id"),
)
print()
print(f"Fertig. Importiert: {imported}, übersprungen: {skipped}")
if DRAFT:
print()
print("Hinweis: DRAFT=True. Die Events wurden als Entwurf angelegt.")
print("Für Veröffentlichung im Script DRAFT = False setzen.")
if __name__ == "__main__":
main()

117
readme.md Normal file
View File

@ -0,0 +1,117 @@
# OSMCal → Mobilizon Importer
EN: Import events from [OSMCal](https://osmcal.org/) into a Mobilizon group, e.g. `https://rheinneckar.events`.
DE: Importiert Veranstaltungen aus dem OpenStreetMap Calendar nach Mobilizon, filtert sie lokal nach Entfernung um Heidelberg und legt sie als Gruppenveranstaltungen an.
---
## Features / Funktionen
- Fetches German OSMCal events via API
Lädt deutsche OSMCal-Veranstaltungen über die API
- Filters events by radius around Heidelberg
Filtert Veranstaltungen nach Radius um Heidelberg
- Reads the original description from each events `.ics` file
Liest die Originalbeschreibung aus der jeweiligen `.ics`-Datei
- Imports into Mobilizon via GraphQL
Importiert nach Mobilizon per GraphQL
- Supports Mobilizon group posting
Unterstützt Veröffentlichung als Mobilizon-Gruppe
- Avoids duplicate imports using a local state file
Verhindert doppelte Importe über eine lokale Statusdatei
---
## Requirements / Voraussetzungen
- Python 3
- Mobilizon account
- Membership in the target Mobilizon group
- OAuth token for the Mobilizon API
Install dependencies:
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install requests python-dotenv icalendar
#auf dem eigenen Rechner voraussetzungen schaffen
#Verzeichnis erstellen und darin ausführen:
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
## Configuration / Konfiguration
Create a .env file:
MOBILIZON_INSTANCE="https://rheinneckar.events"
MOBILIZON_TOKEN="API token"
MOBILIZON_ORGANIZER_ACTOR_ID="profile actor ID"
MOBILIZON_ATTRIBUTED_TO_ID="group actor ID"
#The helper script setup-mobilizon.py can create this .env file.
## Usage / Nutzung
Run the importer:
```bash
source .venv/bin/activate
./import-osmcal-to-mobilizon.py
Example output:
70 Veranstaltungen aus OSMCal geladen
9 Veranstaltungen im 15-km-Umkreis um Heidelberg
Fertig. Importiert: 9, übersprungen: 0
## Settings / Einstellungen
Edit these values in import-osmcal-to-mobilizon.py.
Diese Werte in dieser Datei anpassen
Radius / Radius um die angegebenen Koordinaten
RADIUS_KM = 18.0
Draft mode / Entwurfsmodus
DRAFT = True
Creates drafts / Veranstaltungen werden als Entwurf veröffentlicht.
DRAFT = False
Publishes directly / Veranstaltungen werden direkt veröffentlicht.
Event duration / Veranstaltungsdauer
EVENT_DURATION_HOURS = 3
## Duplicate handling / Umgang mit bereits importierten Veranstaltungen
Imported events are stored in:
imported-osmcal-events.json
Veranstaltungen in dieser Datei werden bei einem erneuten Lauf des Skriptes übersprungen.
Events listed there are skipped on future runs.
Reset for a new test / Zurücksetzen vor einen neuen Lauf:
```bash
echo '{}' > imported-osmcal-events.json
Vorher alte Entwürfe oder Events in Mobilizon löschen, sonst entstehen Duplikate.
Delete old Mobilizon drafts or events first, otherwise duplicates may be created.
Notes / Hinweise
DE:
Bestehende Mobilizon-Events werden nicht aktualisiert.
Bestehende Entwürfe werden nicht automatisch veröffentlicht.
Wenn DRAFT von True auf False geändert wird, werden bereits importierte Events trotzdem übersprungen.
Der Access-Token kann ablaufen und muss dann erneuert werden.
EN:
Existing Mobilizon events are not updated.
Existing drafts are not automatically published.
If DRAFT is changed from True to False, already imported events are still skipped.
The access token may expire and then has to be renewed.

10
requirements.txt Normal file
View File

@ -0,0 +1,10 @@
certifi==2026.4.22
charset-normalizer==3.4.7
icalendar==7.1.0
idna==3.13
python-dateutil==2.9.0.post0
python-dotenv==1.2.2
requests==2.33.1
six==1.17.0
tzdata==2026.2
urllib3==2.6.3

310
setup-mobilizon.py Executable file
View File

@ -0,0 +1,310 @@
#!/usr/bin/env python3
import json
import time
from pathlib import Path
import requests
INSTANCE = "https://rheinneckar.events"
# Wichtig:
# "read" wird benötigt, damit loggedUser.memberships gelesen werden darf.
# Die write:event:* Scopes werden später für das Erstellen/Aktualisieren/Löschen von Events genutzt.
SCOPES = "read write:event:create write:event:update write:event:delete"
APP_FILE = Path("mobilizon-app.json")
TOKEN_FILE = Path("mobilizon-token.json")
ENV_FILE = Path(".env")
def post_form(url, data):
response = requests.post(url, data=data, timeout=30)
print(f"POST {url} -> HTTP {response.status_code}")
try:
payload = response.json()
except Exception:
print("Keine JSON-Antwort:")
print(response.text)
raise SystemExit(1)
if response.status_code >= 400:
print("Fehlerantwort:")
print(json.dumps(payload, indent=2, ensure_ascii=False))
raise SystemExit(1)
return payload
def graphql(access_token, query, variables=None):
response = requests.post(
f"{INSTANCE}/api",
headers={
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
},
json={
"query": query,
"variables": variables or {},
},
timeout=30,
)
print(f"GraphQL -> HTTP {response.status_code}")
try:
payload = response.json()
except Exception:
print("Keine JSON-Antwort:")
print(response.text)
raise SystemExit(1)
if response.status_code >= 400 or payload.get("errors"):
print("GraphQL-Fehler:")
print(json.dumps(payload, indent=2, ensure_ascii=False))
raise SystemExit(1)
return payload["data"]
def register_app():
print("1. App wird registriert...")
app = post_form(
f"{INSTANCE}/apps",
{
"name": "OSMCal Importer",
"redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
"website": INSTANCE,
"scope": SCOPES,
},
)
APP_FILE.write_text(
json.dumps(app, indent=2, ensure_ascii=False),
encoding="utf-8",
)
return app
def request_device_code(client_id):
print()
print("2. Login-Code wird angefordert...")
device = post_form(
f"{INSTANCE}/login/device/code",
{
"client_id": client_id,
"scope": SCOPES,
},
)
print()
print("Öffne diese Adresse im Browser:")
print(device["verification_uri"])
print()
print("Gib dort diesen Code ein:")
print(device["user_code"])
print()
print("Danach hier warten. Das Script fragt automatisch ab, ob du bestätigt hast.")
print()
return device
def wait_for_token(client_id, device):
interval = int(device.get("interval", 5))
expires_in = int(device.get("expires_in", 900))
deadline = time.time() + expires_in
while time.time() < deadline:
time.sleep(interval)
response = requests.post(
f"{INSTANCE}/oauth/token",
data={
"client_id": client_id,
"device_code": device["device_code"],
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
},
timeout=30,
)
try:
payload = response.json()
except Exception:
print("Keine JSON-Antwort beim Token-Abruf:")
print(response.text)
raise SystemExit(1)
if "access_token" in payload:
print("Token erhalten.")
TOKEN_FILE.write_text(
json.dumps(payload, indent=2, ensure_ascii=False),
encoding="utf-8",
)
return payload
error = payload.get("error")
if error == "authorization_pending":
print("Noch nicht bestätigt...")
continue
if error == "slow_down":
print("Server bittet um langsameres Abfragen...")
interval += 5
continue
print("Token-Abruf fehlgeschlagen:")
print(json.dumps(payload, indent=2, ensure_ascii=False))
raise SystemExit(1)
print("Der Login-Code ist abgelaufen. Script neu starten.")
raise SystemExit(1)
def get_memberships(access_token):
print()
print("3. Gruppenmitgliedschaften werden abgefragt...")
query = """
query LoggedUserMemberships($page: Int, $limit: Int) {
loggedUser {
id
memberships(page: $page, limit: $limit) {
total
elements {
role
actor {
id
type
preferredUsername
name
}
parent {
id
type
preferredUsername
name
}
}
}
}
}
"""
data = graphql(
access_token,
query,
variables={
"page": 1,
"limit": 100,
},
)
memberships_data = data.get("loggedUser", {}).get("memberships")
if not memberships_data:
print()
print("Keine Gruppenmitgliedschaften gefunden.")
print("Mögliche Ursachen:")
print("- Du bist mit diesem Account in keiner Gruppe Mitglied.")
print("- Die App wurde nicht mit dem Scope 'read' autorisiert.")
print("- Der verwendete Account ist nicht der erwartete Mobilizon-Account.")
raise SystemExit(1)
memberships = memberships_data.get("elements", [])
if not memberships:
print()
print("Du bist mit diesem Account in keiner Gruppe Mitglied.")
raise SystemExit(1)
return memberships
def choose_membership(memberships):
print()
print("Deine Gruppen:")
print()
for index, membership in enumerate(memberships, start=1):
profile = membership["actor"]
group = membership["parent"]
role = membership["role"]
profile_name = profile.get("name") or profile.get("preferredUsername") or "Profil"
group_name = group.get("name") or group.get("preferredUsername") or "Gruppe"
print(
f"{index}. Gruppe: {group_name} "
f"(group_id={group['id']}) | "
f"Profil: {profile_name} "
f"(profile_id={profile['id']}) | "
f"Rolle: {role}"
)
print()
choice = input("Welche Gruppe soll für den Import verwendet werden? Nummer eingeben: ").strip()
try:
selected = memberships[int(choice) - 1]
except Exception:
print("Ungültige Auswahl.")
raise SystemExit(1)
role = selected["role"]
if role not in ("MEMBER", "MODERATOR", "ADMINISTRATOR"):
print()
print(f"Warnung: Deine Rolle ist {role}.")
print("Falls der Import später fehlschlägt, darf dieses Profil vermutlich keine Gruppen-Events veröffentlichen.")
return selected
def write_env(app, token, membership):
organizer_actor_id = membership["actor"]["id"]
attributed_to_id = membership["parent"]["id"]
lines = [
f'MOBILIZON_INSTANCE="{INSTANCE}"',
f'MOBILIZON_CLIENT_ID="{app["client_id"]}"',
f'MOBILIZON_CLIENT_SECRET="{app.get("client_secret", "")}"',
f'MOBILIZON_TOKEN="{token["access_token"]}"',
f'MOBILIZON_REFRESH_TOKEN="{token.get("refresh_token", "")}"',
f'MOBILIZON_ORGANIZER_ACTOR_ID="{organizer_actor_id}"',
f'MOBILIZON_ATTRIBUTED_TO_ID="{attributed_to_id}"',
]
ENV_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8")
ENV_FILE.chmod(0o600)
print()
print("Fertig. .env wurde geschrieben.")
print()
print("Gesetzte Werte:")
print(f"MOBILIZON_ORGANIZER_ACTOR_ID={organizer_actor_id}")
print(f"MOBILIZON_ATTRIBUTED_TO_ID={attributed_to_id}")
print()
print("Hinweis: Der Access-Token läuft nach einigen Stunden ab.")
print("Für erste Tests reicht das. Für Cron-Betrieb sollte später Refresh-Token-Unterstützung ergänzt werden.")
def main():
app = register_app()
device = request_device_code(app["client_id"])
token = wait_for_token(app["client_id"], device)
memberships = get_memberships(token["access_token"])
selected = choose_membership(memberships)
write_env(app, token, selected)
if __name__ == "__main__":
main()