~ibid-core/ibid/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# Copyright (c) 2008-2011, Michael Gorven, Stefano Rivera, Jonathan Hitchcock
# Released under terms of the MIT/X/Expat Licence. See COPYING for details.

from urllib2 import HTTPError
from time import time
from datetime import datetime
import re
import logging

import feedparser

from ibid.compat import ElementTree
from ibid.config import DictOption
from ibid.plugins import Processor, match, handler
from ibid.utils import ago, decode_htmlentities, generic_webservice, \
                       json_webservice, parse_timestamp

log = logging.getLogger('plugins.social')
features = {}

features['lastfm'] = {
    'description': u'Lists the tracks last listened to by the specified user.',
    'categories': ('lookup', 'web',),
}
class LastFm(Processor):
    usage = u'last.fm for <username>'

    features = ('lastfm',)

    @match(r'last\.?fm for {username:chunk}')
    def listsongs(self, event, username):
        songs = feedparser.parse('http://ws.audioscrobbler.com/1.0/user/%s/recenttracks.rss?%s' % (username, time()))
        if songs['bozo']:
            event.addresponse(u'No such user')
        else:
            event.addresponse(u', '.join(u'%s (%s ago)' % (
                    e.title,
                    ago(event.time - parse_timestamp(e.updated))
                ) for e in songs['entries']))

features['microblog'] = {
    'description': u'Looks up messages on microblogging services like twitter '
                   u'and identica.',
    'categories': ('lookup', 'web',),
}
class Twitter(Processor):
    usage = u"""latest (tweet|identica) from <name>
    (tweet|identica) <number>"""

    features = ('microblog',)

    default = {
        'twitter':   {'endpoint': 'http://api.twitter.com/1/',   'api': 'twitter',  'name': 'tweet', 'user': 'twit'},
        'tweet':     {'endpoint': 'http://api.twitter.com/1/',   'api': 'twitter',  'name': 'tweet', 'user': 'twit'},
        'identica':  {'endpoint': 'http://identi.ca/api/', 'api': 'laconica', 'name': 'dent',  'user': 'denter'},
        'identi.ca': {'endpoint': 'http://identi.ca/api/', 'api': 'laconica', 'name': 'dent',  'user': 'denter'},
        'dent':      {'endpoint': 'http://identi.ca/api/', 'api': 'laconica', 'name': 'dent',  'user': 'denter'},
    }
    services = DictOption('services', 'Micro blogging services', default)

    class NoTweetsException(Exception):
        pass

    def setup(self):
        self.update.im_func.pattern = re.compile(r'^(%s)\s+(\d+)$' % '|'.join(self.services.keys()), re.I)
        self.latest.im_func.pattern = re.compile(r'^(?:latest|last)\s+(%s)\s+(?:update\s+)?(?:(?:by|from|for)\s+)?@?(\S+)$'
                % '|'.join(self.services.keys()), re.I)

    def remote_update(self, service, id):
        status = json_webservice('%sstatuses/show/%s.json' % (service['endpoint'], id))

        return {'screen_name': status['user']['screen_name'], 'text': decode_htmlentities(status['text'])}

    def remote_latest(self, service, user):
        if service['api'] == 'twitter':
            # Twitter ommits retweets in the JSON and XML results:
            statuses = generic_webservice('%sstatuses/user_timeline.rss'
                                          % service['endpoint'], {
                                              'screen_name': user,
                                              'count': 1
                                          })
            tree = ElementTree.fromstring(statuses)
            latest = tree.find('.//item')
            if latest is None:
                if tree.find('.//error'):
                    log.info('Twitter user_latest returned: %s',
                             tree.findtext('.//error'))
                raise self.NoTweetsException(user)
            return {
                'text': latest.findtext('description')
                        .split(': ', 1)[1],
                'ago': ago(datetime.utcnow() - parse_timestamp(
                    latest.findtext('pubDate'))),
                'url': latest.findtext('guid'),
            }
        elif service['api'] == 'laconica':
            statuses = json_webservice('%sstatuses/user_timeline/%s.json'
                    % (service['endpoint'], user.encode('utf-8')),
                    {'count': 1})
            if not statuses:
                raise self.NoTweetsException(user)
            latest = statuses[0]
            url = '%s/notice/%i' % (service['endpoint'].split('/api/', 1)[0],
                                    latest['id'])

        return {
            'text': decode_htmlentities(latest['text']),
            'ago': ago(datetime.utcnow()
                       - parse_timestamp(latest['created_at'])),
            'url': url,
        }

    @handler
    def update(self, event, service_name, id):
        service = self.services[service_name.lower()]
        try:
            event.addresponse(u'%(screen_name)s: "%(text)s"', self.remote_update(service, int(id)))
        except HTTPError, e:
            if e.code in (401, 403):
                event.addresponse(u'That %s is private', service['name'])
            elif e.code == 404:
                event.addresponse(u'No such %s', service['name'])
            else:
                log.debug(u'%s raised %s', service['name'], unicode(e))
                event.addresponse(u'I can only see the Fail Whale')

    @handler
    def latest(self, event, service_name, user):
        service = self.services[service_name.lower()]
        try:
            event.addresponse(u'"%(text)s" %(ago)s ago, %(url)s', self.remote_latest(service, user))
        except HTTPError, e:
            if e.code in (401, 403):
                event.addresponse(u"Sorry, %s's feed is private", user)
            elif e.code == 404:
                event.addresponse(u'No such %s', service['user'])
            else:
                log.debug(u'%s raised %s', service['name'], unicode(e))
                event.addresponse(u'I can only see the Fail Whale')
        except self.NoTweetsException, e:
            event.addresponse(
                u'It appears that %(user)s has never %(tweet)sed', {
                    'user': user,
                    'tweet': service['name'],
                })

    @match(r'^https?://(?:www\.)?twitter\.com/(?:#!/)?[^/ ]+/statuse?s?/(\d+)$',
           simple=False)
    def twitter(self, event, id):
        self.update(event, u'twitter', id)

    @match(r'https?://(?:www\.)?identi.ca/notice/{id:digits}')
    def identica(self, event, id):
        self.update(event, u'identica', id)

# vi: set et sta sw=4 ts=4: