summaryrefslogtreecommitdiffstats
path: root/plugins/WebUi/json_api.py
blob: 720aec91beda89e60ebb0b1f8d3801bab0555164 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# webserver_framework.py
#
# Copyright (C) Martijn Voncken 2007 <mvoncken@gmail.com>
#
# 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, 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, write to:
#     The Free Software Foundation, Inc.,
#     51 Franklin Street, Fifth Floor
#     Boston, MA  02110-1301, USA.
#
#  In addition, as a special exception, the copyright holders give
#  permission to link the code of portions of this program with the OpenSSL
#  library.
#  You must obey the GNU General Public License in all respects for all of
#  the code used other than OpenSSL. If you modify file(s) with this
#  exception, you may extend this exception to your version of the file(s),
#  but you are not obligated to do so. If you do not wish to do so, delete
#  this exception statement from your version. If you delete this exception
#  statement from all source files in the program, then also delete it here.
"""
json api.
only used for XUL and/or external scripts
it would be possible not to incluse the python-json dependency.
"""

from new import instancemethod
from inspect import getargspec
from webserver_framework import remote,ws,get_torrent_status,log,get_category_choosers, get_stats,log,filter_torrent_state,fsize,fspeed
from operator import attrgetter
import lib.webpy022 as web
proxy = ws.proxy

def to_json(obj):
    from lib.pythonize import pythonize
    obj = pythonize(obj)
    try:
        import json
        return json.write(obj)
    except ImportError:
        raise ImportError("""Install python-json using your package-manager
        http://sourceforge.net/projects/json-py/""")

class json_api:
    """
    eperimental json api
    generic proxy for all methods onm self.
    """
    illegal_methods = ['shutdown', 'socket', 'xmlrpclib','pickle','os',
        'is_localhost','CoreProxy','connect_on_new_core', 'connect_on_no_core',
        'connected','deluge','GET','POST']
    def __init__(self):
        self._add_proxy_methods()

    #extra exposed:
    get_torrent_status = get_torrent_status

    @remote
    def POST(self,name):
        import json
        if name.startswith('_'):
            raise AttributeError('_ methods are illegal.')
        if name in self.illegal_methods:
            raise AttributeError('Illegal method.')
        if not(hasattr(self,name)):
            raise AttributeError('No such method')

        method = getattr(self,name)
        vars = web.input(kwargs= None)
        log.debug('vars=%s' % vars)
        if vars.kwargs:
            kwargs = json.read(vars.kwargs)
        else:
            kwargs = {}

        result = method(**kwargs)

        return "(" + to_json(result) + ")"


    def list_methods(self):
        """
        list all json methods
        returns a dict of {methodname:{args:[list of kwargs],doc:'string'},..}
        """
        methods = [getattr(self,m) for m in dir(self)
            if not m.startswith('_')
            and (not m in self.illegal_methods)
            and callable(getattr(self,m))
            ]

        return dict([(f.__name__,
            {'args':getargspec(f)[0],'doc':(f.__doc__ or '').strip()})
            for f in methods])

    def _add_proxy_methods(self):
        methods = [getattr(proxy,m) for m in dir(proxy)
            if not m.startswith('_')
            and (not m in self.illegal_methods)
            and callable(getattr(proxy,m))
            ]
        for m in methods:
            setattr(self,m.__name__,m)

    #extra's:
    def list_torrents(self):
        return [get_torrent_status(torrent_id)
            for torrent_id in ws.proxy.get_session_state()]

    def simplify_torrent_status(self, torrent):
        """smaller subset and preformatted data for the treelist"""
        data = {
            "id":torrent.id,
            "message":torrent.message,
            "name":torrent.name,
            "total_size":fsize(torrent.total_size),
            "progress":torrent.progress,
            "category":torrent.category,
            "seeds":"",
            "peers":"",
            "download_rate":"",
            "upload_rate":"",
            "eta":"",
            "distributed_copies":"",
            "ratio":"",
            "calc_state_str":torrent.calc_state_str,
            "queue_pos":torrent.queue_pos
        }
        if torrent.total_seeds > 0:
            data['seeds'] = "%s (%s)" % (torrent.num_seeds, torrent.total_seeds)
        if torrent.total_peers > 0:
            data['peers'] = "%s (%s)" % (torrent.num_peers, torrent.total_peers)
        if torrent.download_rate > 0:
            data['download_rate'] =  fspeed(torrent.download_rate)
        if torrent.upload_rate > 0:
            data['upload_rate'] = fspeed(torrent.upload_rate)
        if torrent.eta > 0:
            data['eta'] = ("%.3f" % torrent.eta)
        if torrent.distributed_copies > 0:
            data['distributed_copies'] = "%.3f" % torrent.distributed_copies
        if torrent.ratio > 0:
            data['ratio'] = "%.3f" % torrent.ratio
        return data

    def update_ui(self, filter=None, category=None ,sort='name' ,order='down'):
        """
        Combines the most important ui calls into 1 composite call.
        xmlhttp requests are expensive,max 2 running at the same time.
        and performance over the internet is mostly related to the number
        of requests (low ping)
        returns :
        {torrent_list:[{},..],'categories':[],'filters':'','stats':{}}
        """
        torrent_list = self.list_torrents();
        filter_tabs, category_tabs = get_category_choosers(torrent_list)


        #filter-state
        if filter:
            torrent_list = filter_torrent_state(torrent_list, filter)

        #filter-cat
        if category:
            torrent_list = [t for t in torrent_list if t.category == category]

        #sorting
        if sort:
            torrent_list.sort(key=attrgetter(sort))
            if order == 'up':
                torrent_list = reversed(torrent_list)

        torrent_list = [self.simplify_torrent_status(t) for t in torrent_list]

        return {
            'torrent_list':torrent_list,
            'categories':category_tabs,
            'filters':filter_tabs,
            'stats':get_stats()
        }



if __name__ == '__main__':
    from pprint import pprint
    #proxy.set_core_uri('http://localhost:58846') #How to configure this?
    j = json_api()
    if True:
        print 'list-methods:'
        methods = j.list_methods()
        names = methods.keys()
        names.sort()
        for name in names:
            m = methods[name]
            print "%s(%s)\n        %s\n" % (name , m['args'] , m['doc'])

        #j.GET('list_torrents')
        j.POST('list_torrents')