Commit b7cede54 authored by Karl Fleischmann's avatar Karl Fleischmann

Completely rewrite entry-point

* Outsource almost everything
* Encapsulate all work into two calls to objects/routines
parent a712cfda
#!/usr/bin/env python3
import dbus
import urllib.request
import json
import argparse
import os
from time import sleep
import sys
import itertools
USER_HOME = os.path.expanduser("~")
CACHE_FOLDER = os.path.join(str(USER_HOME),".cache/hack_count")
CACHE_PICTURE_FOLDER = os.path.join(str(USER_HOME),".cache/hack_count/pics")
DEFAULT_CACHE_PICTURE = os.path.join(str(USER_HOME),".cache/hack_count/pics/default.png")
CACHE_FILE = "hack_count.json"
CACHE_PATH = os.path.join(str(CACHE_FOLDER),str(CACHE_FILE))
count_changed=True
import argparse
item = ('org.freedesktop.Notifications')
path = ('/org/freedesktop/Notifications')
interface = ('org.freedesktop.Notifications')
icon = ''
array = ''
hint = ''
time = 10000 # Use seconds x 1000
app_name = ('Hack-Space User Count')
import hc_daemon
import hc_main
###############################################################################
# main entry point
###############################################################################
if __name__ == '__main__':
###parser
parser = argparse.ArgumentParser(description='Access peoplecounter in \
Hackspace and create notification or print the information ')
parser.add_argument("-n","--notify",action="store_true",help="Create a \
notification using dbus (default=False) enable with -n",default=False)
parser.add_argument("-p","--printing",action="store_false",help="Enable or disable\
printing (default=enabled) disable printing with -p",default=True)
parser.add_argument("-u","--show_user",action="store_false",help="Show count\
of users or devices in the hackspace (default=user) toggle with -u)",
default=True)
parser.add_argument("-d","--daemonize",action="store_true",help="Daemonize the\
script (default=False) enable with -d set interval with -i",default=False)
parser.add_argument("-i","--interval",type=int,help="Interval for\
update in seconds (default=30)",default=30)
#### parse command line arguments
# create parser
parser = argparse.ArgumentParser(description='''Access peoplecounter in
Hackspace and create notification or print the information''')
## add arguments to be parsed
# notify option
parser.add_argument(
"-n",
"--notify",
action="store_true",
help="Create a notification using dbus (default=False) enable with -n",
default=False)
# print option
parser.add_argument(
"-p",
"--printing",
action="store_false",
help="""Enable or disable printing (default=enabled)
disable printing with -p""",
default=True)
# show user option
parser.add_argument(
"-u",
"--show_user",
action="store_false",
help="""Show count of users or devices in the hackspace (default=user)
toggle with -u""",
default=True)
# deamon option
parser.add_argument(
"-d",
"--daemonize",
action="store_true",
help="""Daemonize the script (default=False) enable with -d
set interval with -i""",
default=False)
# interval option
parser.add_argument(
"-i",
"--interval",
type=int,
help="Interval for update in seconds (default=30)",
default=30)
# parse arguments from commandline
args = parser.parse_args()
if args.daemonize == True :
print("Printing is disabled because you started hack_count in deamon mode.")
args.printing = False
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError:
sys.stderr.write("fork failed")
sys.exit(1)
while True :
##fetch usercount
var = urllib.request.urlopen("http://hack-hro.de/api/users")
json_string = var.read()
json_dict = json.loads(json_string.decode('ascii'))
device_count = json_dict['deviceCount']
users = json_dict['users']
#####create cache folder if not exsits####
if not os.path.exists(CACHE_PICTURE_FOLDER) :
os.makedirs(CACHE_PICTURE_FOLDER)
if not os.path.isfile(DEFAULT_CACHE_PICTURE):
urllib.request.urlretrieve("http://hack-hro.de/avatar/default.png",DEFAULT_CACHE_PICTURE)
for user in users :
user_image_path = os.path.join(CACHE_PICTURE_FOLDER,str(user['id'])+".jpg")
if not os.path.isfile(user_image_path) :
try :
user['avatar']
except :
pass
else :
urllib.request.urlretrieve("http://hack-hro.de"+user['avatar'],user_image_path)
####fetch cached vals
try:
cached_data_dict=json.loads(open(CACHE_PATH).read())
count_changed=False
except:
open(CACHE_PATH, 'a').close()
cached_data_dict={
"device_count" : 0,
"users" : users
}
#compare saved and fetched value
if args.show_user == True and (cached_data_dict['device_count'] != device_count ) :
count_changed=True
#diff saved and new recieved list
user_diff_fetched = list(itertools.filterfalse(lambda x: x in
cached_data_dict['users'],users))
user_diff_saved = list(itertools.filterfalse(lambda x: x in
users, cached_data_dict['users']))
#####prepare to save value
save_cache_dict= {
"device_count" : device_count,
"users" : users
}
if user_diff_fetched.__len__() > 0 :
count_changed = True
user_new_list = user_diff_fetched
if user_diff_saved.__len__() > 0 :
count_changed = True
user_left_list = user_diff_saved
### save to cachefile ####
with open(os.path.join(str(CACHE_FOLDER),str(CACHE_FILE)),"w+" ) as iofile:
json.dump(save_cache_dict,iofile)
iofile.close()
##print count
if args.printing == True :
if args.show_user == False :
print ("HackHro Users: %s " % users.__len__(),end="")
try:
user_left_list
except NameError:
pass
else:
print ("Users left: ",end="",flush = True)
for user in user_left_list :
print (user['name']+" " ,end="",flush = True )
try:
user_new_list
except NameError :
pass
else :
print ("Users new: ",end="",flush = True )
for user in user_new_list :
print (user['name']+" ",end="",flush = True )
else :
print ("HackHro Devcies: ",device_count,flush = True )
##notification
if args.notify and count_changed == True :
###init dbus notifications
bus = dbus.SessionBus()
notif = bus.get_object(item, path)
notify = dbus.Interface(notif, interface)
notification_string = ""
if args.show_user == False :
title = "HackSpace Users Changed"
try:
user_left_list
except NameError:
pass
else:
for user in user_left_list :
icon = os.path.join(CACHE_PICTURE_FOLDER,str(user['id'])+".jpg")
if not os.path.isfile(icon):
icon = os.path.join(CACHE_PICTURE_FOLDER,"default.png")
notification_string = "the user "+str(user['name'])+" left."
#create notification
notify.Notify(app_name, 0, icon, title, notification_string, array, hint, time)
try:
user_new_list
except NameError :
pass
else :
for user in user_new_list :
icon = os.path.join(CACHE_PICTURE_FOLDER,str(user['id'])+".jpg")
if not os.path.isfile(icon):
icon = os.path.join(CACHE_PICTURE_FOLDER,"default.png")
notification_string = "the user "+str(user['name'])+" just came in."
#create notification
notify.Notify(app_name, 0, icon, title, notification_string, array, hint, time)
else :
title = "HackSpace Devices Changed"
notification_string = str(device_count)
#create notification
notify.Notify(app_name, 0, icon, title, notification_string, array, hint, time)
count_changed = False
try:
del user_new_list
del user_left_list
except:
pass
if not args.daemonize == True :
sys.exit(0)
sleep(args.interval)
if args.daemonize:
hc_daemon.Daemon(args).start()
try:
# create Main object and start it
hc_main.Main(args).start()
except KeyboardInterrupt:
print('\rExiting on Keyboard-Interrupt...')
exit(0)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment