This file is indexed.

/usr/share/pyshared/freevo/plugin.py is in python-freevo 1.9.2b2-4.2.

This file is owned by root:root, with mode 0o644.

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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------
# Plug-in interface
# -----------------------------------------------------------------------
# $Id: plugin.py 11905 2011-11-14 21:54:46Z adam $
# -----------------------------------------------------------------------
# Freevo - A Home Theater PC framework
# Copyright (C) 2002 Krister Lagerstrom, et al.
# Please see the file freevo/Docs/CREDITS for a complete list of authors.
#
# 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 MER-
# CHANTABILITY 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.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# -----------------------------------------------------------------------

"""
Plug-in interface
"""
import logging
logger = logging.getLogger("freevo.plugin")

import os, sys
import traceback
import gettext
import copy

# cannot import config here
from event import Event
import rc

import kaa

#
# Some basic plugins known to Freevo.
#

class Plugin:
    """
    Basic plugin class. All plugins should inherit from this
    class
    """
    def __init__(self):
        import config
        self._type   = None
        self._level  = 10
        self._number = 0
        self.plugin_name   = ''
        for var, val, desc in self.config():
            if not hasattr(config, var):
                setattr(config, var, val)

    def init_failed(self, reason):
        """
        Mark this plugin as failed to initialise. This method is need when
        config variables must have been set, which is perform by Plugin.__init__,
        but the plugin then finds it is unable to complete initialisation.
        """
        del self._type
        self.reason = reason

    def config(self):
        """
        return a list of config variables this plugin needs to be set in
        in freevo_config.py. Each variable in again a list and contains
        (varname, default value, description)
        """
        return []


    def translation(self, application):
        """
        Loads the gettext translation for this plugin (only this class).
        This can be used in plugins who are not inside the Freevo distribution.
        After loading the translation, gettext can be used by self._() instead
        of the global _().
        """
        try:
            self._ = gettext.translation(application, os.environ['FREEVO_LOCALE'], fallback=1).gettext
        except:
            self._ = lambda m: m



class MainMenuPlugin(Plugin):
    """
    Plugin class for plugins to add something to the main menu
    """
    def __init__(self):
        Plugin.__init__(self)


    def items(self, parent):
        """
        return the list of items for the main menu
        """
        return []



class ItemPlugin(Plugin):
    """
    Plugin class to add something to the item action list

    The plugin can also have an eventhandler. All events passed to the item
    will also be passed to this plugin. This works only for VideoItems right
    now (each item type must support it directly). If the function returns
    True, the event won't be passed to other eventhandlers and also not to
    the item itself.

    def eventhandler(self, item, event, menuw=None):
    """
    def __init__(self):
        Plugin.__init__(self)


    def actions(self, item):
        """
        return a list of actions to that item. Each actions is a tuple
        (function, 'name-in-the-menu')
        """
        return []



class DaemonPlugin(Plugin):
    """
    Plugin class for daemon objects who will be activate in the
    background while Freevo is running

    A DaemonPlugin can have the following functions:

    def poll(self):
    this function will be called every poll_intervall*0.1 seconds

    def draw(self(type, object), osd):
    this function will be called to update the screen

    def eventhandler(self, event, menuw=None):
    events no one else wants will be passed to this functions, when you also set
    the variable event_listener to True, the object will get all events

    def shutdown(self):
    this function may be called to shutdown the plugin and will be called on freevo
    shutdown
    """
    def __init__(self):
        Plugin.__init__(self)
        self.poll_counter   = 0         # poll counter, don't change this
        self.poll_interval  = 10        # poll every 1/10 second, approximately
        self.poll_menu_only = True      # poll only when menu is active
        self.event_listener = False     # process all events


    def poll_wrapper(self):
        import skin
        if self.poll_menu_only and not skin.active():
            return
        self.poll()



class MimetypePlugin(Plugin):
    """
    Plugin class for mimetypes handled in a directory/playlist.
    self.display_type is a list of display types where this mimetype
    should be displayed, [] for always.
    """
    def __init__(self):
        import util
        Plugin.__init__(self)
        self.display_type = []
        self.find_matches = util.find_matches


    def suffix(self):
        """
        return the list of suffixes this class handles
        """
        return []


    def get(self, parent, files):
        """
        return a list of items based on the files
        """
        return []


    def count(self, parent, files):
        """
        return how many items will be build on files
        """
        return len(self.find_matches(files, self.suffix()))


    def dirinfo(self, diritem):
        """
        set information for a diritem based on the content, etc.
        """
        pass


    def dirconfig(self, diritem):
        """
        adds configure variables to the directory
        """
        return []


#
# Some plugin names to avoid typos
#

AUDIO_PLAYER   = 'AUDIO_PLAYER'
RADIO_PLAYER   = 'RADIO_PLAYER'
VIDEO_PLAYER   = 'VIDEO_PLAYER'
TV             = 'TV'
RECORD         = 'RECORD'


#
# Plugin functions
#


def activate(name, type=None, level=10, args=None):
    """
    activate a plugin
    """
    global __plugin_number__
    global __all_plugins__
    global __initialized__

    __plugin_number__ += 1

    for p in __all_plugins__:
        if not isinstance(name, Plugin) and p[0] == name and p[1] == type and p[3] == args:
            print 'WARNING: duplicate plugin activation, ignoring:'
            print '<%s %s %s>' % (name, type, args)
            print
            return
    if __initialized__:
        __load_plugin__(name, type, level, args, __plugin_number__)
        __sort_plugins__()
    else:
        __all_plugins__.append((name, type, level, args, __plugin_number__))
    return __plugin_number__


def remove(id):
    """
    remove a plugin from the list. This can only be done in local_config.py
    and not while Freevo is running
    """
    global __all_plugins__
    global __initialized__

    if __initialized__:
        return

    # remove by plugin id
    if isinstance(id, int):
        for p in __all_plugins__:
            if p[4] == id:
                __all_plugins__.remove(p)
                return

    # remove by name
    r = []
    for p in copy.copy(__all_plugins__):
        if p[0] == id:
            __all_plugins__.remove(p)


def is_active(name, arg=None):
    """
    search the list if the given plugin is active. If arg is set,
    check arg, too.
    """
    global __all_plugins__
    for p in __all_plugins__:
        if p[0] == name:
            if not arg:
                return p
            if isinstance(arg, list) or isinstance(arg, tuple):
                try:
                    for i in range(len(arg)):
                        if arg[i] != p[3][i]:
                            break
                    else:
                        return p
                except:
                    pass
            if arg == p[3]:
                return p
    return None


def init(callback = None):
    """
    load and init all the plugins
    """
    global __all_plugins__
    global __initialized__
    global __plugin_basedir__

    __initialized__ = True
    __plugin_basedir__ = os.environ['FREEVO_PYTHON']

    current = 0
    for name, type, level, args, number in __all_plugins__:
        current += 1
        if callback:
            callback(int((float(current) / len(__all_plugins__)) * 100))
        __load_plugin__(name, type, level, args, number)

    # sort plugins in extra function (exec doesn't like to be
    # in the same function is 'lambda'
    __sort_plugins__()


def init_special_plugin(id):
    """
    load only the plugin 'id'
    """
    global __all_plugins__
    global __initialized__
    global __plugin_basedir__

    __plugin_basedir__ = os.environ['FREEVO_PYTHON']

    try:
        id = int(id)
    except ValueError:
        pass
    for i in range(len(__all_plugins__)):
        name, type, level, args, number = __all_plugins__[i]
        if number == id or name == id:
            __load_plugin__(name, type, level, args, number)
            del __all_plugins__[i]
            break

    # sort plugins in extra function (exec doesn't like to be
    # in the same function is 'lambda'
    __sort_plugins__()


def shutdown(plugin_name=None):
    """
    called to shutdown one or all daemon plugins
    """
    plugins_to_shutdown = []
    for key in __plugin_type_list__:
        for p in __plugin_type_list__[key]:
            if (not plugin_name or p.plugin_name == plugin_name) and hasattr(p, 'shutdown'):
                if p not in plugins_to_shutdown:
                    plugins_to_shutdown.append(p)

    for p in plugins_to_shutdown:
        plugin_name = p.__module__
        _debug_('shutting down plugin %r' % (plugin_name,), 1)
        p.shutdown()
        _debug_('shut down plugin %r' % (plugin_name,), 2)


def get(type):
    """
    get the plugin list 'type'
    """
    global __plugin_type_list__

    if not __plugin_type_list__.has_key(type):
        __plugin_type_list__[type] = []

    return __plugin_type_list__[type]


def mimetype(display_type):
    """
    return all MimetypePlugins for the given display_type. If display_type is
    None, return all MimetypePlugins.
    """
    ret = []
    if not __plugin_type_list__:
        return ret
    if not display_type:
        return __plugin_type_list__['mimetype']
    for p in __plugin_type_list__['mimetype']:
        if not p.display_type or display_type in p.display_type:
            ret.append(p)
    return ret


def getall():
    """
    return a list of all plugins
    """
    global __all_plugins__
    ret = []
    for t in __all_plugins__:
        ret.append(t[0])
    return ret


def getbyname(name, multiple_choises=0):
    """
    get a plugin by it's name
    """
    global __named_plugins__
    if __named_plugins__.has_key(name):
        return __named_plugins__[name]
    if multiple_choises:
        return []
    return None


def register(plugin, name, multiple_choises=0):
    """
    register an object as a named plugin
    """
    global __named_plugins__
    if multiple_choises:
        if not __named_plugins__.has_key(name):
            __named_plugins__[name] = []
        __named_plugins__[name].append(plugin)
    else:
        __named_plugins__[name] = plugin


def register_callback(name, *args):
    """
    register a callback to the callback handler 'name'.
    @note: The format of args depends on the callback
    """
    global __callbacks__
    if not __callbacks__.has_key(name):
        __callbacks__[name] = []
    __callbacks__[name].append(args)


def get_callbacks(name):
    """
    return all callbacks registered with 'name'
    """
    global __callbacks__
    if not __callbacks__.has_key(name):
        __callbacks__[name] = []
    return __callbacks__[name]


def event(name, arg=None):
    """
    create plugin event
    """
    return Event('PLUGIN_EVENT %s' % name, arg=arg)


def isevent(event):
    """
    plugin event parsing
    """
    event = str(event).split('PLUGIN_EVENT ')
    if len(event) == 2:
        return event[1]
    else:
        return None





#
# internal stuff
#

__initialized__        = False
__all_plugins__        = []
__plugin_number__      = 0
__plugin_type_list__   = {}
__named_plugins__      = {}
__callbacks__          = {}
__plugin_basedir__     = ''


def __add_to_ptl__(type, object):
    """
    small helper function to add a plugin to the PluginTypeList
    """
    global __plugin_type_list__
    if not __plugin_type_list__.has_key(type):
        __plugin_type_list__[type] = []
    __plugin_type_list__[type].append(object)



def __find_plugin_file__(filename):
    global __plugin_basedir__
    full_filename = os.path.join(__plugin_basedir__, filename)

    if os.path.isfile(full_filename + '.py'):
        return filename.replace('/', '.'), None

    if os.path.isdir(full_filename):
        return filename.replace('/', '.'), None

    full_filename = os.path.join(__plugin_basedir__, 'plugins', filename)

    if os.path.isfile(full_filename + '.py'):
        return 'plugins.' + filename.replace('/', '.'), None

    if os.path.isdir(full_filename):
        return 'plugins.' + filename.replace('/', '.'), None

    if filename.find('/') > 0:
        special = filename[:filename.find('/')]
        filename = os.path.join(special, 'plugins', filename[filename.find('/')+1:])
        full_filename = os.path.join(__plugin_basedir__, filename)

        if os.path.isfile(full_filename + '.py'):
            return filename.replace('/', '.'), special

        if os.path.isdir(full_filename):
            return filename.replace('/', '.'), special

    return None, None



def __load_plugin__(name, type, level, args, number):
    """
    load the plugin and add it to the lists
    """
    import rc

    global __plugin_type_list__
    global __named_plugins__
    global __plugin_basedir__

    # fallback
    module  = name
    object  = '%s.PluginInterface' % module
    special = None

    # locate the plugin:
    files = []

    if not isinstance(name, Plugin):
        module, special = __find_plugin_file__(name.replace('.', '/'))
        if module:
            object = module + '.PluginInterface'
        elif name.find('.') > 0:
            module, special = __find_plugin_file__(name[:name.rfind('.')].replace('.', '/'))
            if module:
                object = module + '.%s' % name[name.rfind('.')+1:]
            else:
                print 'can\'t locate plugin %r' % name
                print 'start "freevo plugins -l" to get a list of plugins'
                return
        else:
            print 'can\'t locate plugin %r' % name
            print 'start "freevo plugins -l" to get a list of plugins'
            return

    try:
        if not isinstance(name, Plugin):
            _debug_('loading %s as plugin %s' % (module, object))

            exec('import %s' % module)
            if not args:
                p = eval(object)()
            elif isinstance(args, list) or isinstance(args, tuple):
                paramlist = 'args[0]'
                for i in range(1, len(args)):
                    paramlist += ',args[%s]' % i
                p = eval('%s(%s)' % (object, paramlist))
            else:
                p = eval(object)(args)

            if not hasattr(p, '_type'):
                if hasattr(p, 'reason'):
                    reason = p.reason
                else:
                    reason = 'unknown\nThe plugin neither called __init__ nor set a '\
                             'reason why\nPlease contact the plugin author or the freevo list'
                print 'plugin %s deactivated, reason: %s' % (name, reason)
                return
        else:
            p = name

        p._number = number
        p._level = level

        if type:
            special = type

        if special == 'main':
            special = ''
        elif special:
            special = '_%s' % special
        else:
            special = ''

        # special plugin type (e.g. idlebar)
        if p._type:
            __add_to_ptl__(p._type, p)

        else:
            if isinstance(p, DaemonPlugin):
                __add_to_ptl__('daemon', p)
                for type in ('poll', 'draw', 'eventhandler', 'shutdown' ):
                    if hasattr(p, type):
                        __add_to_ptl__('daemon_%s' % type, p)
                if hasattr(p, 'poll'):
                    if p.poll_menu_only:
                        # replace poll with the poll wrapper to handle
                        # poll_menu_only
                        p.timer = kaa.Timer(p.poll_wrapper)
                    else:
                        p.timer = kaa.Timer(p.poll)
                    p.timer.start(p.poll_interval)

            if isinstance(p, MainMenuPlugin):
                __add_to_ptl__('mainmenu%s' % special, p)
                if hasattr(p, 'eventhandler'):
                    __add_to_ptl__('daemon_eventhandler', p)

            if isinstance(p, ItemPlugin):
                __add_to_ptl__('item%s' % special, p)

            if isinstance(p, MimetypePlugin):
                __add_to_ptl__('mimetype', p)

        if p.plugin_name:
            __named_plugins__[p.plugin_name] = p


    except:
        print 'failed to load plugin %s' % name
        print 'start \'freevo plugins -l\' to get a list of plugins'
        traceback.print_exc()


def __sort_plugins__():
    """
    sort all plugin lists based on the level
    """
    global __plugin_type_list__
    for key in __plugin_type_list__:
        __plugin_type_list__[key].sort(lambda l, o: cmp(l._level, o._level))