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
|
#!/usr/bin/python
# This is a part of the external applets for Cairo-Dock
# Copyright : (C) 2011 by Fabounet
# E-mail : fabounet@glx-dock.org
#
# 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 2
# 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.
# http://www.gnu.org/licenses/licenses.html#GPL
####################
### dependancies ###
####################
try:
# Merge GLib's main loop with Twister's one
from twisted.internet import glib2reactor
glib2reactor.install()
# Import the client module
from deluge.ui.client import client
# Import the reactor module from Twisted - this is for our mainloop
from twisted.internet import reactor
# Set up the logger to print out errors
from deluge.log import setupLogger
import deluge.component
setupLogger()
except ImportError, e:
print e
print "This applet is designed to be used with Deluge 1.2 or later, make sure it is installed."
exit()
import subprocess
from os import popen
from math import sqrt
from gobject import timeout_add
from CDApplet import CDApplet, _
def format_bytes(x):
unit=''
if x < 1024:
unit = 'B'
y = x
elif x < 1048576:
unit = 'K'
y = float(x) / 1024
elif x < 1073741824:
unit = 'M'
y = float(x) / 1048576
else:
unit = 'G'
y = float(x) / 1073741824
return y,unit
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in text)
####################
### Applet class ###
####################
class Applet(CDApplet):
def __init__(self):
# define internal variables
self.d = None
self.cClass = 'deluge'
self.bHasFocus = False
self.iSidGetData = 0
self.iSidTryConnect = 0
self.bConnected = False
self.bExit = False
# call high-level init
CDApplet.__init__(self)
##### private methods #####
# Connection
def try_connect(self):
#print "try_connect..."
if self.bConnected:
self.iSidTryConnect = 0
return False
else:
self.connnect_to_daemon()
return True
def connnect_to_daemon(self):
self.d = client.connect(self.config['server'], self.config['port'], self.config['user'], self.config['password'])
self.d.addCallback(self.on_connect_success)
self.d.addErrback(self.on_connect_fail)
def on_connect_fail(self,reason):
#print "Connection failed!"
#print "reason:", reason
self.bConnected = False
self.icon.SetQuickInfo("")
if self.iSidTryConnect == 0:
self.iSidTryConnect = timeout_add(2000,self.try_connect)
def on_connect_success(self,result):
print "*** connected to Deluge!"
self.bConnected = True
if self.iSidGetData == 0:
self.iSidGetData = timeout_add (2000, self.update_data)
def daemon_disconnect_callback(self):
print "*** Disconnected from deluge daemon"
self.bConnected = False
self.icon.SetQuickInfo("")
if not self.bExit: # we didn't get disconnected because the applet was stopped -> try to reconnect
if self.iSidTryConnect == 0:
self.iSidTryConnect = timeout_add(2000,self.try_connect)
# Global data
def update_data(self):
if not self.bConnected:
self.iSidGetData = 0
return False
client.core.get_session_status(["payload_download_rate"]).addCallback(self.on_got_data,'payload_download_rate')
return True
def on_got_data(self,value,key):
rate=value[key]
unit=''
if rate < 100:
rate = 0
rate,unit = format_bytes(rate)
form = ''
if rate == 0:
form = ".0f"
elif rate < 10:
form = ".2f"
elif rate < 100:
form = ".1f"
else:
form = ".0f"
self.icon.SetQuickInfo(format(rate,form)+unit)
# Torrents info
def show_torrents_info(self):
if self.bConnected:
client.core.get_torrents_status({},['name','progress','eta','paused','ratio','num_peers','num_seeds']).addCallback(self.on_got_torrents_status)
else:
self.icon.ShowDialog(_("Deluge is not running, or is not responding to us."), 4)
def on_got_torrents_status(self,status):
info = ""
n = 0
for id, value in status.items():
info += "<b>"+html_escape(value['name'])+"</b>:\n"
info += " progress: "+format(value['progress'],".1f")+'%'
if value['paused']:
info += " <i>(paused)</i>\n"
else: # active torrent
t = value['eta']
if t > 0:
info += " <i>(time remaining: "
d=h=m=s=0
if t > 86400:
d = int(t) / 86400
h = int(t - d*86400) / 3600
if d > 0:
info += str(d)+"days"
if d > 0 or h > 0:
info += str(h)+"h"
else:
h = int(t) / 3600
m = int(t - h*3600) / 60
s = int(t - h*3600 - m*60)
if h > 0:
info += str(h)+"h"
if h > 0 or m > 0:
info += str(m)+"mn"
info += str(s)+"s)"
info += "</i>\n"
else:
info += " <i>(finished)</i>\n"
info += " nb peers: "+str(value['num_peers'])+", nb seeds: "+str(value['num_seeds'])+"\n"
info += " ratio: "+format(value['ratio'],".2f")+'\n'
n += 1
if n == 0:
info += "<i>no torrent in the list</i>\n"
client.core.get_session_status(["total_payload_download","total_payload_upload"]).addCallback(self.on_got_total_amount,info)
def on_got_total_amount(self,values,info):
info += "\n<b>total amount of data:</b>\n"
dl = values["total_payload_download"]
if dl < 100:
form = ".0f"
else:
form = ".1f"
dl,unit = format_bytes(dl)
info += " - received: "+format(dl,form)+unit+"\n"
ul = values["total_payload_upload"]
if ul < 100:
form = ".0f"
else:
form = ".1f"
ul,unit = format_bytes(ul)
info += " - sent: "+format(ul,form)+unit
dialog_attributes = {
"icon" : "deluge",
"message" : info,
"use-markup" : True,
"time-length" : 4+len(info)/40 }
widget_attributes = {}
self.icon.PopupDialog (dialog_attributes, widget_attributes)
##### applet definition #####
def get_config(self,keyfile):
self.config['server'] = keyfile.get('Configuration', 'server')
self.config['port'] = keyfile.getint('Configuration', 'port')
self.config['user'] = keyfile.get('Configuration', 'user')
self.config['password'] = keyfile.get('Configuration', 'password')
self.config['shortkey'] = keyfile.get('Configuration', 'shortkey')
if self.config['server'] == '':
self.config['server'] = '127.0.0.1'
if self.config['port'] == 0:
self.config['port'] = 58846
def end(self):
print "*** end of Deluge applet"
self.bExit = True # to not try to reconnect when we get the 'disconnected' signal
client.disconnect()
reactor.stop()
def begin(self):
self.icon.BindShortkey([self.config['shortkey']])
self.icon.ControlAppli(self.cClass)
client.set_disconnect_callback(self.daemon_disconnect_callback)
self.connnect_to_daemon()
reactor.run()
def reload(self):
self.icon.BindShortkey([self.config['shortkey']])
##### callbacks #####
def on_click(self,iState):
Xid = self.icon.Get("Xid")
if Xid != 0:
if self.bHasFocus:
self.icon.ActOnAppli("minimize")
else:
self.icon.ActOnAppli("show")
else: # Deluge not started, or in the systray.
print "launch Deluge..."
if not self.bConnected:
subprocess.Popen('deluged')
subprocess.Popen(self.cClass)
def on_middle_click(self):
self.show_torrents_info()
def on_build_menu(self):
if self.bConnected:
items = [ {
"label": _("Pause all torrents"),
"icon" : "gtk-media-pause",
"menu" : CDApplet.MAIN_MENU_ID,
"id" : 1
}, {
"label": _("Resume all torrents"),
"icon" : "gtk-media-play",
"menu" : CDApplet.MAIN_MENU_ID,
"id" : 2
}, {
"label": _("Torrents info") + " (" + _("middle-click") + ")",
"icon" : "gtk-info",
"menu" : CDApplet.MAIN_MENU_ID,
"id" : 3
} ]
self.icon.AddMenuItems(items)
def on_menu_select(self,iNumEntry):
if iNumEntry == 1:
client.core.pause_all_torrents()
elif iNumEntry == 2:
client.core.resume_all_torrents()
elif iNumEntry == 3:
self.show_torrents_info()
def on_drop_data(self,cReceivedData):
print "*** received: "+cReceivedData
if self.bConnected:
client.core.add_torrent_url(str(cReceivedData),None)
else:
subprocess.Popen('deluged')
popen(self.cClass+" "+cReceivedData+"&")
def on_shortkey(self,key):
self.show_torrents_info()
def on_change_focus(self,has_focus):
self.bHasFocus = has_focus
############
### main ###
############
if __name__ == '__main__':
Applet().run()
|