#!/usr/bin/env python # # a python module for submitting content to a drupal server # import xmlrpclib import time import random import hmac import hashlib import datetime AUTH_FILE = "stadtgestalten_auth.conf" def send_xmlrpc_request(server, session, api_key, api_domain, method, args=[]): timestamp = str(int(time.time())) nonce = str(random.Random().randint(0, 1000000000)) hash_base_string = ";".join([timestamp, api_domain, nonce, method]) hash = hmac.HMAC(api_key, hash_base_string, hashlib.sha256).hexdigest() api_uri = server for item in method.split("."): api_uri = getattr(api_uri, item) if isinstance(args, dict): arr = [] for key, value in args.items(): arr.append(key) arr.append(value) return api_uri(hash, api_domain, timestamp, nonce, session['sessid'], args) elif not isinstance(args, list): args = [args] if len(args) == 0: return api_uri(hash, api_domain, timestamp, nonce, session['sessid']) elif len(args) == 1: return api_uri(hash, api_domain, timestamp, nonce, session['sessid'], args[0]) elif len(args) == 2: return api_uri(hash, api_domain, timestamp, nonce, session['sessid'], args[0], args[1]) elif len(args) == 3: return api_uri(hash, api_domain, timestamp, nonce, session['sessid'], args[0], args[1], args[2]) else: return False def generate_node(title, body, username, time_start, time_finish=None, time_duration_minutes=None): # calculate "time_finish" if it is not defined if time_finish is None: if time_duration_minutes is None: time_finish = time_start + datetime.timedelta(hours=2) else: time_finish = time_start + time_duration_minutes return {'type': 'termin', 'title': title, 'body': body, 'name': username, # new nodes will not be published immediately (status=0) 'status': 0, 'field_kategorie': { 'value': [] }, 'field_termin': { 'value': { 'date': time_start.strftime("%d.%m.%Y"), 'time': time_start.strftime("%H:%M"), }, 'value2': { 'date': time_finish.strftime("%d.%m.%Y"), 'time': time_finish.strftime("%H:%M"), }, 'rrule': { 'FREQ': 'NONE', 'INTERVAL': 0, 'advanced': { 'BYDAY': [''], 'BYMONTH': [''], 'BYMONTHDAY': [''], }, }, } } def submit_drupal_node(auth_file, title, body, time_start, time_finish=None, time_duration_minutes=None): url, api_key, api_domain, username, password = file(auth_file).read().splitlines() server = xmlrpclib.ServerProxy(url) # create a session session = server.system.connect() # login session = send_xmlrpc_request(server, session, api_key, api_domain, "user.login", [username, password]) node = generate_node(title, body, username, time_start, time_finish, time_duration_minutes) result = send_xmlrpc_request(server, session, api_key, api_domain, "node.save", node) send_xmlrpc_request(server, session, api_key, api_domain, "user.logout") return result > 0 if __name__ == "__main__": print submit_drupal_node(AUTH_FILE, "Der Titel", "der Inhalt", datetime.datetime.now())