/usr/share/unity-scopes/sogou/unity_sogou_daemon.py is in unity-china-photo-scope 1.3-0ubuntu1.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright: (C) 2013 National University of Defense Technology(NUDT) & Kylin Ltd
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
# 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/>.
# Authored by shijing <jingshi@ubuntukylin.com>
# 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
import os
import gettext
import time
import datetime
import urllib.parse
import urllib.request
import json
from gi.repository import GLib
from gi.repository import Gio
from gi.repository import Accounts
from gi.repository import Signon
from gi.repository import Dee
from gi.repository import Unity
from gi.repository import UnityExtras
from gi.repository import Soup
from gi.repository import SoupGNOME
APP_NAME = "unity-china-photo-scope"
LOCAL_PATH = "/usr/share/locale/"
IS_IN_CHINA = ''
ASK_IP_SERVER_URI_ONE = "http://ip.chinaz.com/"
ASK_IP_SERVER_URI_TWO = "http://www.123myip.co.uk/"
gettext.bindtextdomain(APP_NAME, LOCAL_PATH)
gettext.textdomain(APP_NAME)
_ = gettext.gettext
# Translatable strings
SOURCE = _("Sogou")
NO_RESULTS_HINT = _("Sorry, there are no photos that match your search.")
BUS_NAME = "com.ubuntukylin.Unity.Scope.Photos.Sogou"
#CAT_MINE = _("My Photos")
#CAT_FRIENDS = _("Friends Photos")
#CAT_ONLINE = _("Online Photos")
#CAT_GLOBAL = _("Photos")
CAT_RECENT = _("Recent")
FILTER_DATE = _("Date")
FILTER_OPTION_7DAYS = _("Last 7 days")
FILTER_OPTION_30DAYS = _("Last 30 days")
FILTER_OPTION_6MONTHS = _("Last 6 months")
FILTER_OPTION_OLDER = _("Older")
THEME = "/usr/share/icons/unity-icon-theme/places/svg/"
class Scope(Unity.DeprecatedScope):
last_result = None
def do_preview_result(self, result, callback):
"""Temporarily save the ScopeResult so it is available for
preview-uri signal handlers."""
# Wrap the AsyncReadyCallback to handle dummy user_data argument.
def wrapped_callback(object, async_result, user_data):
return callback(object, async_result)
self.last_result = result
try:
return Unity.DeprecatedScope.do_preview_result(
self, result, wrapped_callback, None)
finally:
self.last_result = None
class Daemon:
def __init__(self):
"""Set some initial values for the scope and connect to Unity"""
self._scope = Scope (dbus_path="/com/ubuntukylin/unity/scope/photos/sogou", id="sogou")
self._sources_options = []
self.url = ''
self.items = []
self.new_dic = {}
self.result_list = []
# Storage for results waiting to be displayed
self.results_waiting = {1:[], 2:[], 3:[]}
self.init_session_management ()
self._enabled = False
self._scope.connect("search-changed", self.on_search_changed)
self._scope.connect("notify::active", self.on_lens_active_or_preference_changed)
self._scope.connect('preview-uri', self.on_preview_uri)
self.preferences = Unity.PreferencesManager.get_default()
self.preferences.connect("notify::remote-content-search", self.on_lens_active_or_preference_changed)
filters = Unity.FilterSet.new()
f2 = Unity.RadioOptionFilter.new ("date", FILTER_DATE, Gio.ThemedIcon.new("input-keyboard-symbolic"), False)
f2.add_option ("7", FILTER_OPTION_7DAYS, None)
f2.add_option ("30", FILTER_OPTION_30DAYS, None)
f2.add_option ("180", FILTER_OPTION_6MONTHS, None)
f2.add_option ("100000",FILTER_OPTION_OLDER, None)
filters.add (f2)
cats = Unity.CategorySet.new()
cats.add (Unity.Category.new ('recent',
CAT_RECENT,
Gio.ThemedIcon.new(THEME + "group-recent.svg"),
Unity.CategoryRenderer.VERTICAL_TILE))
self._scope.props.categories = cats
self._scope.props.filters = filters
self._scope.export ()
def callback(object, result, user_data):
object.preview_result_finish(result)
def init_session_management (self):
""" Define a set of variables used for Soup session management """
self._pending = []
self._http = []
for i in range(3):
self._pending.append(None)
self._http.append(self._get_http_session ())
def _get_http_session (self):
session = Soup.SessionAsync()
session.add_feature_by_type(SoupGNOME.ProxyResolverGNOME)
return session
########
#IS_IN_CHINA
########
def is_in_China (self):
IS_IN_CHINA = "Unknown"
try:
if IS_IN_CHINA == "Unknown":
content = urllib.request.urlopen(ASK_IP_SERVER_URI_ONE).read().decode('utf-8','ignore')
location = content.find("北京") + content.find("上海") + content.find("天津") + content.find("重庆") + content.find("黑龙江") + content.find("吉林") + content.find("辽宁") + content.find("江苏") + content.find("山东") + content.find("安徽") + content.find("河北") + content.find("河南") + content.find("湖北") + content.find("湖南") + content.find("江西") + content.find("陕西") + content.find("山西") + content.find("四川") + content.find("青海") + content.find("海南") + content.find("广东") + content.find("贵州") + content.find("浙江") + content.find("福建") + content.find("台湾") + content.find("甘肃") + content.find("云南") + content.find("内蒙古") + content.find("宁夏") + content.find("新疆") + content.find("西藏") + content.find("广西")
if location < 0 :
content = urllib.request.urlopen(ASK_IP_SERVER_URI_TWO).read().decode('utf-8','ignore')
location = content.find("China")
if location > 0 :
IS_IN_CHINA = "Yes"
return True
else:
IS_IN_CHINA = "Yes"
else:
return True
return True
except:
print ("please check network!")
########
# Sogou query generators
########
def _url_maker(self, cat, search_string, date):
"""Select the correct query depending on search parameters"""
if date < 0:
date = 180*86400
now = int(time.time())
date = now - date
date_query = "and created < '%s'" % date
elif date > 0:
date_query = "and created > '%s'" % date
else:
date_query = ""
if date == 0:
self.recent_expected = True
url = ("http://pic.sogou.com/pics?reqType=ajax&query=%s" % (urllib.parse.quote(search_string)))
return url
########
# Lens functions
########
def on_lens_active_or_preference_changed(self, *_):
""" Update results when the lens is opened """
self._scope.queue_search_changed(Unity.SearchType.DEFAULT)
def check_date_filter(self,s):
"""Get active option for a filter name"""
try:
date = s.get_filter("date").get_active_option().props.id
date = int(date)*86400
now = int(time.time())
date = now - date
except (AttributeError):
date = 0
return date
def on_search_changed (self, scope, search, search_type, cancellable):
"""Trigger a search for each category when the lens requests it"""
self.recent_expected = False
model = search.props.results_model
search.set_reply_hint ("no-results-hint", GLib.Variant.new_string(NO_RESULTS_HINT))
model.clear()
# only perform the request if the user has not disabled
# online results. That will hide the category as well.
if self.preferences.props.remote_content_search != Unity.PreferencesManagerRemoteContent.ALL:
search.emit('finished')
return
if not self.is_in_China () :
print("Error can not search photo from Sogou !")
return
self._queued_search = (scope, search, search_type, cancellable)
search_string = search.props.search_string.strip()
if not self._enabled:
print ('Sogou : new search %s' % search_string)
date = self.check_date_filter (search)
i = 0
if search_string:
# for i in range(1,3):
if self._pending[i] is not None:
self._http[i].cancel_message(self._pending[i],
Soup.KnownStatusCode.CANCELLED)
url = self._url_maker(i, search_string, date)
self.url = url
if url:
self._pending[i] = Soup.Message.new("GET", url)
self._http[i].queue_message(self._pending[i],self._search_cb,[search_string, model, i, search])
else:
# for i in range(3):
if self._pending[i] is not None:
self._http[i].cancel_message(self._pending[i],
Soup.KnownStatusCode.CANCELLED)
url = self._url_maker(i, search_string, date)
if url:
self._pending[i] = Soup.Message.new("GET", url)
self._http[i].queue_message(self._pending[i],self._search_cb,[search_string, model, i, search])
else:
search.emit('finished')
def update_results_model(self, search, model, results, cat, recent_done):
"""Update results for category 0, then the others"""
counter = 0
myresults = {}
myresults = results
for k in myresults:
if (k == 'items'):
self.items = myresults['items']
for index, k in enumerate(self.items):
self.new_dic['title'] = k['title']
self.new_dic['page_url'] = k['page_url']
self.new_dic['pic_url'] = k['pic_url']
title = k['title']
page_url = k['page_url']
pic_url = k['pic_url']
size = k['size']
title1 = k['title1']
width = k['width']
height = k['height']
model.append(uri=self.new_dic['page_url'],icon_hint=self.new_dic['pic_url'],category=0,mimetype="text/html",title=self.new_dic['title'],comment='',dnd_uri=self.new_dic['page_url'],result_type=Unity.ResultType.PERSONAL)
self.result_list.append({'page_url':page_url, 'pic_url':pic_url,'title':title,'size':size,'title1':title1,'height':height,'width':width})
########
# Service answer handling
########
def _search_cb(self, session, msg, search_args):
"""Handle async Soup callback"""
results = self._handle_search_msg(msg, search_args[2])
self.update_results_model(search_args[0], search_args[1], results, search_args[2], False)
search_args[3].emit('finished')
def _handle_search_msg(self, msg, cat):
""" Handle response message"""
results = {}
a = ''
if msg.status_code != 200:
self._pending[cat] = None
print ("Error: Unable to get results from the server")
print (" %d: %s" % (msg.status_code, msg.reason_phrase))
else:
self._pending[cat] = None
try:
# a = urllib.parse.unquote(self.url).encode()
results = json.loads(urllib.request.urlopen(self.url).read().decode('gbk', 'ignore'))
# print(type(results))
except:
pass
return results
########
# Previews
########
def on_preview_uri(self, scope, uri):
"""Preview request handler"""
preview = None
if scope.last_result.uri == uri:
photo_id = uri
meta = self.getMetadataForPhoto (photo_id,scope.last_result.category)
width, date, image, title, description, height, position, album_size = None, None, None, '', '', None, None, None
if meta[6]:
title = meta[6]
elif meta[5]:
title = meta[5]
else:
title = scope.last_result.title
if meta[1]:
description = meta[1]
preview = Unity.GenericPreview.new(title.strip (), description.strip (), None)
if meta[2]:
preview.props.image_source_uri = meta[2]
else:
preview.props.image_source_uri = scope.last_result.icon_hint
if meta[8]:
preview.props.subtitle = meta[8]
if meta[7]:
preview.add_info(Unity.InfoHint.new("width", _("Width"), None, meta[7]))
if meta[9]:
album = meta[9]
if meta[10] and meta[11]:
# album = "%s, %i of %i" % (meta[9], meta[10], meta[11])
album = "%s, %i of %i" % (12, 12, 12)
preview.add_info(Unity.InfoHint.new("height", _("Height"), None, album))
if meta[4]:
preview.add_info(Unity.InfoHint.new("with", _("With"), None, meta[4]))
gfile_icon = Gio.file_new_for_path("/usr/share/icons/unity-icon-theme/places/svg/service-sogou.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)
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
def getMetadataForPhoto(self, oid, cat):
"""Fetch photo metadata from service"""
url = oid
link, size, image, subtitle = None, None, None, None
subject, tags, height, position = None, None, None, None
width, name, username, album_size = None, None, None, None
tag_list = []
for i in self.result_list:
if url == i['page_url']:
image = i['pic_url']
name = i['title']
size = i['size']
subtitle = i['title1']
width = i['width']
height = i['height']
return [link,size, image, subject, tags, username, name, width, subtitle, height, position, album_size]
if __name__ == '__main__':
daemon = UnityExtras.dbus_own_name(BUS_NAME, Daemon, None)
if daemon:
GLib.unix_signal_add(0, 2, lambda x: daemon.quit(), None)
daemon.run([])
|