~jderose/dmedia/non-suck

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

# Authors:
#   Jason Gerard DeRose <jderose@novacut.com>
#   David Green <david4dev@gmail.com>
#
# dmedia: distributed media library
# Copyright (C) 2010, 2011 Jason Gerard DeRose <jderose@novacut.com>
#
# This file is part of `dmedia`.
#
# `dmedia` is free software: you can redistribute it and/or modify it under the
# terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# `dmedia` 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 Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with `dmedia`.  If not, see <http://www.gnu.org/licenses/>.


"""
Command line tool for talking to dmedia DBus services.
"""

from sys import argv, stderr
import dmedia
from dmedia.constants import BUS, IFACE
import dbus

class DBusCLI (object):
    """
    DBusCLI allows you to easily create command line interfaces from
    DBus APIs.

    Example usage:
        my_cli = DBusCLI(
            'mycli', '1.0', 'org.freedesktop.My',
            '/', 'org.freedesktop.My'
        )
        my_cli.add_action("name1", function1, "usage of name1", "description of name1")
        my_cli.add_dbus_action("MethodName", "usage of MethodName", "description of MethodName")
        if __name__ == '__main__':
            my_cli.main(*sys.argv[1:])
    """
    def __init__(self, exec_name, version, dbus_bus, dbus_object, dbus_iface):
        """
        `exec_name` is the name of the executable of the command line
        program. It should be what the user needs to run to use the
        program.

        `version` is the version string of the command line program.

        `dbus_bus` is the dbus bus name of the dbus API.

        `dbus_object` is the dbus object of the dbus API.

        `dbus_iface` is the dbus interface of the dbus API.
        """
        self._exec = exec_name
        self._version = version
        self._default_bus = dbus_bus
        self._bus = self._default_bus
        self._obj = dbus_object
        self._iface = dbus_iface
        self._action_methods = {}
        self._action_help = {}
        self._conn = dbus.SessionBus()
        self._add_default_actions()

    def has_action(self, name):
        """
        Return true if the action `name` exists,
        false otherwise.
        """
        return (self._action_methods.has_key(name) and
            self._action_help.has_key(name))

    def get_action_method(self, name):
        """
        Return the function for action `name`.
        """
        return self._action_methods[name]

    def get_usage(self):
        """
        Return the usage string for this program.
        """
        return """Usage:
\t%s ACTION [ARGUMENTS]

Run:
\t%s help ACTION
for help with a specific action.

Run:
\t%s actions
for a list of available actions.
""" % (self._exec, self._exec, self._exec)

    def get_help(self, *names):
        """
        Return the help string for action(s) `names`.
        If no names are specified, the help string will show
        help for all available actions.
        """
        if len(names) == 0:
            names = self.get_actions()
        return "\n".join(map(
            lambda name: "Action `%s`. Usage:\n\t%s %s %s\n%s\n" % (
                (name, self._exec, name) + self._action_help[name]
            ),
            names
        ))

    def get_actions(self):
        """
        Return all available actions as a tuple.
        """
        return tuple(self._action_methods)

    def show_usage(self):
        """
        Display the usage string for this program.
        """
        print(self.get_usage())

    def show_help(self, *names):
        """
        Display the help string for `names`. See `get_help`.
        """
        print(self.get_help(*names))

    def show_actions(self):
        """
        Display all available actions, each on a separate line.
        """
        print("\n".join(self.get_actions()))

    def show_version(self):
        """
        Display the version of this program.
        """
        print(self._version)

    def dbus_run(self, name, *args):
        """
        Run the dbus method `name` with arguments `args`.
        Catch any errors and print them to stderr.
        """
        proxy = self._conn.get_object(self._bus, self._obj)
        method = proxy.get_dbus_method(name, dbus_interface=self._iface)
        try:
            print(str(method(*args)))
        except Exception, e:
            stderr.write("Error: %s\n"%e.message)

    def run_action(self, name, *args):
        """
        Run the action `name` with arguments `args`.
        """
        if self.has_action(name):
            self.get_action_method(name)(*args)
        else:
            stderr.write("No such action `%s`\n" % name)
            print(self.get_usage())

    def run_action_with_bus(self, bus, name, *args):
        """
        Run the action `name` with arguments `args`.
        Use a custom dbus bus name `bus`.
        """
        self._bus = bus
        self.run_action(name, *args)

    def add_action(self, name, function=lambda *a:None, usage="", description=""):
        """
        Add an action to the command line program.
        `name` is the name of the action.
        `function` is the function to be called for this action.
        `usage` is a string describing the arguments of the action to the user.
        `description` is a string describing what the action does.
        """
        self._action_methods[name] = function
        self._action_help[name] = (usage, description)

    def add_dbus_action(self, name, usage="", description=""):
        """
        Add an action to the command line program based upon a dbus method.
        `name` is the name of the action and the name of the dbus method.
        `usage` is a string describing the arguments of the action to the user.
        `description` is a string describing what the action does.
        """
        self.add_action(
            name,
            lambda *args:self.dbus_run(name, *args),
            usage,
            description
        )

    def _add_default_actions(self):
        #version
        self.add_action(
            "version",
            self.show_version,
            "",
            "Display the version of this program."
        )
        #help
        self.add_action(
            "help",
            self.show_help,
            "[ACTION_1] [ACTION_2] ... [ACTION_N]",
            "Display help information for each of the listed actions. If no actions are listed, help will be displayed for all available actions."
        )
        #usage
        self.add_action(
            "usage",
            self.show_usage,
            "",
            "Display a usage message."
        )
        #actions
        self.add_action(
            "actions",
            self.show_actions,
            "",
            "Display the list of available actions."
        )
        #bus
        self.add_action(
            "bus",
            self.run_action_with_bus,
            "BUS_NAME ACTION [ARGUMENTS]",
            "Run an action using the dbus bus `BUS_NAME` for any dbus interaction."
        )

    def main(self, *args):
        """
        Run the command line program with the specified arguments.
        """
        args = list(args)
        if len(args) < 1:
            self.run_action("usage")
        else:
            self.run_action(args.pop(0), *args)

dmedia_cli = DBusCLI("dmedia-cli", dmedia.__version__, BUS, '/', IFACE)

dmedia_cli.add_dbus_action("Version", "", "Display the version of running `dmedia-service`.")
dmedia_cli.add_dbus_action("Kill", "", "Shutdown `dmedia-service`.")
dmedia_cli.add_dbus_action("AddFileStore", "PARENT_DIR", "Add a new dmedia file store. Create it in the `PARENT_DIR` directory (eg. /home/username).")
dmedia_cli.add_dbus_action("GetDoc", "DOC_ID", "Get a document from CouchDB. `DOC_ID` is the _id of the document.")
dmedia_cli.add_dbus_action("Upload", "FILE_ID STORE_ID", "Upload the file with id `FILE_ID` to the remote store with id `STORE_ID`.")
dmedia_cli.add_dbus_action("Download", "FILE_ID STORE_ID", "Download the file with id `FILE_ID` from the remote store with id `STORE_ID`.")
dmedia_cli.add_dbus_action("ListTransfers", "", "List active uploads and downloads.")
dmedia_cli.add_dbus_action("GetEnv", "", "Display dmedia env as JSON.")
dmedia_cli.add_dbus_action("GetAuthURL", "", "Get URL with basic auth user and password.")
dmedia_cli.add_dbus_action("HasApp", "", "")

if __name__ == '__main__':
    dmedia_cli.main(*argv[1:])