Add range parameter.

This commit is contained in:
redxef 2022-10-13 11:06:44 +02:00
parent 8460f70216
commit 69b11d513a
Signed by: redxef
GPG key ID: 7DAC3AA211CBD921
3 changed files with 66 additions and 16 deletions

View file

@ -12,6 +12,7 @@ from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
logger = logging.getLogger(f"wp_cal.{__name__}")
print(logger.name)
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

View file

@ -56,9 +56,15 @@ class Wordpress():
'wp-submit': 'Anmelden',
'redirect_to': f'{self.base_url}/wp-admin/',
'testcookie': 1,
}
},
allow_redirects=False,
)
return login_request
logger.debug('login request return headers = %s', login_request.headers)
login_request_cookies = [x.strip() for x in login_request.headers['Set-Cookie'].split(',')]
if len(login_request_cookies) > 1:
logger.debug('login seems to be ok, cookies = %s', login_request_cookies)
return True
return False
def _datestr_to_date(self, s, tz=None):
if s.endswith('Z'):
@ -118,8 +124,8 @@ class Wordpress():
start: datetime.datetime | None=None,
until: datetime.timedelta | None=None
):
until = until if until else datetime.timedelta(days=365)
start = start if start else datetime.datetime.utcnow().astimezone()
until = until if until else datetime.timedelta(days=365)
final_dict = {}
for event in events:
@ -132,9 +138,9 @@ class Wordpress():
)
return final_dict
def post_events(self, events):
def post_events(self, events, start: datetime.datetime | None=None, until: datetime.timedelta | None=None):
metadata = self.calendar_meadata.to_dict()
data = self._generate_data(events)
data = self._generate_data(events, start=start, until=until)
update_request = self.session.post(
f'{self.base_url}/wp-admin/admin-ajax.php',
auth=(self.credentials['user'], self.credentials['password']),
@ -144,5 +150,5 @@ class Wordpress():
'calendar_data': json.dumps(data),
},
)
return update_request
return 'wpbs_message=calendar_update_success' in update_request.text

63
main.py
View file

@ -5,6 +5,7 @@ import os
import sys
import yaml
import logging
import datetime
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
@ -14,7 +15,7 @@ import click
from adapters import *
logger = logging.getLogger(f'wp_cal.{__name__}')
logger = logging.getLogger(f'wp_cal')
class BaseConfig(dict):
@ -84,6 +85,7 @@ class Config(BaseConfig):
.wordpress.credentials.user: the user as which to log into wordpress
.wordpress.credentials.password: the users password
.logging.level: one or more log levels of the form <module.submodule>:<level> seperated by a `,` (comma)
.range: the range in the format <nnn><u>, where n are digits and u is the unit; valid units: 'smhdw' <-> seconds minutes hours days weeks
"""
def __init__(self, file, defaults, *args, **kwargs):
@ -101,7 +103,41 @@ class Config(BaseConfig):
defaults = [(x[0].split('.'), x[1]) for x in defaults]
super().__init__(file, defaults, *args, **kwargs)
def init_logging(level: str):
def range_str_to_timedelta(value):
valid_units = 'smhdw'
current_int = 0
values = {}
for c in value:
if c in '0123456789':
current_int *= 10
current_int += int(c)
elif c in valid_units:
if c in values:
logger.warning('unit %s already in values, overwriting', c)
values[c] = current_int
current_int = 0
c = 's'
if current_int != 0:
if c in values:
logger.warning('unit %s already in values, overwriting', c)
values['s'] = current_int
for valid_unit in valid_units:
values.setdefault(valid_unit, 0)
return datetime.timedelta(
seconds=values['s'],
minutes=values['m'],
hours=values['h'],
days=values['d'],
weeks=values['w']
)
def init_logging():
logging.getLogger().addHandler(
logging.StreamHandler(),
)
def set_logging_level(level: str):
allowed_values = {'NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'}
log_levels = [x.split(':') for x in level.split(',')]
@ -117,11 +153,12 @@ def init_logging(level: str):
@click.option('--level', '-l', envvar='WP_CAL_LEVEL', default=':WARNING,wp_cal:INFO', help='The log level for the application')
@click.option('--config', '-c', envvar='WP_CAL_CONFIG', default='-', help='The configuration file')
@click.option('--dryrun', '-d', envvar='WP_CAL_DRYRUN', is_flag=True, help="Don't actually post any data, just show it")
def main(level, config, dryrun):
logging.basicConfig()
init_logging(level)
@click.option('--range', '-r', envvar='WP_CAL_RANGE', default='365d', help='The time range from start to start + range to synchronize events')
def main(level, config, dryrun, range):
init_logging()
set_logging_level(level)
config = Config(config, [('logging.level', ':WARNING,wp_cal:INFO')])
config = Config(config, [('logging.level', level), ('range', range)])
if config.exception():
logger.info('config not found, trying to generate template')
try:
@ -132,7 +169,8 @@ def main(level, config, dryrun):
logger.info('generated config at "%s"', config.file)
return
init_logging(config['logging']['level'])
set_logging_level(config['logging']['level'])
config['range'] = range_str_to_timedelta(config['range'])
g = Google(
config['google']['calendar_id'],
@ -149,14 +187,19 @@ def main(level, config, dryrun):
credentials=config['wordpress']['credentials'],
)
g.login()
events = g.get_events()
events = g.get_events(until=config['range'])
logger.info("syncing %d events", len(events))
w.login()
if not w.login():
logger.info('failed to login to wordpress')
return 1
if dryrun:
logger.info("dryrun; would post events: %s", events)
else:
w.post_events(events)
if not w.post_events(events, until=config['range']):
logger.info('failed to post event data')
return 1
logger.info("done")
return 0
if __name__ == '__main__':
main()