source: products/quintagroup.plonegooglesitemaps/trunk/quintagroup/plonegooglesitemaps/browser/configletview.py @ 3163

Last change on this file since 3163 was 3163, checked in by zidane, 13 years ago

fixes pyflakes and pylint

  • Property svn:eol-style set to native
File size: 6.1 KB
Line 
1from zope.component import queryMultiAdapter
2from zope.interface import implements, Interface, Attribute
3
4from OFS.Image import cookId
5from OFS.ObjectManager import BadRequestException
6from Products.Five import BrowserView
7
8
9def splitNum(num):
10    res = []
11    prefn = 3
12    for c in str(num)[::-1]:
13        res.insert(0, c)
14        if not len(res) % prefn:
15            res.insert(0, ',')
16            prefn += 4
17    return "".join(res[0] == ',' and res[1:] or res)
18
19
20class IConfigletSettingsView(Interface):
21    """
22    Sitemap view interface
23    """
24
25    sitemaps = Attribute("Returns mapping of sitemap's type to list of " \
26                         "appropriate objects")
27    hasContentSM = Attribute("Returns boolean about existance of content " \
28                             "sitemap")
29    hasMobileSM = Attribute("Returns boolean about existance of mobile " \
30                            "sitemap")
31    hasNewsSM = Attribute("Returns boolean about existance of news sitemap")
32    sm_types = Attribute("List of sitemap types")
33
34    def sitemapsDict():
35        """ Return dictionary like object with data for table
36        """
37    def sitemapsURLByType():
38        """ Return dictionary like object with sitemap_type as key
39            and sitemap object(s) as value
40        """
41    def getVerificationFiles():
42        """ Return list of existent verification files on site.
43            Update googlesitemap_properties.verification_file
44            property for only existent files
45        """
46
47    def uploadVerificationFile(vfile):
48        """ Upload passed site verification file to the site.
49            On success - update googlesitemaps verification files list.
50            Return tuple where :
51              1. boolean value - is verification file successfully created.
52              2. string value:
53                2.1. if successfull - id of created verification file
54                2.2. if failure - error descirption
55        """
56
57
58class ConfigletSettingsView(BrowserView):
59    """
60    Configlet settings browser view
61    """
62    implements(IConfigletSettingsView)
63    sitemaps = []
64
65    def __init__(self, context, request):
66        self.context = context
67        self.request = request
68
69        self.tools = queryMultiAdapter((self.context, self.request),
70                                       name="plone_tools")
71        self.pps = queryMultiAdapter((self.context, self.request),
72                                     name="plone_portal_state")
73        self.sitemaps = [i.getObject() for i in \
74                         self.tools.catalog()(portal_type='Sitemap')]
75
76    @property
77    def sm_types(self):
78        return [i.getSitemapType() for i in self.sitemaps]
79
80    @property
81    def hasContentSM(self):
82        return 'content' in self.sm_types
83
84    @property
85    def hasMobileSM(self):
86        return 'mobile' in self.sm_types
87
88    @property
89    def hasNewsSM(self):
90        return 'news' in self.sm_types
91
92    def sitemapsURLByType(self):
93        sitemaps = {}
94        for sm in self.sitemaps:
95            smlist = sitemaps.setdefault(sm.getSitemapType(), [])
96            smlist.append({'url': sm.absolute_url(), 'id': sm.id})
97        sitemaps['all'] = sitemaps.setdefault('content', []) + \
98                          sitemaps.setdefault('mobile', []) + \
99                          sitemaps.setdefault('news', [])
100        return sitemaps
101
102    def sitemapsURLs(self):
103        sitemaps = {}
104        for sm in self.sitemaps:
105            smlist = sitemaps.setdefault(sm.getSitemapType(), [])
106            smlist.append(sm.absolute_url())
107        return sitemaps
108
109    def sitemapsDict(self):
110        content, mobile, news = [], [], []
111        for sm in self.sitemaps:
112            data = self.getSMData(sm)
113            if data['sm_type'] == 'Content':
114                content.append(data)
115            elif data['sm_type'] == 'Mobile':
116                mobile.append(data)
117            elif data['sm_type'] == 'News':
118                news.append(data)
119        return content + mobile + news
120
121    def getSMData(self, ob):
122        size, entries = self.getSitemapData(ob)
123        return {'sm_type': ob.getSitemapType().capitalize(),
124                'sm_id': ob.id,
125                'sm_url': ob.absolute_url(),
126                'sm_size': size and splitNum(size) or '',
127                'sm_entries': entries and splitNum(entries) or '',
128               }
129
130    def getSitemapData(self, ob):
131        size, entries = (0, 0)
132        view = ob and ob.defaultView() or None
133        if view:
134            self.request.RESPONSE
135            bview = queryMultiAdapter((ob, self.request), name=view)
136            if bview:
137                try:
138                    size = len(bview())
139                    entries = bview.numEntries
140                    self.request.RESPONSE.setHeader('Content-Type',
141                                                    'text/html')
142                except:
143                    pass
144        return (size, entries)
145
146    def getVerificationFiles(self):
147        vfs = []
148        props = getattr(self.tools.properties(), 'googlesitemap_properties')
149        if props:
150            portal_ids = self.pps.portal().objectIds()
151            props_vfs = list(props.getProperty('verification_filenames', []))
152            vfs = [vf for vf in props_vfs if vf in portal_ids]
153            if not props_vfs == vfs:
154                props._updateProperty('verification_filenames', vfs)
155        return vfs
156
157    def uploadVerificationFile(self, request):
158        vfilename = ""
159        portal = self.pps.portal()
160        try:
161            vfile = request.get("verification_file")
162            vfilename, vftitle = cookId("", "", vfile)
163            portal.manage_addFile(id="", file=vfile)
164            portal[vfilename].manage_addProperty(
165                'CreatedBy', 'quintagroupt.plonegooglesitemaps', 'string')
166        except BadRequestException, e:
167            return False, str(e)
168        else:
169            props = self.tools.properties().googlesitemap_properties
170            vfilenames = list(props.getProperty('verification_filenames', []))
171            vfilenames.append(vfilename)
172            props.manage_changeProperties(verification_filenames=vfilenames)
173        return True, vfilename
Note: See TracBrowser for help on using the repository browser.