Internet radio browser GUI for music/video streams from various directory services.

⌈⌋ branch:  streamtuner2


Check-in [8178f6832b]

Overview
Comment:Add plugin defaults now really on initialization. Safeguard in configwin. Always use gtk.STOCK_NEW for empty app fields in config_dialog (not just for new lines).
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 8178f6832b1bcde6796afe2286289a31db68ba39
User & Date: mario on 2015-04-04 10:00:37
Other Links: manifest | tags
Context
2015-04-04
10:01
Spread out #pack: specifiers into doc files. check-in: 31995cd149 user: mario tags: trunk
10:00
Add plugin defaults now really on initialization. Safeguard in configwin. Always use gtk.STOCK_NEW for empty app fields in config_dialog (not just for new lines). check-in: 8178f6832b user: mario tags: trunk
06:06
Compress gtkBuilder file with zlib for distribution. (gzip not usable without workarounds in Python2) check-in: 780f0ca590 user: mario tags: trunk
Changes

Makefile became executable with contents [4a807d2d9d].

Modified channels/configwin.py from [af833a9f7e] to [ec93be6e35].

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
                    config[key] = {}
                    for row in w:
                        if row[0] and row[1]:
                            config[key][row[0]] = row[1]
            __print__(dbg.CONF, "config save", prefix+key, val)
    
    
    # Generic Gtk callback to update ListStore when entries get edited


    def list_edit(self, liststore, path, column, new_text):
        liststore[path][column] = new_text
        liststore[path][3] = self.app_bin_check(new_text)
        # The signal_connect() dict actually prepares individual lambda functions
        # to bind the correct ListStore and column id.

    # return OK or CANCEL depending on availability of app
    def app_bin_check(self, v):
        m = re.search("(?![$(`])\S+", v)
        if m and m.group(0) and find_executable(m.group(0)):

            return gtk.STOCK_MEDIA_PLAY
        else:
            return gtk.STOCK_CANCEL


        


    # iterate over channel and feature plugins
    def add_plugins(self):
        ls = dict([(name, plugin_meta(module=name)) for name in module_list()])
        #for name in module_list():
        #    if name in self.channels:
        #        ls[name] = self.channels[name].meta
        #    elif name in self.features:
        #        ls[name] = self.features[name].meta
        #    else:
        #        ls[name] = plugin_meta(module=name)
        for name,meta in sorted(ls.items(), key=lambda e: e[1]["type"]+e[1]["title"].lower(), reverse=False):


            self.add_plg(name, meta)


    # add configuration setting definitions from plugins
    plugin_text = "<span size='larger' weight='heavy'>%s</span> <span style='italic' foreground='slate blue'>(%s/%s)</span> <span weight='bold' foreground='orange'>%s</span>\n<span size='smaller' stretch='ultraexpanded'>%s</span>"
    def add_plg(self, name, meta):
        # add plugin load entry







|
>
>



<
<




|
>
|
|
|
>
>














>
>







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
                    config[key] = {}
                    for row in w:
                        if row[0] and row[1]:
                            config[key][row[0]] = row[1]
            __print__(dbg.CONF, "config save", prefix+key, val)
    
    
    # Generic Gtk callback to update ListStore when entries get edited.
    # (The main signal_connect() dict prepares individual lambda funcs
    # for each ListStore column id.)
    def list_edit(self, liststore, path, column, new_text):
        liststore[path][column] = new_text
        liststore[path][3] = self.app_bin_check(new_text)



    # return OK or CANCEL depending on availability of app
    def app_bin_check(self, v):
        m = re.search("(?![$(`])\S+", v)
        if m and m.group(0):
            if find_executable(m.group(0)):
                return gtk.STOCK_MEDIA_PLAY
            else:
                return gtk.STOCK_CANCEL
        else:
            return gtk.STOCK_NEW
        


    # iterate over channel and feature plugins
    def add_plugins(self):
        ls = dict([(name, plugin_meta(module=name)) for name in module_list()])
        #for name in module_list():
        #    if name in self.channels:
        #        ls[name] = self.channels[name].meta
        #    elif name in self.features:
        #        ls[name] = self.features[name].meta
        #    else:
        #        ls[name] = plugin_meta(module=name)
        for name,meta in sorted(ls.items(), key=lambda e: e[1]["type"]+e[1]["title"].lower(), reverse=False):
            if not name in conf.plugins:
                conf.plugins[name] = False
            self.add_plg(name, meta)


    # add configuration setting definitions from plugins
    plugin_text = "<span size='larger' weight='heavy'>%s</span> <span style='italic' foreground='slate blue'>(%s/%s)</span> <span weight='bold' foreground='orange'>%s</span>\n<span size='smaller' stretch='ultraexpanded'>%s</span>"
    def add_plg(self, name, meta):
        # add plugin load entry

Modified config.py from [5baf9d2d63] to [86c0092432].

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
           "video/*": self.find_player(typ="video", default="vlc"),
           "url/http": self.find_player(typ="browser"),
        }
        self.record = {
           "audio/*": self.find_player(typ="xterm") + " -e streamripper %srv",   # -d /home/***USERNAME***/Musik
           "video/youtube": self.find_player(typ="xterm") + " -e \"youtube-dl %srv\"",
        }
        # these presets are a temporary workaround, until `priority:` is checked before module loading
        self.plugins = {
             # core plugins, cannot be disabled anyway
            "bookmarks": 1,
            "search": 1,
            "streamedit": 1,
            "configwin": 1,
            # standard channels
            "shoutcast": 1,
            "xiph": 1,
            "myoggradio": 1,
            "internet_radio": 1,
            "surfmusik": 1,
            "jamendo": 1,
            "icast": 1,
            "itunes": 1,
            # disabled per default
            "radiobrowser": 0,
            "youtube": 0,
            "modarchive": 0,
            "live365": 0,
            "radiotray": 0,
            "timer": 0,
            "history": 0,
            "global_key": 0,
            "useragentswitcher": 0,
            # obsolete / removed
            "file": 0,
            "punkcast": 0,
            "basicch": 0,
            "tv": 0,
        }
        self.tmp = os.environ.get("TEMP", "/tmp")
        self.max_streams = "500"
        self.show_bookmarks = 1
        self.show_favicons = 1
        self.load_favicon = 1
        self.heuristic_bookmark_update = 0







|






<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







97
98
99
100
101
102
103
104
105
106
107
108
109
110
























111
112
113
114
115
116
117
           "video/*": self.find_player(typ="video", default="vlc"),
           "url/http": self.find_player(typ="browser"),
        }
        self.record = {
           "audio/*": self.find_player(typ="xterm") + " -e streamripper %srv",   # -d /home/***USERNAME***/Musik
           "video/youtube": self.find_player(typ="xterm") + " -e \"youtube-dl %srv\"",
        }
        # Presets are redundant now. On first startup the `priority:` field of each plugin is checked.
        self.plugins = {
             # core plugins, cannot be disabled anyway
            "bookmarks": 1,
            "search": 1,
            "streamedit": 1,
            "configwin": 1,
























        }
        self.tmp = os.environ.get("TEMP", "/tmp")
        self.max_streams = "500"
        self.show_bookmarks = 1
        self.show_favicons = 1
        self.load_favicon = 1
        self.heuristic_bookmark_update = 0
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
        config = meta.get("config", [])
        for opt in config:
            if ("name" in opt) and ("value" in opt) and (opt["name"] not in vars(self)):
                self.__dict__[opt["name"]] = opt["value"]

        # plugin state
        if module and module not in conf.plugins:
             conf.plugins[module] = meta.get("priority") in ("core", "builtin", "default", "standard")


    # look at system binaries for standard audio players
    def find_player(self, typ="audio", default="xdg-open"):
        players = {
           "audio": ["audacious %g", "audacious2", "exaile %p", "xmms2", "banshee", "amarok %g", "clementine", "qmmp", "quodlibet", "aqualung", "mp3blaster %g", "vlc --one-instance %srv", "totem"],
           "video": ["parole", "umplayer", "xnoise", "gxine", "totem", "vlc --one-instance", "smplayer", "gnome-media-player", "xine", "bangarang"],
           "browser": ["opera", "midori", "sensible-browser"],
           "xterm": ["xfce4-terminal", "x-termina-emulator", "gnome-terminal", "xterm", "rxvt"],
        }
        for bin in players[typ]:
            if find_executable(bin.split()[0]):
                return bin
        return default

        
    # http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
    def xdg(self, path="/streamtuner2"):
        home = os.environ.get("HOME", self.tmp)
        config = os.environ.get("XDG_CONFIG_HOME", os.environ.get("APPDATA", home+"/.config"))
        
        # storage dir







|
>













>







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
        config = meta.get("config", [])
        for opt in config:
            if ("name" in opt) and ("value" in opt) and (opt["name"] not in vars(self)):
                self.__dict__[opt["name"]] = opt["value"]

        # plugin state
        if module and module not in conf.plugins:
             conf.plugins[module] = meta.get("priority") in ("core", "builtin", "always", "default", "standard")


    # look at system binaries for standard audio players
    def find_player(self, typ="audio", default="xdg-open"):
        players = {
           "audio": ["audacious %g", "audacious2", "exaile %p", "xmms2", "banshee", "amarok %g", "clementine", "qmmp", "quodlibet", "aqualung", "mp3blaster %g", "vlc --one-instance %srv", "totem"],
           "video": ["parole", "umplayer", "xnoise", "gxine", "totem", "vlc --one-instance", "smplayer", "gnome-media-player", "xine", "bangarang"],
           "browser": ["opera", "midori", "sensible-browser"],
           "xterm": ["xfce4-terminal", "x-termina-emulator", "gnome-terminal", "xterm", "rxvt"],
        }
        for bin in players[typ]:
            if find_executable(bin.split()[0]):
                return bin
        return default

        
    # http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
    def xdg(self, path="/streamtuner2"):
        home = os.environ.get("HOME", self.tmp)
        config = os.environ.get("XDG_CONFIG_HOME", os.environ.get("APPDATA", home+"/.config"))
        
        # storage dir
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
    def update(self, with_new_data):
        for key,value in with_new_data.items():
            if type(value) == dict:
                self[key].update(value)
            else:
                self[key] = value
        # descends into sub-dicts instead of wiping them with subkeys


    # update old setting names
    def migrate(self):
        # 2.1.1
        if "audio/mp3" in self.play:
            self.play["audio/mpeg"] = self.play["audio/mp3"]
            del self.play["audio/mp3"]

         
    # check for existing filename in directory list
    def find_in_dirs(self, dirs, file):
        for d in dirs:
            if os.path.exists(d+"/"+file):
                return d+"/"+file


    # standard user account storage in ~/.netrc or less standard but contemporarily in ~/.config/netrc
    def netrc(self, varhosts=("shoutcast.com")):
        global netrc
        if not netrc:
            netrc = {}
            try:







>














>







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
    def update(self, with_new_data):
        for key,value in with_new_data.items():
            if type(value) == dict:
                self[key].update(value)
            else:
                self[key] = value
        # descends into sub-dicts instead of wiping them with subkeys


    # update old setting names
    def migrate(self):
        # 2.1.1
        if "audio/mp3" in self.play:
            self.play["audio/mpeg"] = self.play["audio/mp3"]
            del self.play["audio/mp3"]

         
    # check for existing filename in directory list
    def find_in_dirs(self, dirs, file):
        for d in dirs:
            if os.path.exists(d+"/"+file):
                return d+"/"+file


    # standard user account storage in ~/.netrc or less standard but contemporarily in ~/.config/netrc
    def netrc(self, varhosts=("shoutcast.com")):
        global netrc
        if not netrc:
            netrc = {}
            try:
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
            if server in netrc:
                return netrc[server]
        


# Retrieve content from install path or pyzip archive (alias for pkgutil.get_data)
#
def get_data(fn, decode=False, z=False):
    try:
        bin = pkgutil.get_data("config", fn)
        if z:
            bin = zlib.decompress(bin)
        if decode:
            return bin.decode("utf-8")
        else:
            return str(bin)
    except:
        pass


# Search through ./channels/ and get module basenames.
# (Reordering channel tabs is now done by uikit.apply_state.)
#
def module_list():

    # Should list plugins within zips as well as local paths
    ls = pkgutil.iter_modules([conf.share+"/channels", "channels"])
    return [name for loader,name,ispkg in ls]



# Plugin meta data extraction
#
# Extremely crude version for Python and streamtuner2 plugin usage.
# But can fetch from different sources:
#  · fn= to read from literal files, out of a .pyzip package
#  · src= to extract from pre-read script code
#  · module= utilizes pkgutil to read 
#  · frame= automatically extract comment header from caller
#
def plugin_meta(fn=None, src=None, module=None, frame=1):

    # try via pkgutil first
    if module:
       fn = module
       src = pkgutil.get_data("channels", fn+".py")

    # get source directly from caller
    elif not src and not fn:
        module = inspect.getmodule(sys._getframe(frame))
        fn = inspect.getsourcefile(module)
        src = inspect.getcomments(module)








|

|













|


|













|




|







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
            if server in netrc:
                return netrc[server]
        


# Retrieve content from install path or pyzip archive (alias for pkgutil.get_data)
#
def get_data(fn, decode=False, z=False, file_base="config"):
    try:
        bin = pkgutil.get_data(file_base, fn)
        if z:
            bin = zlib.decompress(bin)
        if decode:
            return bin.decode("utf-8")
        else:
            return str(bin)
    except:
        pass


# Search through ./channels/ and get module basenames.
# (Reordering channel tabs is now done by uikit.apply_state.)
#
def module_list(plugin_base="channels"):

    # Should list plugins within zips as well as local paths
    ls = pkgutil.iter_modules([plugin_base, conf.share+"/"+plugin_base, conf.dir+"/plugins"])
    return [name for loader,name,ispkg in ls]



# Plugin meta data extraction
#
# Extremely crude version for Python and streamtuner2 plugin usage.
# But can fetch from different sources:
#  · fn= to read from literal files, out of a .pyzip package
#  · src= to extract from pre-read script code
#  · module= utilizes pkgutil to read 
#  · frame= automatically extract comment header from caller
#
def plugin_meta(fn=None, src=None, module=None, frame=1, plugin_base="channels"):

    # try via pkgutil first
    if module:
       fn = module
       src = pkgutil.get_data(plugin_base, fn+".py")

    # get source directly from caller
    elif not src and not fn:
        module = inspect.getmodule(sys._getframe(frame))
        fn = inspect.getsourcefile(module)
        src = inspect.getcomments(module)

Modified st2.py from [a24c95cdd7] to [d4a3f5a23c].

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# config:  
#   { type: env, name: http_proxy, description: proxy for HTTP access }
#   { type: env, name: XDG_CONFIG_HOME, description: relocates user .config subdirectory }
# category: sound
# depends: pygtk | gi, threading, requests, pyquery, lxml
# id: streamtuner2
# pack: *.py, gtk3.xml.zlib, bin, channels/__init__.py, bundle/*.py, CREDITS, help/index.page,
#   streamtuner2.desktop=/usr/share/applications/, README=/usr/share/doc/streamtuner2/,
#   help/streamtuner2.1=/usr/share/man/man1/, NEWS.gz=/usr/share/doc/streamtuner2/changelog.gz,
#   logo.png=/usr/share/pixmaps/streamtuner2.png
# architecture: all
#
# Streamtuner2 is a GUI for browsing internet radio directories, music
# collections, and video services - grouped by genres or categories.
# It runs your preferred audio player, and streamripper for recording.
#
# It's an independent rewrite of streamtuner1. Being written in Python,







<
|
|







13
14
15
16
17
18
19

20
21
22
23
24
25
26
27
28
# config:  
#   { type: env, name: http_proxy, description: proxy for HTTP access }
#   { type: env, name: XDG_CONFIG_HOME, description: relocates user .config subdirectory }
# category: sound
# depends: pygtk | gi, threading, requests, pyquery, lxml
# id: streamtuner2
# pack: *.py, gtk3.xml.zlib, bin, channels/__init__.py, bundle/*.py, CREDITS, help/index.page,

#   streamtuner2.desktop, README, help/streamtuner2.1=/usr/share/man/man1/,
#   NEWS.gz=/usr/share/doc/streamtuner2/changelog.gz, logo.png=/usr/share/pixmaps/streamtuner2.png
# architecture: all
#
# Streamtuner2 is a GUI for browsing internet radio directories, music
# collections, and video services - grouped by genres or categories.
# It runs your preferred audio player, and streamripper for recording.
#
# It's an independent rewrite of streamtuner1. Being written in Python,
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


    # load plugins from /usr/share/streamtuner2/channels/
    def load_plugin_channels(self):

        # initialize plugin modules (pre-ordered)
        ls = module_list()
        for module in ls:
            gui_startup(4/20.0 + 13.5/20.0 * float(ls.index(module))/len(ls), "loading module "+module)





            # skip module if disabled
            if conf.plugins.get(module, 1) == False:
                __print__(dbg.STAT, "disabled plugin:", module)
                continue
            # or if it's a built-in (already imported)
            elif module in self.features or module in self.channels:
                continue
            
            # load plugin
            try:
                plugin = __import__("channels."+module, globals(), None, [""])
                #print [name for name,c in inspect.getmembers(plugin) if inspect.isclass(c)]
                plugin_class = plugin.__dict__[module]
                plugin_obj = plugin_class(parent=self)

                # add to .channels{}
                if issubclass(plugin_class, channels.GenericChannel):
                    self.channels[module] = plugin_obj
                # or .features{} for other plugin types
                else:
                    self.features[module] = plugin_obj
                
            except Exception as e:
                __print__(dbg.INIT, "load_plugin_channels: error initializing:", module, ", exception:")
                traceback.print_exc()


    # store window/widget states (sizes, selections, etc.)
    def app_state(self, widget):
        # gtk widget states
        widgetnames = ["win_streamtuner2", "toolbar", "notebook_channels", ] \







|
|

>
>
>
>

|
|


|




|

|




|


|


|







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


    # load plugins from /usr/share/streamtuner2/channels/
    def load_plugin_channels(self):

        # initialize plugin modules (pre-ordered)
        ls = module_list()
        for name in ls:
            gui_startup(4/20.0 + 13.5/20.0 * float(ls.index(name))/len(ls), "loading module "+name)

            # load defaults on first startup
            if not name in conf.plugins:
                conf.add_plugin_defaults(plugin_meta(module=name), name)
            
            # skip module if disabled
            if conf.plugins.get(name, 1) == False:
                __print__(dbg.STAT, "disabled plugin:", name)
                continue
            # or if it's a built-in (already imported)
            elif name in self.features or name in self.channels:
                continue
            
            # load plugin
            try:
                plugin = __import__("channels."+name, globals(), None, [""])
                #print [name for name,c in inspect.getmembers(plugin) if inspect.isclass(c)]
                plugin_class = plugin.__dict__[name]
                plugin_obj = plugin_class(parent=self)

                # add to .channels{}
                if issubclass(plugin_class, channels.GenericChannel):
                    self.channels[name] = plugin_obj
                # or .features{} for other plugin types
                else:
                    self.features[name] = plugin_obj
                
            except Exception as e:
                __print__(dbg.INIT, "load_plugin_channels: error initializing:", name, ", exception:")
                traceback.print_exc()


    # store window/widget states (sizes, selections, etc.)
    def app_state(self, widget):
        # gtk widget states
        widgetnames = ["win_streamtuner2", "toolbar", "notebook_channels", ] \