Commits

Josh VanderLinden committed c6a575c

Finished working on the API changes

Comments (0)

Files changed (4)

clip2zeus/common.py

     import json
 except ImportError:
     import simplejson as json
-    
+
 import socket
 import sys
 import time
+import traceback
 import urllib
 import urllib2
 import xmlrpclib
         self.server = None
         self._has_connection = False
         self.last_check = None
-        self.interval = config.get('main', 'interval', 1)
-        self.api_key = config.get('main', 'api_key', '')
+        self.interval = config.getint('main', 'interval', 1)
+        self.api_key = config.get('main', 'api_key', '').replace('|', ':')
+
+        logging.debug('API Key: %s' % self.api_key)
+
         self.threshold = timedelta(seconds=HEARTBEAT_INT)
         socket.setdefaulttimeout(TIMEOUT_SEC)
 
                     'url': url,
                     'api': self.api_key,
                 })
+                logger.debug('Request: %s' % params)
 
                 try:
                     logger.info(' - %s' % url)
                     c = UrlOpener.open('http://2ze.us/generate/', params)
-                    c.add_header('X-Requested-With', 'clip2zeus')
                 except (urllib2.HTTPError, urllib2.URLError):
                     # do something?
                     update_data = False
                     except (ValueError, ):
                         usable = None
 
-                if usable and usable['urls'].get(url, None):
-                    short = usable['urls'][url]['shortcut']
+                if usable and usable.get('url', None):
+                    short = usable['url']['shortcut']
                     logger.info('   -> %s' % short)
-                    data = data.replace(url, short)
+                    try:
+                        data = data.replace(url, short)
+                    except:
+                        logger.debug('An error occurred: %s' % traceback.format_exc())
 
         self.data = data
 
 
         logger.debug('API key updated by client: %s' % (api_key,))
         self.api_key = api_key
-        config.set('main', 'api_key', api_key)
+        config.set('main', 'api_key', api_key.replace(':', '|'))
 
     def quit(self):
         """Ends processing"""

clip2zeus/config.py

-from ConfigParser import SafeConfigParser
+from ConfigParser import SafeConfigParser as SCP
 import logging
 import os
 import re
 
 CONFIG_FILE = os.path.join(CONFIG_DIR, 'clip2zeus.conf')
 
-class Clip2ZeusConfig(SafeConfigParser):
+class Clip2ZeusConfig(object):
 
-    __instance = None
+    def __init__(self, conf_file):
+        self.conf_file = conf_file
+        self.parser = SCP()
+        self.parser.read([self.conf_file])
 
     def get(self, section, option, default=None):
         """Allows default values to be returned if necessary"""
 
-        if self.has_section(section) and self.has_option(section, option):
-            return SafeConfigParser.get(self, section, option)
+        if self.parser.has_section(section) and self.parser.has_option(section, option):
+            return self.parser.get(section, option)
         else:
             return default
 
     def set(self, section, option, value):
         """Sets some configuration value and persists to disk"""
 
-        if not self.has_section(section):
-            self.add_section(section)
+        if not self.parser.has_section(section):
+            self.parser.add_section(section)
 
-        SafeConfigParser.set(self, section, option, str(value))
-        self.write(open(CONFIG_FILE, 'w'))
+        self.parser.set(section, option, str(value))
+        self.parser.write(open(self.conf_file, 'w'))
 
-    @classmethod
-    def instance(cls):
-        if cls.__instance is None:
-            # make sure the file exists
-            if not os.path.exists(CONFIG_FILE):
-                open(CONFIG_FILE, 'w')
-
-            cls.__instance = Clip2ZeusConfig()
-            cls.__instance.read(open(CONFIG_FILE))
-
-        return cls.__instance
-
-config = Clip2ZeusConfig.instance()
+config = Clip2ZeusConfig(CONFIG_FILE)
 
 DELIM = ' \n\r<>"\''
 URL_RE = re.compile('((\w+)://([^/%%%s]+)(/?[^%s]*))' % (DELIM, DELIM), re.I | re.M)
 
         logger.debug('Creating widgets')
         self.opt_value = tk.IntVar()
+        self.api_key = tk.StringVar()
+
         self.opt_poll = tk.Radiobutton(self.parent, text='Automatic shortening',
             value=ID_AUTO, variable=self.opt_value, command=self.mode_selected)
         self.opt_manual = tk.Radiobutton(self.parent, text='Manual shortening',
         self.scl_interval = tk.Scale(self.parent, from_=0, to=30,
             label='Interval', orient=tk.HORIZONTAL, tickinterval=10,
             command=self.mode_selected)
-        self.txt_api = tk.Text(self.parent, text='API Key', variable=self.api_key,
-            command=self.api_changed)
+        self.lbl_api = tk.Label(self.parent, text='API Key')
+        self.txt_api = tk.Entry(self.parent, textvariable=self.api_key)
 
         self.btn_shorten = tk.Button(self.parent, text="Shorten", command=self.check_clipboard)
+        self.btn_save = tk.Button(self.parent, text="Save Settings", command=self.api_changed)
         self.btn_quit = tk.Button(self.parent, text="Quit", command=self.quit)
 
         logger.debug('Arranging widgets')
         self.opt_manual.grid(row=0, column=0, sticky='w')
         self.opt_poll.grid(row=1, column=0, sticky='w')
+
+        self.lbl_api.grid(row=2, column=0, sticky='w')
+        self.txt_api.grid(row=3, column=0, sticky='we')
+        self.scl_interval.grid(row=4, column=0, columnspan=2, sticky='we')
+
         self.btn_shorten.grid(row=0, column=1, sticky='we')
-        self.btn_quit.grid(row=1, column=1, sticky='we')
-        self.scl_interval.grid(row=2, column=0, columnspan=2, sticky='we')
-        self.txt_api.grid(row=3, column=0, columnspan=2, sticky='we')
+        self.btn_save.grid(row=1, column=1, sticky='we')
+        self.btn_quit.grid(row=2, column=1, sticky='we')
 
         cur_interval = self.execute_command('get_interval')
         logger.debug('Received "%s" as the current interval' % (cur_interval,))
         self.scl_interval.set(cur_interval)
 
         api_key = self.execute_command('get_api_key')
-        self.txt_api.set(api_key)
+        self.api_key.set(api_key)
 
         self.parent.columnconfigure(0, weight=1)
 
         windows=[gui],
     )
 elif sys.platform in ('darwin', ):
-    import py2app
-    extra = dict(
-        app=['clip2zeus/main.py'],
-    )
+    try:
+        import py2app
+    except ImportError:
+        pass
+    else:
+        extra = dict(
+            app=['clip2zeus/main.py'],
+        )
 
 setup(
     name=APP_TITLE,
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.