--- /dev/null
+# liszt_util.py - classes used both by liszt and liszt-daemon.
+
+import os, sys
+import urllib, urllib2, cookielib
+from urllib import quote
+from urllib2 import HTTPError, URLError
+import atexit
+from signal import SIGTERM
+
+try:
+ import json
+except ImportError:
+ import simplejson as json
+
+base = "http://0.0.0.0:8080/api/v1"
+
+def bailout(msg):
+ print msg
+ return
+
+
+# The Daemon class comes from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
+class Daemon:
+ """
+ A generic daemon class.
+
+ Usage: subclass the Daemon class and override the run() method
+ """
+ def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
+ self.stdin = stdin
+ self.stdout = stdout
+ self.stderr = stderr
+ self.pidfile = pidfile
+
+ def daemonize(self):
+ """
+ do the UNIX double-fork magic, see Stevens' "Advanced
+ Programming in the UNIX Environment" for details (ISBN 0201563177)
+ http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
+ """
+ try:
+ pid = os.fork()
+ if pid > 0:
+ # exit first parent
+ sys.exit(0)
+ except OSError, e:
+ sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
+ sys.exit(1)
+
+ # do second fork
+ try:
+ pid = os.fork()
+ if pid > 0:
+ # exit from second parent
+ sys.exit(0)
+ except OSError, e:
+ sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
+ sys.exit(1)
+
+ # redirect standard file descriptors
+ sys.stdout.flush()
+ sys.stderr.flush()
+ si = file(self.stdin, 'r')
+ so = file(self.stdout, 'a+')
+ se = file(self.stderr, 'a+', 0)
+ os.dup2(si.fileno(), sys.stdin.fileno())
+ os.dup2(so.fileno(), sys.stdout.fileno())
+ os.dup2(se.fileno(), sys.stderr.fileno())
+
+ # write pidfile
+ atexit.register(self.delpid)
+ pid = str(os.getpid())
+ file(self.pidfile,'w+').write("%s\n" % pid)
+
+ def delpid(self):
+ os.remove(self.pidfile)
+
+ def start(self):
+ """
+ Start the daemon
+ """
+ # Check for a pidfile to see if the daemon already runs
+ try:
+ pf = file(self.pidfile,'r')
+ pid = int(pf.read().strip())
+ pf.close()
+ except IOError:
+ pid = None
+
+ if pid:
+ message = "pidfile %s already exist. Daemon already running?\n"
+ sys.stderr.write(message % self.pidfile)
+ sys.exit(1)
+
+ # Start the daemon
+ self.daemonize()
+ self.run()
+
+ def stop(self):
+ """
+ Stop the daemon
+ """
+ # Get the pid from the pidfile
+ try:
+ pf = file(self.pidfile,'r')
+ pid = int(pf.read().strip())
+ pf.close()
+ except IOError:
+ pid = None
+
+ if not pid:
+ message = "pidfile %s does not exist. Daemon not running?\n"
+ sys.stderr.write(message % self.pidfile)
+ return # not an error in a restart
+
+ # Try killing the daemon process
+ try:
+ while 1:
+ os.kill(pid, SIGTERM)
+ time.sleep(0.1)
+ except OSError, err:
+ err = str(err)
+ if err.find("No such process") > 0:
+ if os.path.exists(self.pidfile):
+ os.remove(self.pidfile)
+ else:
+ print str(err)
+ sys.exit(1)
+
+ def restart(self):
+ """
+ Restart the daemon
+ """
+ self.stop()
+ self.start()
+
+ def run(self):
+ """
+ You should override this method when you subclass Daemon. It will be called after the process has been
+ daemonized by start() or restart().
+ """
+ pass
+
+
+class LisztSession:
+ def __init__(self):
+
+ self.jar = cookielib.LWPCookieJar()
+ if os.path.isfile(os.path.expanduser('~/.liszt/cookiejar')):
+ self.jar.load(os.path.expanduser('~/.liszt/cookiejar'))
+
+ self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.jar))
+ urllib2.install_opener(self.opener)
+
+ def login(self, username, password):
+ d = {'username' : username, 'password': password}
+ ed = urllib.urlencode(d)
+
+ while True:
+ try:
+ urllib2.urlopen(base + "/login/", ed)
+ return
+ except URLError, HTTPError:
+ print "Unable to log you in"
+ time.sleep(5 * 60) # Try to reconnect every five minutes.
+ continue
+
+ def create_list(self, listname):
+ listname = listname.encode("utf8")
+ try:
+ urllib2.urlopen(base + "/create/" + quote(listname) + "/")
+ except HTTPError:
+ bailout("Unable to create the list " + listname)
+
+ def create_list_entry(self, listname, entry):
+ listname = listname.encode("utf8")
+ entry = entry.encode("utf8")
+
+ try:
+ urllib2.urlopen(base + "/create/" + quote(listname) + "/" + quote(entry) + "/")
+ except HTTPError:
+ bailout("Unable to create the list entry in list " + listname)
+
+ def get_lists_list(self):
+ try:
+ req = urllib2.urlopen(base + "/getlists/")
+ except HTTPError:
+ bailout("Unable to get a list of the available lists")
+
+ return json.load(req)
+
+ def get_list(self, listname):
+ try:
+ req = urllib2.urlopen(base + "/get/" + quote(listname) + "/")
+ except HTTPError:
+ bailout("Unable to open the list " + listname)
+
+ return json.load(req)
+
+ def get_entry(self, listname, index):
+ try:
+ req = urllib2.urlopen(base + "/get/" + quote(listname) + "/" + str(index) + "/")
+ except HTTPError:
+ bailout("Unable to get entry " + str(index) + " from list " + listname)
+
+ return json.load(req)
+
+ def remove_list(self, listname):
+ try:
+ urllib2.urlopen(base + "/remove/" + quote(listname) + "/")
+ except HTTPError:
+ bailout("Unable to remove the list " + listname)
+
+ def remove_list_entry(self, listname, index):
+ try:
+ urllib2.urlopen(base + "/remove/" + quote(listname) + "/" + quote(index) + "/")
+ except HTTPError:
+ bailout("Unable to remove the entry " + index + "from list " + listname)
+
+ def update_list_entry(self, listname, index, contents):
+ ec = urllib.urlencode(contents)
+ try:
+ urllib2.urlopen(base + "/update/" + listname + "/" + str(index) + "/", ec)
+ except HTTPError:
+ bailout("Unable to update the list entry")
+
+# Cached list manages a list cached on the client.
+class CachedList(object):
+ def __init__(self, listname):
+ try:
+ self.listname = listname
+ fd = open(os.path.expanduser('~/.liszt/cached/') + listname)
+ try:
+ self.cached_list = json.load(fd)
+ except ValueError:
+ bailout("List <%s> is not a valid json file" % listname)
+
+ except IOError:
+ # Create it.
+ try:
+ fd = open(os.path.expanduser('~/.liszt/cached/') + listname, 'w+')
+ except IOError:
+ bailout("IOError when trying to create a cached list.")
+
+ self.cached_list = {"name" : listname, "contents" : []}
+
+ def save(self):
+ fd = open(os.path.expanduser('~/.liszt/cached/') + self.listname, 'w+')
+ json.dump(self.cached_list, fd, encoding="utf8")
+
+ def remove(self):
+ os.unlink(os.path.expanduser('~/.liszt/cached/') + self.listname)
+
+ def fget(self):
+ return self.cached_list
+
+ def fset(self, list):
+ self.cached_list = list
+
+ def fdel(self):
+ del self.cached_list
+
+ contents = property(fget, fset, fdel)
import datetime
import locale
import codecs
+from libliszt.utils import CachedList
try:
import json
os.write(fd, json.dumps(dict))
os.close(fd)
-class CachedList(object):
- def __init__(self, listname):
- try:
- self.listname = listname
- fd = open(os.path.expanduser('~/.liszt/cached/') + listname)
- try:
- self.cached_list = json.load(fd)
- except ValueError:
- bailout("List <%s> is not a valid json file" % listname)
-
- except IOError:
- # Create it.
- try:
- fd = open(os.path.expanduser('~/.liszt/cached/') + listname, 'w+')
- except IOError:
- bailout("IOError when trying to create a cached list.")
-
- self.cached_list = {"name" : listname, "contents" : []}
-
- def save(self):
- fd = open(os.path.expanduser('~/.liszt/cached/') + self.listname, 'w+')
- json.dump(self.cached_list, fd, encoding="utf8")
-
- def remove(self):
- os.unlink(os.path.expanduser('~/.liszt/cached/') + self.listname)
-
- def fget(self):
- return self.cached_list
-
- def fset(self, list):
- self.cached_list = list
-
- def fdel(self):
- del self.cached_list
-
- contents = property(fget, fset, fdel)
def glob_listname(pattern):
import os
import sets
from datetime import datetime
-import urllib, urllib2, cookielib
-from urllib import quote
-from urllib2 import HTTPError, URLError
-import subprocess
-from subprocess import Popen
-import fnmatch
-import tempfile
import thread
import time
import ConfigParser
-import atexit
-from signal import SIGTERM
+
+from libliszt.utils import Daemon, LisztSession
+
try:
import json
import simplejson as json
-base = "http://0.0.0.0:8080/api/v1"
-
conf = ConfigParser.RawConfigParser()
conf.read(os.path.expanduser('~/.liszt/config'))
username = conf.get('Credentials', 'username')
password = conf.get('Credentials', 'password')
-
-# The Daemon class comes from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
-class Daemon:
- """
- A generic daemon class.
-
- Usage: subclass the Daemon class and override the run() method
- """
- def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
- self.stdin = stdin
- self.stdout = stdout
- self.stderr = stderr
- self.pidfile = pidfile
-
- def daemonize(self):
- """
- do the UNIX double-fork magic, see Stevens' "Advanced
- Programming in the UNIX Environment" for details (ISBN 0201563177)
- http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
- """
- try:
- pid = os.fork()
- if pid > 0:
- # exit first parent
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
- sys.exit(1)
-
- # do second fork
- try:
- pid = os.fork()
- if pid > 0:
- # exit from second parent
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
- sys.exit(1)
-
- # redirect standard file descriptors
- sys.stdout.flush()
- sys.stderr.flush()
- si = file(self.stdin, 'r')
- so = file(self.stdout, 'a+')
- se = file(self.stderr, 'a+', 0)
- os.dup2(si.fileno(), sys.stdin.fileno())
- os.dup2(so.fileno(), sys.stdout.fileno())
- os.dup2(se.fileno(), sys.stderr.fileno())
-
- # write pidfile
- atexit.register(self.delpid)
- pid = str(os.getpid())
- file(self.pidfile,'w+').write("%s\n" % pid)
-
- def delpid(self):
- os.remove(self.pidfile)
-
- def start(self):
- """
- Start the daemon
- """
- # Check for a pidfile to see if the daemon already runs
- try:
- pf = file(self.pidfile,'r')
- pid = int(pf.read().strip())
- pf.close()
- except IOError:
- pid = None
-
- if pid:
- message = "pidfile %s already exist. Daemon already running?\n"
- sys.stderr.write(message % self.pidfile)
- sys.exit(1)
-
- # Start the daemon
- self.daemonize()
- self.run()
-
- def stop(self):
- """
- Stop the daemon
- """
- # Get the pid from the pidfile
- try:
- pf = file(self.pidfile,'r')
- pid = int(pf.read().strip())
- pf.close()
- except IOError:
- pid = None
-
- if not pid:
- message = "pidfile %s does not exist. Daemon not running?\n"
- sys.stderr.write(message % self.pidfile)
- return # not an error in a restart
-
- # Try killing the daemon process
- try:
- while 1:
- os.kill(pid, SIGTERM)
- time.sleep(0.1)
- except OSError, err:
- err = str(err)
- if err.find("No such process") > 0:
- if os.path.exists(self.pidfile):
- os.remove(self.pidfile)
- else:
- print str(err)
- sys.exit(1)
-
- def restart(self):
- """
- Restart the daemon
- """
- self.stop()
- self.start()
-
- def run(self):
- """
- You should override this method when you subclass Daemon. It will be called after the process has been
- daemonized by start() or restart().
- """
-
-
-class LisztSession:
- def __init__(self):
-
- self.jar = cookielib.LWPCookieJar()
- if os.path.isfile(os.path.expanduser('~/.liszt/cookiejar')):
- self.jar.load(os.path.expanduser('~/.liszt/cookiejar'))
-
- self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.jar))
- urllib2.install_opener(self.opener)
-
- def login(self, username, password):
- d = {'username' : username, 'password': password}
- ed = urllib.urlencode(d)
-
- while True:
- try:
- urllib2.urlopen(base + "/login/", ed)
- return
- except URLError, HTTPError:
- print "Unable to log you in"
- time.sleep(5 * 60) # Try to reconnect every five minutes.
- continue
-
- def create_list(self, listname):
- listname = listname.encode("utf8")
- try:
- urllib2.urlopen(base + "/create/" + quote(listname) + "/")
- except HTTPError:
- bailout("Unable to create the list " + listname)
-
- def create_list_entry(self, listname, entry):
- listname = listname.encode("utf8")
- entry = entry.encode("utf8")
-
- try:
- urllib2.urlopen(base + "/create/" + quote(listname) + "/" + quote(entry) + "/")
- except HTTPError:
- bailout("Unable to create the list entry in list " + listname)
-
- def get_lists_list(self):
- try:
- req = urllib2.urlopen(base + "/getlists/")
- except HTTPError:
- bailout("Unable to get a list of the available lists")
-
- return json.load(req)
-
- def get_list(self, listname):
- ln = self.glob_listname(listname)
-
- try:
- req = urllib2.urlopen(base + "/get/" + quote(ln) + "/")
- except HTTPError:
- bailout("Unable to open the list " + listname)
-
- return json.load(req)
-
- def get_entry(self, listname, index):
- ln = self.glob_listname(listname)
-
- try:
- req = urllib2.urlopen(base + "/get/" + quote(ln) + "/" + str(index) + "/")
- except HTTPError:
- bailout("Unable to get entry " + str(index) + " from list " + listname)
-
- return json.load(req)
-
- def remove_list(self, listname):
- try:
- urllib2.urlopen(base + "/remove/" + quote(listname) + "/")
- except HTTPError:
- bailout("Unable to remove the list " + listname)
-
- def remove_list_entry(self, listname, index):
- try:
- urllib2.urlopen(base + "/remove/" + quote(listname) + "/" + quote(index) + "/")
- except HTTPError:
- bailout("Unable to remove the entry " + index + "from list " + listname)
-
- def update_list_entry(self, listname, index, contents):
- ec = urllib.urlencode(contents)
- try:
- urllib2.urlopen(base + "/update/" + listname + "/" + str(index) + "/", ec)
- except HTTPError:
- bailout("Unable to update the list entry")
-
- def glob_listname(self, pattern):
-
- def match_listname(l):
- # This function doesn't seem very pythonic...
- if len(l) > 1:
- print str(len(l)) + " lists satifisfy the pattern : "
- print l
-
- try:
- pat = raw_input("Enter a matching pattern to clarify your choice : ")
- except EOFError:
- sys.exit(-1)
-
- return match_listname(fnmatch.filter(l, pat))
- else:
- return l[0]
-
- try:
- lists = self.get_lists_list()
- res = fnmatch.filter(lists, pattern)
-
- if len(res) > 1:
- return match_listname(res)
- else:
- return res[0]
-
- except HTTPError:
- bailout("Unable to glob list pattern")
-
def process_json_delayed_file(path):
try:
fd = open(path)
return
elif data["request"] == "update-entry":
try:
- session.update_entry(data["listname"], data["content"]["index"], data["content"])
+ session.update_list_entry(data["listname"], data["content"]["index"], data["content"])
except KeyError:
return
while True:
for file in os.listdir(os.path.expanduser('~/.liszt/delayed/')):
process_json_delayed_file(os.path.expanduser('~/.liszt/delayed/') + file)
-
+
time.sleep(15 * 60) # Sync the files with the server every 15 minutes.
+def cache_lists_list():
+# l = set(session.get_lists_list())
+# fd = open(os.path.expanduser('~/.liszt/cached/'), 'w+')
+# json.dump(l, fd)
+# fd.close()
+ pass
+
def cache_new_lists():
# This thread caches lists that were recently created on the server but are not available
# on the client.
sync_cached_list(os.path.expanduser('~/.liszt/cached/') + file)
time.sleep(20 * 60) # Sync the files with the server every 20 minutes.
-
-if __name__ == "__main__":
+# class LisztDaemon(Daemon):
+# def run(self):
+# pass
+
+if __name__ == "__main__":
session = LisztSession()
session.login(username, password)
-
+
thread.start_new_thread(watch_spool_dir, ())
thread.start_new_thread(cache_new_lists, ())
+# daemon = LisztDaemon(pidfile="/var/lock/liszt-daemon.pidfile")
- while 1:pass
# This program setups the ~/.liszt directory.
import os
+import ConfigParser
-path = os.path.expanduser('~/.liszt')
+path = os.path.expanduser('~/.liszt/')
if os.access(path, os.F_OK):
os.chdir(path)
os.mkdir("delayed")
os.mkdir("cached")
os.system("echo [] > cached/lists_list")
+
+config = ConfigParser.RawConfigParser()
+
+username = raw_input("Please enter your username : ").strip()
+password = raw_input("Please enter your password : ").strip()
+
+config.add_section('Credentials')
+config.set('Credentials', 'password', password)
+config.set('Credentials', 'username', username)
+
+try:
+ conffd = open(path + "config", 'w+')
+except IOError:
+ print "Unable to open configuration file for writing"
+ sys.exit(-1)
+
+config.write(conffd)
+
+print "\nThe configuration file has been created. It's time to create lists !"