source: MILK/trunk/milk_server/milk_server/controllers/selectedItems.py @ 4482

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

Replace 'viewItems' controller and flesh out selected Items controller - to allow user to plot results out in Google Earth and conTerra +
add wmc client section to config file to allow this to be specified as
an alternative service + tidy up some logging and unused code + update
prototype version to avoid IE problems.

Line 
1# Copyright (C) 2007 STFC & NERC (Science and Technology Facilities Council).
2# This software may be distributed under the terms of the
3# Q Public License, version 1.0 or later.
4# http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
5#
6"""
7 Controller for the 'Selections' tab - which displays selected WMC/granules and allows
8 these to be displayed via a selection of methods
9
10 @author: C Byrom
11"""
12
13from milk_server.lib.base import *
14from paste.request import parse_querystring
15from milk_server.models.selectedItem import SelectedItem
16import copy, urllib, logging
17
18class SelecteditemsController(BaseController):
19   
20    def index(self):
21        """
22        Default controller method to handle the initial requests to the page
23        """
24        # Get the inputs passed via the URL
25        self.inputs=dict(parse_querystring(request.environ))
26               
27        # if 'remove all' button clicked, clear out selection session data
28        if 'ClearSelections' in self.inputs: 
29            if 'selection' in session:
30                del session['selection']
31            session.save()
32        elif 'PlotSelectedInGoogle' in self.inputs:
33            # get all selected selections
34            self.getSelectedItems()
35            # ensure selections have been made
36            if 'selectedItems' in session:
37                # now create the aggregated KML file
38                # NB, set header info correctly to open as a file
39                #response.write(render('kml_aggregate', format='xml'))
40                response.headers['Content-Type'] = 'text/plain or application/vnd.google-earth.kml+xml'
41                response.headers['Content-Disposition'] = 'attachment;filename=kmlAggregate.kml'
42                return render('kml_aggregate', format='xml')
43
44        elif 'PlotSelectedInConTerra' in self.inputs:
45            # get all selected selections
46            self.getSelectedItems()
47
48            # ensure selections have been made
49            if 'selectedItems' in session:
50                # NB, only add selections which have a WMC URL defined
51                wmcURLs = []
52                for item in session['selectedItems']:
53                    logging.debug('SelectedItem: kmlList = %s, wmcList = %s' % (
54                        `item.kmlList`, `item.wmcList`))
55
56                    if (item.wmcURL):
57                        wmcURLs.append(item.wmcURL)
58                return getConTerraDoc(wmcURLs)
59       
60        elif 'PlotSelectedInLocal' in self.inputs:
61            # get all selected selections
62            self.getSelectedItems()
63
64            # ensure selections have been made
65            if 'selectedItems' in session:
66               
67                # the view tab uses its own selections session variable
68                # - this should initially match that set here
69                session['viewItems'] = copy.deepcopy(session['selectedItems'])
70                session.save()
71
72                # redirect to the view tab index code
73                h.redirect_to(h.url_for(controller='viewItems',action='index'))
74       
75        else:
76            # Check to see if individual con terra plots have been requested
77            for input in self.inputs:
78                if str(input).startswith('PlotConTerra____'):
79                    # if here a WMC has been requested to be plotted
80                    # - get the URL and plot
81                    dummy, wmcURL = str(input).split('____')
82                    # NB, the image key that we're parsing has either .x or .y at the end
83                    # - so strip this off
84                    wmcURL = wmcURL[0:len(wmcURL)-2]
85                    wmcURLs = [wmcURL]
86                    return getConTerraDoc(wmcURLs)
87           
88        return render('selectedItems')
89
90   
91    def getSelectedItems(self):
92        """
93        Check through the inputs to determine which checkboxes
94        have been selected in the 'selections' tab; use these
95        to build a new session list to use with the various visualisation methods
96        """
97
98        # clear out existing data
99        if 'selectedItems' in session:
100            del session['selectedItems']
101       
102        # now check for checkboxes as inputs; NB, these have the
103        # same names as the DIF entryIDs - i.e. the first element
104        # in the selection arrays - but with an extension appended to
105        # allow specific WMC/KMLs to be retrieved from list
106        selectedItems = []
107        for input in self.inputs:
108            if input.find('____') > -1:
109                entryID, i = input.split('____')
110                i = int(i)
111                for selection in session['selection']:
112                    if selection.entryID in entryID:
113                        newSelection = copy.deepcopy(selection)
114                        # NB, cope with multiple WMC/KML urls by splitting these
115                        # into multiple rows and redefining the selection item URL appropriately
116                        url = None
117                        if len(selection.kmlList) > i:
118                            url = selection.kmlList[i]
119                        newSelection.kmlURL = url
120                        url = None
121                        if len(selection.wmcList) > i:
122                            url = selection.wmcList[i]
123                        newSelection.wmcURL = url
124                        selectedItems.append(newSelection)
125       
126        if len(selectedItems) > 0:
127            session['selectedItems'] = selectedItems
128
129        session.save()
130       
131
132    def getConTerraDoc(wmcURLs):
133        """
134        Construct an aggregated XML file and display this as a temporary webpage; this will automatically be
135        POSTED so that the data is sent via POST to the Con Terra mapClient to visualise (as required by this client)
136        @param wmcURLS: An array of URLs pointing to WMC docs to visualise
137        """
138        # firstly, retrieve each WMC doc
139        wmcDocs = []
140        for wmcURL in wmcURLs:
141            wmcDocs.append(WMC(wmcURL))
142       
143        # now create a dictionary of WMS/layer from these docs - to avoid duplicate layers
144        c.wms = {}
145        for wmcDoc in wmcDocs:
146            for layer in wmcDoc.layers:
147                if layer.wmsURL not in c.wms:
148                    c.wms[layer.wmsURL] = [layer.name]
149                else:
150                    if layer.name not in c.wms[layer.wmsURL]:
151                        c.wms[layer.wmsURL].append(layer.name)
152       
153        # now create the form to post this data
154        logging.info('Creating form doc with data to post to Con Terra mapClient')
155        c.redirectToConterra = True;
156        response.write(render('selectedItems'))
157   
158    def addSelectedItem(self,entryid,divid):
159        """
160        Add a selected item to the session
161        - if this is the first item, then display the selections tab
162        @param entryid: Entry ID of related DIF record
163        @param divid: The div ID relating to the selected item in the results tab     
164        """
165
166        # URLs are unsafe to be added to the URL path_info so get them from the query_string
167        kmlurl = request.params['kmlurl']
168        wmcurl = request.params['wmcurl']
169        title = request.params['title']
170
171        logging.debug('addSelectedItem(%s, %s, %s, %s, %s)' % (
172            `entryid`, `kmlurl`, `wmcurl`, `title`, `divid`))
173
174        item = SelectedItem(entryid, title, kmlurl, wmcurl)
175
176        logging.debug('SelectedItem: kmlList = %s, wmcList = %s' % (
177            `item.kmlList`, `item.wmcList`))
178       
179        selections = [item,]
180        if 'selection' not in session:
181            newtabs=1
182            session['selection']=selections
183        else:
184            newtabs=0
185            for selection in session['selection']:
186                if selection.entryID != entryid:
187                    selections.append(selection)
188                   
189            session['selection']=selections
190        session.save()
191   
192        # TODO: would be nice to have page refresh upon selection of
193        # first item - so that selections tab not always visible
194        if newtabs:
195            c.UpdatePageTabs=1
196            c.current='Results'
197            c.pageTabs.append(('Selections',
198                               h.url_for(controller='selectedItems',
199                                         action='index')))
200
201        # Return a link to allow the item to be unselected
202        # - effectively this provides a remove function from the Results page
203        return h.link_to_remote('Unselect',
204                              dict(update=divid,
205                                    url=h.url_for(controller="selectedItems",
206                                               action="unSelectItem",
207                                               entryid=entryid,
208                                               divid=divid)))
209
210   
211    def removeSelectedItem(self,entryid):
212        """
213        Remove selected item from session data
214        @param entryid: Entry ID of record to remove from selected items list
215        """
216        self.deleteSelectedItem(entryid)
217        # rerender selections to update with item removed
218        return render('selectedItems')
219
220   
221    def deleteSelectedItem(self,entryid):
222        """
223        Remove selected item from session data
224        - NB, do this by rebuilding the session data
225        without the input data included
226        @param entryid: Entry ID of record to remove from selected items list
227        """
228        selections = []
229        deletedItem = None
230        for selection in session['selection']: 
231            if selection.entryID != entryid:
232                selections.append(selection)
233            else:
234                deletedItem = selection
235               
236        # if the new list is empty, remove the session variable and hide the selection page
237        if len(selections) == 0:
238            del session['selection']
239            c.UpdatePageTabs=1
240        else:
241            session['selection']=selections
242        session.save()
243       
244        return deletedItem
245       
246
247    def unSelectItem(self,entryid,divid):
248        """
249        Remove selected item from session data and adjust the 'Unselect' link
250        to display 'Select'
251        @param entryid: Entry ID of record to remove from selected items list
252        @param divid: The div ID relating to the selected item in the results tab     
253        """
254        deletedItem = self.deleteSelectedItem(entryid)
255       
256        return h.link_to_remote("Select",
257                               dict(update=divid,
258                                    url=h.url_for(controller="selectedItems",
259                                               action="addSelectedItem",
260                                               entryid=deletedItem.entryID,
261                                               kmlurl=deletedItem.kmlURL,
262                                               wmcurl=deletedItem.wmcURL,
263                                               title=deletedItem.title,
264                                               divid=divid)))
Note: See TracBrowser for help on using the repository browser.