File: SinTool.py

package info (click to toggle)
zope-cmfsin 0.6.1-5
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 156 kB
  • ctags: 164
  • sloc: python: 752; makefile: 30; sh: 2
file content (412 lines) | stat: -rw-r--r-- 13,981 bytes parent folder | download | duplicates (2)
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import os, os.path
import re
import locale
from types import StringType, UnicodeType

from AccessControl import ClassSecurityInfo
from BTrees.OOBTree import OOBTree
from SinConfigParser import ConfigParser
from Globals import InitializeClass, package_home
from OFS.SimpleItem import SimpleItem
from Products.CMFCore.Expression import Expression
from Products.CMFCore.CMFCorePermissions  import ManagePortal, ModifyPortalContent, View
from Products.CMFCore.ActionInformation import ActionInformation
from Products.CMFCore.ActionProviderBase import ActionProviderBase
from Products.CMFCore.utils import UniqueObject, getToolByName
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from StringIO import StringIO
from Acquisition import aq_base
from ComputedAttribute import ComputedAttribute

from Map import Map
from Channel import Channel
from rssparser import parse
from OrderPolicy import listPolicies

schedRe = re.compile("(?P<freq>\d+)(?P<period>h|d|w|m|y):")

_parsers = {}

def registerParser(channel, parser):
    _parsers[channel] = parser

def lookupParser(channel, default=parse):
    return _parsers.get(channel, default)

def udecode(data, encoding='ascii'):
    if (encoding and encoding.lower() == 'unicode'
        or isinstance(data, UnicodeType)):
        return unicode(data)
    encodings = [encoding, 'utf-8']
    try:
        encodings.append(locale.nl_langinfo(locale.CODESET))
    except:
        pass
    try:
        encodings.append(locale.getlocale()[1])
    except:
        pass
    try:
        encodings.append(locale.getdefaultlocale()[1])
    except:
        pass
    encodings.append('latin-1')
    for enc in encodings:
        if not enc:
            continue
        try:
            return unicode(data, enc)
        except (UnicodeError, LookupError):
            pass
    raise UnicodeError(
        'Unable to decode input data.  Tried the following encodings: %s.'
        % ', '.join([repr(enc) for enc in encodings if enc]))


class SinTool(UniqueObject, ActionProviderBase, SimpleItem):
    """ CMF Syndication Client  """

    id        = 'sin_tool'
    meta_type = 'CMFSin Syndication Tool'

    security = ClassSecurityInfo()

    _actions = [ActionInformation(
        id='newfeeds'
        , title='NewsFeeds'
        , action=Expression(text='string: ${portal_url}/sin_tool/sincfg')
        , condition=Expression(text='member')
        , permissions=(ManagePortal,)
        , category='portal_tabs'
        , visible=0
        )]

    manage_options=(
        ({ 'label'   : 'Config',
           'action'  : 'manage_configForm',
           },
         {  'label'  : 'Debug',
            'action' : 'manage_debugForm',
            },
         ) + SimpleItem.manage_options
        +  ActionProviderBase.manage_options
        )

    manage_debugForm = PageTemplateFile('www/debug', globals())
    manage_configForm = PageTemplateFile('www/config', globals())

    def __init__(self):
        self._reset()

    def _reset(self, config=None):
        self.maps     = OOBTree()
        self._v_data     = OOBTree()
        self.channels = OOBTree()
        self.config   = config

    security.declarePublic('Maps')
    def Maps(self):
        """ Available Maps """
        return self.maps.values()

    security.declarePublic('Channels')
    def Channels(self):
        """ Available Channels """
        return self.channels.values()

    security.declarePublic('Policies')
    def Policies(self):
        """ Available Policies """
        return listPolicies()

    def encode(self, parsed_data):
        # Get site encoding

        enc = 'iso8859-1'
        try:
            pp = getToolByName(self, 'portal_properties')
            enc = getattr(pp.site_properties, 'default_charset', 'iso8859-1')
        except (AttributeError, KeyError):
            pass
        info, data = parsed_data
        if info.has_key('title'):
            if type(info['title']) not in (UnicodeType, ):
                info['title'] = udecode(info['title']).encode(enc)
        if info.has_key('description'):
            if type(info['description']) not in (UnicodeType, ):
                info['description'] = udecode(info['description']).encode(enc)
        for r in data:
            if r.has_key('title'):
                if type(r['title']) not in (UnicodeType, ):
                    r['title'] = udecode(r['title']).encode(enc)
        return info, data

    def _update(self, channel, force=None):
        # Hard update of a channels feed -> data
        try:
            parser = lookupParser(channel.id)
            data = self.encode(parser(channel.uri))
            channel.update(data, force)
            # Lastly, we update the existing data
            # if everything worked
            if not hasattr(aq_base(self), '_v_data'):
                self._v_data = OOBTree()
            self._v_data[channel.id] = data
        except (IOError, OSError):
            channel.failed()

    security.declareProtected(View, 'updateChannel')
    def updateChannel(self, channel, force=None):
        if not isinstance(channel, Channel):
            channel = self.channels[channel]

        if force or channel.requireUpdate():
            self._update(channel, force)

    security.declareProtected(View, 'sin')
    def sin(self, map_name, force=0, max_size=None):
        """
        Returns the syndication info for a given mapping
        force    -- force a channel update
        max_size -- max size of result set (may be used in policy to calc pri)
        """

        if not hasattr(aq_base(self), '_v_data'):
            self._v_data = OOBTree()

        # With a fallback to channel for development
        map = self.maps.get(map_name)
        if not map:
            map = self.channels[map_name]
            channels = (map, )
        else:
            channels = map.Channels()

        for ci in channels:
            enabled = ci['enabled']
            if not enabled: continue
            channel = ci['channel']
            self.updateChannel(channel, force)

# How safe is it to use threading inside Zope?
#             import threading
#             thread_name = "SinTool.Channel.%s" % channel.id
#             if not [t for t in threading.enumerate() if \
#                     t.getName() == thread_name]:
#                 threading.Thread(target=self.updateChannel, name=thread_name, \
#                                  args=(channel, force)).start()

        #Collect all the data for all the enabled channels now
        results = []
        links   = {}

        for ci in channels:
            enabled = ci['enabled']
            if not enabled: continue
            channel = ci['channel']
            priority = ci['priority']
            data = self._v_data.get(channel.id, None)
            final   = []

            if not data: continue
            # We remove dup links inline
            for link in data[1]:
                if not links.has_key(link['link']):
                    links[link['link']] = 1
                    final.append(link)
                #We don't cache skips now because the Map
                #doesn't keep any data, just the channel
                #relationship, if this is an issue
                #its easy enough to change

            data[0]['priority'] = priority
            results.append(data)

        policy = map.policy
        results = policy.order(results, max_size=max_size)

        return results

    security.declareProtected(ModifyPortalContent, 'addChannel')
    def addChannel(self, name, url, **kwargs):
        c = Channel(name, url, **kwargs)
        self.channels[name] = c

    security.declareProtected(ModifyPortalContent, 'addMap')
    def addMap(self, map, channels=[]):
        self.maps[map] = m = Map(map)
        for c in channels:
            c = self.channels[c]
            m.addChannel(c)
        return m

    security.declarePrivate('parse')
    def parse(self, file):
        if type(file) == type(''):
            file = StringIO(file)

        config = ConfigParser()
        config.readfp(file)

        s = 'channels'
        options = config.options(s)
        args = {}
        for o in options:
            uri =  config.get(s, o, raw=1)
            match = schedRe.match(uri)
            if match:
                uri = uri[match.end():]
                args['period']    = match.group('period')
                args['frequency'] = int(match.group('freq'))
            self.addChannel(o, uri, **args)
            args.clear()

        s = 'maps'
        options = config.options(s)
        for o in options:
            channels = config.get(s, o, raw=1)
            #We look for policy_name:x,y,z
            #if no policy is specified default is used
            idx = channels.find(':')
            policy = None
            if idx != -1:
                policy, channels = channels[:idx], channels[idx+1:]

            m = self.addMap(o)
            if policy:
                m.setPolicy(policy)

            channels = channels.split(',')
            for c in channels:
                c = c.strip()  # remove whitespace around delimitters
                if c.endswith(')'):
                    #look for channel(pri) format
                    idx = c.rfind('(')
                    if idx != -1:
                        pri = int(c[idx+1:-1])
                        c = c[:idx]
                else:
                    pri = 0

                c = self.channels[c]
                m.addChannel(c, priority=pri)

        file.seek(0)
        self.config = file.read()

    security.declarePrivate('load')
    def load(self, filename):
        """ Load a file into config """
        name = os.path.join(package_home(globals()), \
                            os.path.basename(filename))
        if not name.endswith('.cfg'):
            name += '.cfg'

        fp = open(name)
        self.parse(fp)

    security.declarePrivate('save')
    def save(self, filename):
        """ Write config into a file """
        name = os.path.join(package_home(globals()), \
                            os.path.basename(filename))
        if not name.endswith('.cfg'):
            name += '.cfg'

        fp = open(name, 'w')
        fp.write(self.config)
        fp.close()

    security.declareProtected(ModifyPortalContent, 'updateConfig')
    def updateConfig(self, config=None, REQUEST=None, *args):
        """Update the config using new info"""
        self.parse(config)

        if REQUEST:
            return REQUEST.RESPONSE.redirect(self.absolute_url() + \
                                             "/sincfg?portal_status_message=Config+Updated")

    security.declareProtected(ManagePortal, 'manage_configSin')
    def manage_configSin(self, submit, config='', filename='', \
                         REQUEST=None, **kwargs):
        """config this puppy"""
        if submit == "Set Config":
            self.parse(config)
        elif submit == "Import":
            self.load(filename)
        elif submit == "Export":
            self.save(filename)

        if REQUEST:
            return REQUEST.RESPONSE.redirect(self.absolute_url() + \
                                             "/manage_workspace")

    security.declareProtected(ManagePortal, 'manage_debug')
    def manage_debug(self, submit, maps=(),  REQUEST=None, *args, **kwargs):
        """update maps for testing"""
        if submit == "Purge":
            self._reset(self.config)
            self.parse(self.config)

        elif submit == "Update Maps":
            for id in maps:
                self.sin(id, force=1)

        if REQUEST:
            return REQUEST.RESPONSE.redirect(self.absolute_url() + \
                                             "/manage_workspace")

    security.declarePrivate('setCurrentFeed')
    def setCurrentFeed(self, name):
        self._v_current_feed = name

    security.declareProtected(View, 'getCurrentFeed')
    def getCurrentFeed(self):
        """ Get the current configured feed """
        fd = self._v_current_feed
        if fd not in self.maps.keys():
            raise ValueError, "'%s' is not a valid map" % fd
        return fd

    # slightly improved hack-o-rama to allow
    # using a simpler path expression: here/sintool/macros/slashdot
    security.declareProtected(View, 'map')
    def macros(self):
        """ Allow traversing to map macro via ZPT """
        return SinMacro(self)

    macros = ComputedAttribute(macros, 1)

InitializeClass(SinTool)

class SinMacro:
    """ A dict-like object to allow configurable traversing to the macro
    while setting up the current feed reliably """

    def __init__(self, sintool, template='sinBox', macro='sinBox'):
        self._sintool = sintool
        self._template = template
        self._macro = macro

    def __repr__(self):
        return '<SinMacro at %s template: %s, macro: %s, maps: %s>' % \
               (id(self), self._template, self._macro, \
                ','.join(self._sintool.maps.keys()))

    def __getattr__(self, key):
        if key in self.__dict__.keys():
            return getattr(self, key)
        return getattr(self._sintool, key)

    def __getitem__(self, key):
        if key not in self._sintool.maps.keys():
            raise KeyError(key)
        skinstool = getToolByName(self._sintool, 'portal_skins')
        template = getattr(skinstool, self._template)
        macro = template.macros[self._macro]
        # this is a little bad, but here we dont have
        # request etc...
        self._sintool.setCurrentFeed(key)
        return macro