Changeset 600e09c


Ignore:
Timestamp:
2015-05-14T16:38:00Z (9 years ago)
Author:
Wilmer van der Gaast <wilmer@…>
Children:
513be3b
Parents:
578e5b0
Message:

Rough split of NewsBlur plugin from implugin base. Includes some plumbing
for caching setting values inside the plugin.

Location:
python
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • python/implugin.py

    r578e5b0 r600e09c  
    11#!/usr/bin/python
    22
    3 import sys
    43import bjsonrpc
    54from bjsonrpc.handlers import BaseHandler
    65
    7 import operator
    8 import random
    96import re
    107import socket
    11 import time
    12 
    13 import requests
    148
    159# List of functions an IM plugin can export. This library will indicate to
     
    5549        # away states, put them in a list in this variable.
    5650        AWAY_STATES = None
     51
     52        SETTINGS = {
     53                "oauth": {
     54                        "default": False,
     55                        "type": "bool",
     56                },
     57                "test": {
     58                        "default": 123,
     59                        "type": "int",
     60                },
     61                "stringetje": {
     62                        "default": "testje",
     63                        "flags": 0x04,
     64                }
     65        }
     66        _settings_values = {}
    5767       
    5868        # Filled in during initialisation:
     
    6474        bee = None
    6575       
    66         BASE_URL = "https://newsblur.com"
    67        
    6876        @classmethod
    6977        def _factory(cls, *args, **kwargs):
     
    7381                return handler_factory
    7482       
    75         #def __init__(self, connection, *args, **kwargs):
    76         #       BaseHandler.__init__(self,connection)
    77 
    78         def url(self, path):
    79                 return (self.BASE_URL + path)
    80 
    8183        def init(self, bee):
    8284                self.bee = RpcForwarder(bee["method_list"], self._conn.call)
     
    8486                self.bitlbee_version_str = bee["version_str"]
    8587
    86                 # TODO: See how to call into the module here.
    8788                return {
    8889                        "name": self.NAME,
     
    9091                        "account_flags": self.ACCOUNT_FLAGS,
    9192                        "away_state_list": self.AWAY_STATES,
    92                         "settings": {
    93                                 "oauth": {
    94                                         "default": "off",
    95                                         "type": "bool",
    96                                 },
    97                                 "test": {
    98                                         "default": "123",
    99                                         "type": "int",
    100                                 },
    101                                 "stringetje": {
    102                                         "default": "testje",
    103                                         "flags": 0x04,
    104                                 }
    105                         },
     93                        "settings": self.SETTINGS,
    10694                }
     95
     96        def login(self, account):
     97                for key, value in account.get("settings", {}).iteritems():
     98                        self.set_set(key, value)
     99
     100        def set_set(self, key, value):
     101                self._settings_values[key] = value
     102                try:
     103                        func = self.__getattribute__("set_set_%s" % key)
     104                except AttributeError:
     105                        return
     106                func(key, value)
    107107       
    108         def login(self, account):
    109                 self.ua = requests.Session()
    110                 creds = {"username": account["user"], "password": account["pass"]}
    111                 r = self.ua.post(self.url("/api/login"), creds)
    112                 self.bee.log("You're running BitlBee %d.%d.%d" % self.bitlbee_version)
    113                 if r.status_code != 200:
    114                         self.bee.error("HTTP error %d" % r.status_code)
    115                         self.bee.logout(True)
    116                 elif r.json()["errors"]:
    117                         self.bee.error("Authentication error")
    118                         self.bee.logout(False)
    119                 else:
    120                         self.bee.add_buddy("rss", None)
    121                         self.bee.connected()
    122                         self.seen_hashes = set()
    123                         self.keepalive()
    124 
    125         def logout(self):
    126                 self.bee.error("Ok bye!")
    127 
    128         def buddy_msg(self, handle, msg, flags):
    129                 feed = self.feeds[handle]
    130                 cmd = re.split(r"\s+", msg)
    131        
    132         def set_set(self, setting, value):
    133                 print "Setting %s changed to %r" % (setting, value)
    134        
    135         # BitlBee will call us here every minute which is actually a neat way
    136         # to get periodic work (like RSS polling) scheduled. :-D
    137         def keepalive(self):
    138                 r = self.ua.post(
    139                         self.url("/reader/unread_story_hashes"),
    140                         {"include_timestamps": True})
    141                 if r.status_code != 200:
    142                         self.bee.error("HTTP error %d" % r.status_code)
    143                         return
    144 
    145                 # Throw all unread-post hashes in a long list and sort it by posting time.
    146                 feed_hashes = r.json()["unread_feed_story_hashes"]
    147                 all_hashes = []
    148                 for feed, hashes in feed_hashes.iteritems():
    149                         all_hashes += [tuple(h) for h in hashes]
    150                 all_hashes.sort(key=operator.itemgetter(1))
    151                
    152                 # Look at the most recent 20, grab the ones we haven't shown yet.
    153                 req_hashes = []
    154                 for hash, _ in all_hashes[-20:]:
    155                         if hash not in self.seen_hashes:
    156                                 req_hashes.append(hash)
    157                
    158                 if not req_hashes:
    159                         return
    160                
    161                 # Grab post details.
    162                 r = self.ua.post(self.url("/reader/river_stories"), {"h": req_hashes})
    163                 if r.status_code != 200:
    164                         self.bee.error("HTTP error %d" % r.status_code)
    165                         return
    166                
    167                 # Response is not in the order we requested. :-( Make it a hash
    168                 # and reconstruct order from our request.
    169                 stories = {s["story_hash"]: s for s in r.json()["stories"]}
    170                 for s in (stories[hash] for hash in req_hashes):
    171                         line = "%(story_title)s <%(story_permalink)s>" % s
    172                         ts = int(s.get("story_timestamp", "0"))
    173                         self.bee.buddy_msg("rss", line, 0, ts)
    174                         self.seen_hashes.add(s["story_hash"])
     108        def setting(self, key):
     109                return self._settings_values[key]
    175110
    176111
    177 def RunPlugin(plugin, debug=True):
     112def RunPlugin(plugin, debug=False):
    178113        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    179114        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    180         sock.bind("/tmp/rpcplugins/test2")
     115        sock.bind("/tmp/rpcplugins/%s.sock" % plugin.NAME)
    181116        sock.listen(3)
    182117       
     
    185120        srv.debug_socket(debug)
    186121        srv.serve()
    187 
    188 RunPlugin(BitlBeeIMPlugin)
Note: See TracChangeset for help on using the changeset viewer.