source: MILK/trunk/milk_server/milk_server/controllers/trackback/trackback.py @ 5261

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/MILK/trunk/milk_server/milk_server/controllers/trackback/trackback.py@5261
Revision 5261, 7.0 KB checked in by cbyrom, 11 years ago (diff)

Lots of tidy ups to MILK codebase:

Implement new input search filters - with javascript datapickers to
pick the date ranges + add the vocab search ahead text input and
combine this with the text input.

Refactor discovery controller to tidy it up significantly - making more
structured and improving error handling and logging. Improve
templates for the search filter, splitting into multiple files to
organise better.

Various tidying up and tweaks of other codebase - e.g. standardising
use of global variables across app.

Line 
1'''
2 Class representing the pylons controller for trackback functionality.  This allows:
3 
4 i) commenting on metadata
5 ii) referencing of metadata
6
7 NB, info on TrackBack available from:
8 
9 http://www.sixapart.com/pronet/docs/trackback_spec
10 
11 @author: C Byrom, Tessella Feb 2009
12'''
13from milk_server.lib.base import *
14from milk_server.models.ndgdoc import NDGDoc
15from ndg.common.src.models.ndgObject import ndgObject
16import ndg.common.src.clients.xmldb.eXist.dbconstants as dc
17from ndg.common.src.lib.mailer import mailHandler
18
19class TrackbackController(BaseController):
20    '''
21    Provides the pylons controller for recieving trackbacks to NDG documents
22    '''
23    def __setup(self,uri):
24        '''
25        Common setup stuff for all the actions on this controller
26        @param uri: ndgURI associated with current doc being viewed
27        '''
28        logging.info("Setting up TrackbackController")
29        self.cf = request.environ['ndgConfig']
30        try:
31            self.uri=ndgObject(uri, config = self.cf)
32        except ValueError,e:
33            return e
34
35        self.inputs = request.params
36
37        self.ndgDoc = NDGDoc(ndgURI = uri, config = self.cf)
38        logging.info("TrackbackController set up")
39        return 0   
40
41
42    def ping(self, uri):
43        '''
44        This is the default trackback receipt method. When a doc is referenced
45        from a TrackBack enabled site, this method should be invoked, via a
46        TrackBack ping, to notify that it has been referenced.  Log the reference
47        by sending a mail to the trackback recipient set in the config file and
48        adding an entry to the citation feed.
49        ( Note we haven't implemented whitelisting yet )
50        @param uri: ndgURI associated with the doc being pinged by trackback
51        '''
52        logging.info("Trackback ping called - notifying trackback recipient + feed of citation")
53        err = 0
54        status=self.__setup(uri)
55       
56        # lookup referenced doc - to ensure it exists and get extra info to add
57        # to citation messages
58        self.ndgDoc.setupDocumentModel()
59        payload = ""
60        if self.ndgDoc.status:
61            payload = '<trackback><uri>%s</uri><title>%s</title></trackback>' %(self.ndgDoc.docModel.atomBrowseURL, 
62                                                                                self.ndgDoc.name)
63        else:
64            err = "Could not find document, '%s', to reference in trackback" %uri
65       
66        if not g.mailServer:
67            err = 'Server not configured for trackback (no mail server)'
68       
69        if not g.tbRecipient:
70            err = 'Server not configured for trackback (no recipient)'
71       
72        body='Citation Trackback for %s\n\n\n%s'% (uri, payload)
73        name='CitationTrackbackFor_%s.xml'%uri
74       
75        if err != 0:
76            c.message = err
77            c.err = 1
78        else: 
79            logging.info("Sending notification mail to '%s'" %g.tbRecipient)
80            status, message = mailHandler([g.tbRecipient,], body, body,
81                                          xmlAttachments = [(payload, name),],
82                                          server = g.mailServer)
83            if status:
84                c.err = 0
85            else:
86                c.err = 1
87                c.message = 'Unable to forward trackback to designated recipient [%s]' %message
88
89            # lastly, add to citation feed
90            logging.info("Mail sent - now add data to the citations feed")
91            g.validator._atomClient.feedClient.createGenericFeedEntry(name, payload,
92                                                                      dc.CITATIONS_COLLECTION_PATH)
93       
94        response.headers['content-type'] = 'text/xml'
95
96        logging.info("Trackback logged - now sending receipt")
97        return render('genshi', 'trackback/trackback',format='xml')
98   
99
100    def getTrackBackInfo(self, uri, name):
101        '''
102        Get the trackback info for the specified uri and name
103        @param uri: ndgURI representing doc
104        @param name: title of doc
105        @return rdf element representing trackback info
106        '''
107        s='''<!--
108        <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
109             xmlns:dc="http://purl.org/dc/elements/1.1/"
110             xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
111        <rdf:Description
112            rdf:about="%s"
113            dc:identifier="%s"
114            dc:title="%s"
115            trackback:ping="%s" />
116        </rdf:RDF>
117        -->'''%(uri,g.server+h.url_for(),name,
118                g.server+h.url_for(controller="trackback/trackback", action="ping"))
119        return s
120
121
122   
123    def askCorrect(self,uri):
124        '''
125        Provide a form (ajaxaciously) so that a user can correct a metadata record
126        '''
127        logging.info("Called askCorrect - to render a corrections input form")
128        status=self.__setup(uri)
129        c.uri=self.uri
130       
131        if status:
132            return response.write(status)
133
134        try:
135            html =  render("genshi", 'trackback/correct',fragment=True)
136        except Exception, e:
137            logging.error("Error experienced whilst rendering 'correct' template: %s" %e)
138           
139        logging.info("- retrieved info - now rendering form")
140        return html
141
142   
143    def correct(self, uri):
144        '''
145        Receive a correction form to update a record and post it to the holder
146        '''
147        logging.info("Submitting correction info - this will be mailed to metadata " + \
148            "maintainer + added to the corrections feed")
149        status=self.__setup(uri)
150        if 'ndgSec' not in session:
151            c.xml = 'Error - user not currently logged in.  Please login before submitting user comments.'
152            logging.error(c.xml)
153            return render('kid', 'error')
154       
155        body = 'Metadata Change Request for %s' %uri
156        payload = '<Change><uri>%s</uri><from>%s</from><Contents>%s</Contents></Change>' \
157            %(self.inputs['Identifier'],self.inputs['Submitter'],self.inputs['Comment'])
158        name = 'ChangeRequestFor_%s.xml' %uri
159       
160        logging.info("Mailing corrections info to %s" %g.metadataMaintainer)
161        status,message = mailHandler([g.metadataMaintainer],
162                                     body,body,xmlAttachments=[(payload,name),],
163                                     server = g.mailServer)
164        if status:
165            result = 'Your comments have been sent to the metadata maintainer and added to corrections feed for the metatadata database.'
166        else:
167            result = message
168           
169        c.xml = result
170        logging.info("- now add these to the corrections feed")
171        # add the maintainer info
172        body += " - for metadata maintainer, '%s'" %g.metadataMaintainer
173        g.validator._atomClient.feedClient.createGenericFeedEntry(body, payload,
174                                                                  dc.CORRECTIONS_COLLECTION_PATH)
175
176        g.correctionPosted = result
177        h.redirect_to(h.url_for(controller = 'browse/retrieve', action='view', \
178                                uri = uri))
179
Note: See TracBrowser for help on using the repository browser.