Parent: [51ce87] (diff)

Child: [51171d] (diff)

Download this file

unity_recoll_daemon.py    378 lines (323 with data), 12.3 kB

  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
#! /usr/bin/python3
# -*- mode: python; python-indent: 2 -*-
#
# Copyright 2012 Canonical Ltd. 2013 Jean-Francois Dockes
#
# Contact: Jean-Francois Dockes <jfd@recoll.org>
#
# GPLv3
#
import os
import gettext
import locale
import sys
import time
import urllib.parse
import hashlib
from gi.repository import GLib, GObject, Gio
from gi.repository import Accounts, Signon
from gi.repository import GData
from gi.repository import Unity
try:
from recoll import rclconfig
hasrclconfig = True
except:
hasrclconfig = False
# As a temporary measure, we also look for rclconfig as a bare
# module. This is so that the intermediate releases of the lens can
# ship and use rclconfig.py with the lens code
if not hasrclconfig:
try:
import rclconfig
hasrclconfig = True
except:
pass
try:
from recoll import recoll
from recoll import rclextract
hasextract = True
except:
import recoll
hasextract = False
APP_NAME = "unity-scope-recoll"
LOCAL_PATH = "/usr/share/locale/"
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(APP_NAME, LOCAL_PATH)
gettext.textdomain(APP_NAME)
_ = gettext.gettext
THEME = "/usr/share/icons/unity-icon-theme/places/svg/"
UNITY_TYPE_TO_RECOLL_CLAUSE = {
"documents" : "rclcat:message rclcat:spreadsheet rclcat:text",
"folders" : "mime:inode/directory",
"images" : "rclcat:media",
"audio":"rclcat:media",
"videos":"rclcat:media",
"presentations" : "rclcat:presentation",
"other":"rclcat:other"
}
# Icon names for some recoll mime types which don't have standard icon by the
# normal method
SPEC_MIME_ICONS = {'application/x-fsdirectory' : 'gnome-fs-directory.svg',
'inode/directory' : 'gnome-fs-directory.svg',
'message/rfc822' : 'mail-read',
'application/x-recoll' : 'recoll'}
# Truncate results here:
MAX_RESULTS = 30
# Where the thumbnails live:
XDGCACHE = os.getenv('XDG_CACHE_DIR', os.path.expanduser("~/.cache"))
THUMBDIRS = [os.path.join(XDGCACHE, "thumbnails"),
os.path.expanduser("~/.thumbnails")]
def _get_thumbnail_path(url):
"""Look for a thumbnail for the input url, according to the
freedesktop thumbnail storage standard. The input 'url' always
begins with file:// and is unencoded. We encode it properly
and compute the path inside the thumbnail storage
directory. We return the path only if the thumbnail does exist
(no generation performed)"""
global THUMBDIRS
# Compute the thumbnail file name by encoding and hashing the url string
path = url[7:]
try:
path = "file://" + urllib.parse.quote_from_bytes(path)
except Exception as msg:
print("_get_thumbnail_path: urllib.parse.quote failed: %s" % msg,
file=sys.stderr)
return ""
#print("_get_thumbnail: encoded path: [%s]" % path, file=sys.stderr)
thumbname = hashlib.md5(path.encode('utf-8')).hexdigest() + ".png"
# If the "new style" directory exists, we should stop looking in
# the "old style" one (there might be interesting files in there,
# but they may be stale, so it's best to not touch them). We do
# this semi-dynamically so that we catch things up if the
# directory gets created while we are running.
if os.path.exists(THUMBDIRS[0]):
THUMBDIRS = THUMBDIRS[0:1]
# Check in appropriate directories to see if the thumbnail file exists
#print("_get_thumbnail: thumbname: [%s]" % (thumbname,))
for topdir in THUMBDIRS:
for dir in ("large", "normal"):
tpath = os.path.join(topdir, dir, thumbname)
#print("Testing [%s]" % (tpath,))
if os.path.exists(tpath):
return tpath
return ""
class RecollScope(Unity.AbstractScope):
__g_type_name__ = "RecollScope"
def __init__(self):
super(RecollScope, self).__init__()
self.search_in_global = True;
lng, self.localecharset = locale.getdefaultlocale()
def do_get_group_name(self):
# The primary bus name we grab *must* match what we specify in our
# .scope file
return "org.recoll.Unity.Scope.File.Recoll"
def do_get_unique_name(self):
return "/org/recoll/unity/scope/file/recoll"
def do_get_filters(self):
print("RecollScope: do_get_filters", file=sys.stderr)
filters = Unity.FilterSet.new()
f = Unity.RadioOptionFilter.new ("modified", _("Last modified"), Gio.ThemedIcon.new("input-keyboard-symbolic"), False)
f.add_option ("last-7-days", _("Last 7 days"), None)
f.add_option ("last-30-days", _("Last 30 days"), None)
f.add_option ("last-year", _("Last year"), None);
filters.add(f)
f2 = Unity.CheckOptionFilter.new ("type", _("Type"), Gio.ThemedIcon.new("input-keyboard-symbolic"), False)
f2.add_option ("media", _("Media"), None)
f2.add_option ("message", _("Message"), None)
f2.add_option ("presentation", _("Presentation"), None)
f2.add_option ("spreadsheet", _("Spreadsheet"), None)
f2.add_option ("text", _("Text"), None)
f2.add_option ("other", _("Other"), None)
filters.add (f2)
return filters
def do_get_categories(self):
print("RecollScope: do_get_categories", file=sys.stderr)
cats = Unity.CategorySet.new()
cats.add (Unity.Category.new ('global',
_("Files & Folders"),
Gio.ThemedIcon.new(THEME + "group-folders.svg"),
Unity.CategoryRenderer.VERTICAL_TILE))
cats.add (Unity.Category.new ('recent',
_("Recent"),
Gio.ThemedIcon.new(THEME + "group-recent.svg"),
Unity.CategoryRenderer.VERTICAL_TILE))
cats.add (Unity.Category.new ('downloads',
_("Downloads"),
Gio.ThemedIcon.new(THEME + "group-downloads.svg"),
Unity.CategoryRenderer.VERTICAL_TILE))
cats.add (Unity.Category.new ('folders',
_("Folders"),
Gio.ThemedIcon.new(THEME + "group-folders.svg"),
Unity.CategoryRenderer.VERTICAL_TILE))
return cats
def do_get_schema (self):
print("RecollScope: do_get_schema", file=sys.stderr)
schema = Unity.Schema.new ()
return schema
def do_create_search_for_query(self, search_context):
print("RecollScope: do_create_search_for query", file=sys.stderr)
return RecollScopeSearch(search_context)
class RecollScopeSearch(Unity.ScopeSearchBase):
__g_type_name__ = "RecollScopeSearch"
def __init__(self, search_context):
super(RecollScopeSearch, self).__init__()
self.set_search_context(search_context)
if hasrclconfig:
self.config = rclconfig.RclConfig()
def connect_db(self):
#print("RecollScopeSearch: connect_db", file=sys.stderr)
self.db = None
dblist = []
if hasrclconfig:
extradbs = rclconfig.RclExtraDbs(self.config)
dblist = extradbs.getActDbs()
try:
self.db = recoll.connect(extra_dbs=dblist)
self.db.setAbstractParams(maxchars=200, contextwords=4)
except Exception as s:
print("RecollScope: Error connecting to db: %s" % s, file=sys.stderr)
return
def do_run(self):
#print("RecollScopeSearch: do_run", file=sys.stderr)
context = self.search_context
filters = context.filter_state
search_string = context.search_query
result_set = context.result_set
# Get the list of documents
is_global = context.search_type == Unity.SearchType.GLOBAL
self.connect_db()
# We do not want filters to effect global results
catgf = ""
datef = ""
if not is_global:
catgf = self.catg_filter(filters)
datef = self.date_filter(filters)
sizef = self.size_filter(filters)
search_string = " ".join((search_string, catgf, datef, sizef))
print("RecollScopeSearch::do_run: Search: [%s]" % search_string)
# Do the recoll thing
try:
query = self.db.query()
nres = query.execute(search_string)
except Exception as msg:
print("recoll query execute error: %s" % msg)
return
actual_results = 0
for i in range(nres):
try:
doc = query.fetchone()
except:
break
titleorfilename = doc.title
if titleorfilename is None or titleorfilename == "":
titleorfilename = doc.filename
if titleorfilename is None:
titleorfilename = "doc.title and doc.filename are none !"
# Results with an ipath get a special mime type so that they
# get opened by starting a recoll instance.
url, mimetype, iconname = self.icon_for_type (doc)
try:
abstract = self.db.makeDocAbstract(doc, query)
except:
break
# Ok, I don't understand this category thing for now...
if is_global:
category = 0
else:
if doc.mimetype == "inode/directory" or \
"application/x-fsdirectory":
category = 3
else:
category = 1
#print({"uri":url,"icon":iconname,"category":category,
#"mimetype":mimetype, "title":titleorfilename,
#"comment":abstract,
#"dnd_uri":doc.url})
result_set.add_result(
uri=url,
icon=iconname,
category=category,
result_type=Unity.ResultType.PERSONAL,
mimetype=mimetype,
title=titleorfilename,
comment=abstract,
dnd_uri=doc.url)
actual_results += 1
if actual_results >= MAX_RESULTS:
break
def date_filter (self, filters):
#print("RecollScopeSearch: date_filter")
dateopt = ""
f = filters.get_filter_by_id("modified")
if f != None:
o = f.get_active_option()
if o != None:
if o.props.id == "last-year":
dateopt="date:P1Y/"
elif o.props.id == "last-30-days":
dateopt = "date:P1M/"
elif o.props.id == "last-7-days":
dateopt = "date:P7D/"
#print("RecollScopeSearch: date_filter: return [%s]" % dateopt)
# Until we fix the recoll bug:
# return dateopt
return ""
def catg_filter(self, filters):
f = filters.get_filter_by_id("type")
if not f: return ""
if not f.props.filtering:
return ""
ss = ""
for fopt in f.options:
print(fopt.props.id, file=sys.stderr)
if fopt.props.active:
if fopt.props.id in UNITY_TYPE_TO_RECOLL_CLAUSE:
ss += " " + UNITY_TYPE_TO_RECOLL_CLAUSE[fopt.props.id]
print("RecollScopSearch: catg_filter: [%s]" % ss)
return ss
def size_filter(self, filters):
print("size_filter", file=sys.stderr)
f = filters.get_filter_by_id("size")
if not f: return ""
print("size_filter got f", file=sys.stderr)
if not f.props.filtering:
return ""
print("size_filter f filtering", file=sys.stderr)
ss = ""
for fopt in f.options:
print(fopt.props.id, file=sys.stderr)
print("RecollScopeSearch: size_filter: [%s]" % ss)
return ss
# Send back a useful icon depending on the document type
def icon_for_type (self, doc):
iconname = "text-x-preview"
# Results with an ipath get a special mime type so that they
# get opened by starting a recoll instance.
thumbnail = ""
if doc.ipath != "":
mimetype = "application/x-recoll"
url = doc.url + "#" + doc.ipath
else:
mimetype = doc.mimetype
url = doc.url
# doc.url is a unicode string which is badly wrong.
# Retrieve the binary path for thumbnail access.
thumbnail = _get_thumbnail_path(doc.getbinurl())
iconname = ""
if thumbnail:
iconname = thumbnail
else:
if doc.mimetype in SPEC_MIME_ICONS:
iconname = SPEC_MIME_ICONS[doc.mimetype]
else:
icon = Gio.content_type_get_icon(doc.mimetype)
if icon:
# At least on Quantal, get_names() sometimes returns
# a list with '(null)' in the first position...
for iname in icon.get_names():
if iname != '(null)':
iconname = iname
break
return (url, mimetype, iconname);
def load_scope():
return RecollScope()