first working commit

This commit is contained in:
Yessiest 2022-01-29 03:13:34 +04:00
parent 8541bab260
commit 446b22959c
1 changed files with 57 additions and 48 deletions

105
decal
View File

@ -6,7 +6,6 @@ import caldav
import argparse import argparse
import os import os
import json import json
import re
config = configparser.ConfigParser() config = configparser.ConfigParser()
Version = "%(prog)s 0.1" Version = "%(prog)s 0.1"
configpath = os.getenv("HOME")+"/.config/decal.conf" configpath = os.getenv("HOME")+"/.config/decal.conf"
@ -59,7 +58,7 @@ parser.add_argument("-n",
args = vars(parser.parse_args()) args = vars(parser.parse_args())
#check some stuff, do some warnings, initiate the config, etc. #check some stuff, do some warnings, initiate the config, etc.
if not os.path.exists(configpath): if not os.path.exists(configpath):
config['DEFAULT'] = {'uri': 'your caldap server here', config['DEFAULT'] = {'uri': 'your caldav server here',
'user': 'your username here', 'user': 'your username here',
'password': 'your pass here'} 'password': 'your pass here'}
print("Creating an empty config in ~/.config/decal.conf") print("Creating an empty config in ~/.config/decal.conf")
@ -74,7 +73,7 @@ for arg in ("user","password","uri"):
print("The config is incomplete, please check the \""+arg+"\" field") print("The config is incomplete, please check the \""+arg+"\" field")
exit(1) exit(1)
if config['DEFAULT']['uri'] == "your caldap server here": if config['DEFAULT']['uri'] == "your caldav server here":
print("To properly utilize decal, please fill out the fields in the config") print("To properly utilize decal, please fill out the fields in the config")
exit(1) exit(1)
@ -102,8 +101,8 @@ def gencal(year,month,start_on_sunday=True,cell_modifier=lambda d: d,append_year
lines[counter//7] +=" " lines[counter//7] +=" "
counter+=1 counter+=1
month = datetime.date(year,month,1).strftime("%B %Y") month = datetime.date(year,month,1).strftime("%B %Y")
padding = (len(lines[0])-len(month))//2 padding = (21-len(month))//2
rpadding = len(lines[0])%(padding+len(month)+padding) rpadding = 21%(padding+len(month)+padding)
if start_on_sunday: if start_on_sunday:
lines.insert(0,"Su Mo Tu We Th Fr Sa ") lines.insert(0,"Su Mo Tu We Th Fr Sa ")
else: else:
@ -137,13 +136,10 @@ color_names = {
} }
# add a function to colorize terminal text # add a function to colorize terminal text
def colorize(text,color): def colorize(text,c):
if color in color_names: if c in color_names:
return "\033["+color_names[color]+"m"+text+"\033[0m" return "\033["+color_names[c]+"m"+text+"\033[0m"
elif re.match("(\d{1,3}),(\d{1,3}),(\d{1,3})",color): return "\033[38;2;"+str(c[0])+";"+str(c[1])+";"+str(c[2])+"m"+text+"\033[0m"
color = "\\"+re.sub("(\d{1,3}),(\d{1,3}),(\d{1,3})","38;2;\\1;\\2;\\3m",color)
return color+text+"\033[0m"
#calculate offset in months #calculate offset in months
def span(year,month,offset): def span(year,month,offset):
@ -159,6 +155,14 @@ def getbounds(y,m,offset):
(datetime.date(postnextmonth[0],postnextmonth[1],1)-datetime.timedelta(days=1)).day) (datetime.date(postnextmonth[0],postnextmonth[1],1)-datetime.timedelta(days=1)).day)
return start,end return start,end
# generator for year/month pairs
def ympairs(startdate,offset,dstart = False):
if dstart == True:
startdate = span(startdate[0],startdate[1],-1)
for offset in range(offset):
yield span(startdate[0],startdate[1],offset)
return
# we calculate start/end dates and an offset for later use according to arguments # we calculate start/end dates and an offset for later use according to arguments
start = None start = None
end = None end = None
@ -196,49 +200,54 @@ if "calendars" in config['DEFAULT']:
# hooo boy, fun things start here. # hooo boy, fun things start here.
# we generate a dict of (year,month) pairs for easier indexing # we generate a dict of (year,month) pairs for easier indexing
events = {} events = {}
with (args["year"],args["month"]) as startdate: for ympair in ympairs((args['year'],args['month']),offset,dstart=args['3']):
if args["3"]: events[ympair] = {}
startdate = span(args["year"],args["month"],-1)
for offset in range(offset):
events[span(startdate[0],startdate[1],offset)] = {}
# next, we iterate over events in each calendar, sorting them the folliwng way: # next, we iterate over events in each calendar, sorting them the folliwng way:
# events[(int year,int month)][int day] = [event event1, event event2, ...] # events[(int year,int month)][int day] = [event event1, event event2, ...]
# looks awful, is awful, overall i love this. # looks awful, is awful, overall i love this.
for calendar in calendars: for cal in calendars:
events_fetched = calendar.date_search(start,end) events_fetched = cal.date_search(start,end)
for event in events_fetched: for event in events_fetched:
if not event in events: event = event.vobject_instance.vevent.contents
event = event.vobject_instance.vevent.contents curdate = event["dtstart"][0].value + datetime.timedelta(days=-1)
curdate = event["dtstart"][0].value + datetime.timedelta(days=-1) while curdate < event["dtend"][0].value:
while curdate < event["dtend"][0].value: curdate += datetime.timedelta(days=1)
curdate += datetime.timedelta(days=1) curdindex = (curdate.year,curdate.month)
curdindex = (curdate.year,curdate.month) if curdindex in events:
if curdindex in events: if not curdate.day in events[curdindex]:
if not curdate.day in events[curdindex]: events[curdindex][curdate.day] = []
events[curdindex][curdate.day] = [] events[curdindex][curdate.day].append(event)
events[curdindex][curdate.day].append(event) else:
else: break
break
# if you're reading the source code for this (oof), feel free to suggest improvements for this, or, well, anything above or below this comment (as long as it's not just "rewrite this entire thing in C++ for me because i think python bad", "idk how but optimize stuff kthx". just don't be a dick, ok? thanks). # if you're reading the source code for this (oof), feel free to suggest improvements for this, or, well, anything above or below this comment (as long as it's not just "rewrite this entire thing in C++ for me because i think python bad", "idk how but optimize stuff kthx". just don't be a dick, ok? thanks).
# and now we're just generating calendar lines # and now we're just generating calendar lines
calendar_prints = [] cal_prints = []
with (args["year"],args["month"]) as startdate: for year,month in ympairs((args['year'],args['month']),offset,dstart=args['3']):
if args["3"]: # a function to colorize cells in a more or less generic way
startdate = span(args["year"],args["month"],-1) def lambdafunc(cell):
for offset in range(offset): day = int(cell)
# a function to colorize cells in a more or less generic way if day in events[(year,month)]:
curdate = gencal(startdate[0],startdate[1],offset) event = events[(year,month)][day]
def lambdafunc(cell): uid = event[0]["uid"][0].value.encode()
day = int(cell) cell = colorize(cell,uid)
if day in events[(curdate[0],curdate[1])]: if datetime.date(year,month,day) == datetime.date.today():
event = events[(curdate[0],curdate[1])][day] cell = colorize(cell,"inverse")
print(event["uid"][0].value) return cell
exit(0) cal_prints.append(gencal(year,
calendar_prints.append(gencal(curdate[0], month,
curdate[1], cell_modifier=lambdafunc))
cell_modifier=lambdafunc))
def printlines(c1,c2,c3):
for count in range(len(c1)):
line = ""
line += c1.pop(0)+" "
if len(c2) > 0: line += c2.pop(0)+" "
if len(c3) > 0: line += c3.pop(0)+" "
print(line)
for count in range(3-(len(cal_prints)%3)):
cal_prints.append([])
for cal in range(0,len(cal_prints),3):
printlines(cal_prints[cal],cal_prints[cal+1],cal_prints[cal+2])