~davidc3/onehundredscopes/europeana

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
#! /usr/bin/python

#    Copyright(c) 2012 David Calle <davidc@framli.eu>

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
from gi.repository import GLib, GObject, Gio
from gi.repository import Unity
import urllib2, urllib
import re
import simplejson
import random

BUS_NAME = "net.launchpad.lens.europeana"


class Daemon:

    def __init__(self):
        self._lens = Unity.Lens.new("/net/launchpad/lens/europeana",
                                     "europeana")
        self._scope = Unity.Scope.new("/net/launchpad/lens/europeana/main")
        self._lens.props.search_hint = "Search Europeana"
        self._lens.props.visible = True

        self._lens.add_local_scope(self._scope)
        self._scope.connect("search-changed", self.on_search_changed)
        self._scope.connect('preview-uri', self.on_preview_uri)
        svg_dir = "/usr/share/icons/unity-icon-theme/places/svg/"
        cats = []
        cats.append(Unity.Category.new("Items",
                                       Gio.ThemedIcon.new(svg_dir+"group-installed.svg"),
                                       Unity.CategoryRenderer.VERTICAL_TILE))
        self._lens.props.categories = cats
        
        self.preferences = Unity.PreferencesManager.get_default()
        self.preferences.connect("notify::remote-content-search", self._on_preference_changed)
        self._lens.export();
        self._scope.export();

    def _on_preference_changed(self, *_):
        self._scope.queue_search_changed(Unity.SearchType.DEFAULT)

    def on_search_changed(self, scope, search, search_type, *_):
        model = search.props.results_model
        model.clear()
        if self.preferences.props.remote_content_search != Unity.PreferencesManagerRemoteContent.ALL:
            search.finished()
            return

        if search_type is Unity.SearchType.DEFAULT:
            search_string = search.props.search_string.strip()
            print "Search changed to \"%s\"" % search_string
            self.update_results_model(model, search_string)
            search.set_reply_hint("no-results-hint", GLib.Variant.new_string("Sorry, there are no Europeana items that match your search."))
        search.finished()

 
    def update_results_model(self, model, search):
        if not search:
            search = ""
        q = urllib.quote(search)
        qscope = urllib.quote('where:\"%s\" OR who:\"%s\" OR when:\"%s\" OR what:\"%s\"' % (q,q,q,q))
        url = "http://preview.europeana.eu/api/v2/search.json?wskey=QLShGrLqe&query=%s&start=1&rows=200&profile=standard" % (qscope)
        print url
        results = simplejson.load(urllib2.urlopen(url))
        if results['success']:
            if "items" in results:
                for item in results['items']:
                    dprovider, provider, title, image, guid, creator = '','','','','', ''
                    for e in item:
                        if e == "dataProvider":
                            dprovider =  item['dataProvider'][0]
                        elif e == "provider":
                            provider = item['provider'][0]
                        elif e == "title":
                            title = item['title'][0]
                        elif e == "thumbnails":
                            image = item['thumbnails'][0]
                        elif e == "guid":
                            guid = item['guid']
                        elif e == "dcCreator":
                            creator = item['dcCreator'][0]
                        else:
                            pass
                    print item
                    if image != '' and item['type'] == "IMAGE":
                        title = title.split(";")[-1]
                        if title == '':
                            title = creator
                        model.append(guid,image,0, "text/html", title, provider, guid)



    def on_preview_uri(self, scope, uri):
        """Preview request handler"""
        preview = None
        model = self._scope.props.results_model
        iter = model.get_first_iter()
        end_iter = model.get_last_iter()
        while iter != end_iter:
            if model.get_value(iter, 0) == uri:
                title  = model.get_value(iter, 4)
                amount = ''
                description = ''
                for r in self.recipes:
                    if title == r[0]:
                        print r
                        if ',' in r[3]:
                            amount = r[3].split(',')[-1]
                        description = r[4]

                image = self.createRecipeImage(title)
                
                gicon_icon = Gio.FileIcon.new(Gio.file_new_for_uri(model.get_value(iter, 1)))
                if self.is_file(CACHE+image):
                    gicon_recipe = Gio.FileIcon.new(Gio.file_new_for_path(CACHE+image))
                else:
                    gicon_recipe = ''
                preview = Unity.ApplicationPreview.new(title.strip(),'' ,description,gicon_icon, gicon_recipe)
                if amount != '':
                    preview.add_info(Unity.InfoHint.new("Production", "Production", None, amount))
#                gfile_icon = Gio.file_new_for_path("/usr/share/icons/unity-icon-theme/places/svg/service-picasa.svg")
#                gicon = Gio.FileIcon.new(gfile_icon)
#                view_action = Unity.PreviewAction.new("view", _("View"), gicon)
#                view_action.connect('activated', self.view_action)
#                preview.add_action(view_action)
                break
            iter = model.next(iter)
        if preview == None:
            print("Couldn't find model row for requested preview uri: '%s'", uri)
        return preview

    def view_action(self, scope, uri):
        """On item clicked, close the Dash and display the photo"""
        return


if __name__ == "__main__":
    session_bus_connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    session_bus = Gio.DBusProxy.new_sync(session_bus_connection, 0, None,
                                          'org.freedesktop.DBus',
                                          '/org/freedesktop/DBus',
                                          'org.freedesktop.DBus', None)
    result = session_bus.call_sync('RequestName',
                                   GLib.Variant("(su)",(BUS_NAME, 0x4)),
                                   0, -1, None)
                                   
    result = result.unpack()[0]

    if result != 1:
        print >> sys.stderr, "Failed to own name %s. Bailing out." % BUS_NAME
        raise SystemExit(1)

    daemon = Daemon()
    GObject.MainLoop().run()