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

โŒˆโŒ‹ โŽ‡ branch:  streamtuner2


Check-in [c860f8c6cc]

Overview
Comment:Enable record options getting applied. Added wget and more fPls options. Separate out row,*k,**kw params from overriden action.record() call. Simplify and rearrange gtk callbacks.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: c860f8c6cc9431c33b72177ab2fe6b26338bb8ad
User & Date: mario on 2017-01-22 22:15:24
Other Links: manifest | tags
Context
2017-01-25
19:14
Added pip -U for mutagen; typo fixes. check-in: ccc551cb58 user: Oliver tags: trunk
2017-01-22
22:15
Enable record options getting applied. Added wget and more fPls options. Separate out row,*k,**kw params from overriden action.record() call. Simplify and rearrange gtk callbacks. check-in: c860f8c6cc user: mario tags: trunk
16:46
new plugin: recording options which hijacks the record button, provides streamripper/fPls/youtube-dl specific command-line flags in a GUI. check-in: 64de51eb48 user: mario tags: trunk
Changes

Modified contrib/recordflags.py from [6b7d53ce01] to [cd11ba7686].

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
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




-
+
+









-
+







+
+
+
+

-
-


-
+
-


















-
+
+
+







-
+

-
+






-
+


-
-
+
+

-
-
+
+


-
+



-
+








-
+

+
+
+
+
+
+
+
-
+

-
-
-
-
-
-
-
-
+




















-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+








+
+
+
+
+



-
+










+
+







-

-














+
+
+
+









-
+


-
-
+
+
+
+
+



-
-
-


-



+







+
+
+
+
+
-
-
+
+
-
-
+
-
-
-
-
+
+


-
+




-
-







# encoding: utf-8
# api: streamtuner2
# title: Recording options
# description: Allows to set streamripper/fIcy options before recording
# version: 0.5
# version: 0.7
# depends: streamtuner2 > 2.2.0
# conflicts: continuous_record
# priority: optional
# config:
#    { name: recordflags_auto, type: bool, value: 1, description: Apply options automatically once saved. }
#    { name: recordflags_row, type: select, value: record_flags, select: "record_flags|extras", description: Station field for saved options. }
#    { name: recordflags_dir, type: str, value: "", description: Default output directory. }
# type: handler
# category: ui
#
# Hijacks the โœช record button, presents an option dialog to set various
# Hijacks the โ— record button, presents an option dialog to set various
# streamripper options. Allows to set an output directory or single-file
# recording for example.
#
# Reuses the known option scheme from the config window. Which is perhaps
# less pretty than a custom dialog, but allows to show options for different
# download/recording tools.
#
# Note that predefining -flags in the Apps/Recording config table might
# conflict with per-stream options. In particular avoid a -d directory
# default for streamripper; and use this pluginsยด option instead.
#
# ToDo:
#  โ†’ detect different record apps (fPls, wget, youtube-dl, etc.)
#  โ†’ implement fPls options etc.
#  โ†’ override main.record() instead of action.record
#  โ†’ eventually strip defaults such as `-d ../dir` from conf.record;
#    using action append= param now, thus no rewriting of assoc dict;
#    using action append= param now, thus no rewriting of assoc dict
#    so this should rather go into documenation
#


import re
import os
import copy
from config import *
from channels import *
from uikit import *
import action
from compat2and3 import *


# hook record button / menu / action
class recordflags (FeaturePlugin):

    # settings
    cfg_widget_pfx = "recordoptions_config_"
    widgets = {}    
    widgets = {}
    
    # available options per recording tool
    flag_meta = {
        "streamripper": {
            "title": "streamripper",
            "priority": "required",
            "type": "app",
            "category": "recording",
            "version": "1.64.6",
            "description": "Standard radio stream recording app",
            "description": "Standard radio/stream recording tool",
            "config": [
                { "name": "A",	"arg": "-A",	"type": "bool",	"description": "โž–๐˜ผ Don't write individual tracks/MP3s. And whatever..... fill text", "value": False },
                { "name": "A",	"arg": "-A",	"type": "bool",	"description": "โž–๐˜ผ Don't split individual tracks/MP3s", "value": False },
                { "name": "a",	"arg": "-a",	"type": "str",	"description": "โž–๐™– Single MP3 output file", "value": "" },
                { "name": "dir", "arg": "-d",	"type": "str",	"description": "โž–๐™™ Destination directory", "value": "" },
                { "name": "D",	"arg": "-D",	"type": "str",	"description": "โž–๐˜ฟ Filename pattern", "value": "" },
                { "name": "s",	"arg": "-s",	"type": "bool",	"description": "โž–๐™จ No subdirectories for each stream", "value": False },
                { "name": "t",	"arg": "-t",	"type": "bool",	"description": "โž–๐™ฉ Never overwrite incomplete tracks", "value": False },
                { "name": "T",	"arg": "-T",	"type": "bool",	"description": "โž–๐™ Truncate duplicated incompletes", "value": False },
                { "name": "o",	"arg": "-o",	"type": "select",	"description": "โž–๐™จ Incomplete track overwriting", "select": "|always|never|larger|version", "value": "" },
                { "name": "o",	"arg": "-o",	"type": "select",	"description": "โž–๐™ค Incomplete track overwriting", "select": "|always|never|larger|version", "value": "" },
                { "name": "l",	"arg": "-l",	"type": "int",	"description": "โž–๐™ก Seconds to record", "value": 3600 },
                { "name": "M",	"arg": "-M",	"type": "int",	"description": "โž–๐™ˆ Max megabytes to record", "value": 16 },
                { "name": "xs2", "arg": "--xs2", "type": "bool", "description": "โž–โž–๐™ญ๐™จ๐Ÿฎ new pause detection", "value": False },
                { "name": "xsnone", "arg": "--xs-none", "type": "bool", "description": "Dont't search for/split on track silence", "value": False },
                { "name": "xs2", "arg": "--xs2", "type": "bool", "description": "โž–โž–๐™ญ๐™จ๐Ÿฎ New pause detection algorithm", "value": False },
                { "name": "xsnone", "arg": "--xs-none", "type": "bool", "description": "โž–โž–๐™ญ๐™จโž–๐™ฃ๐™ค๐™ฃ๐™š No silence splitting", "value": False },
                { "name": "i",	"arg": "-i",	"type": "bool", "description": "โž–๐™ž Don't add any ID3 tags", "value": False },
                { "name": "id3v1", "arg": "--with-id32v1", "type": "bool", "description": "Add ID3v1 tags", "value": False },
                { "name": "noid3v2", "arg": "--without-id32v2", "type": "bool", "description": "Omit ID3v2 tags", "value": False },
                { "name": "id3v1", "arg": "--with-id3v1", "type": "bool", "description": "โž–โž–๐™ฌ๐™ž๐™ฉ๐™โž–๐™ž๐™™๐Ÿฏ๐™ซ๐Ÿญ Add ID3v1 tags", "value": False },
                { "name": "noid3v2", "arg": "--without-id3v2", "type": "bool", "description": "โž–โž–๐™ฌ๐™ž๐™ฉ๐™๐™ค๐™ช๐™ฉโž–๐™ž๐™™๐Ÿฏ๐™ซ๐Ÿฎ Omit ID3v2 tags", "value": False },
                { "name": "cs_fs", "arg": "--codeset-filesys", "type": "str", "description": "Charset filesystem", "value": "" },
                { "name": "cs_id3", "arg": "--codeset-id3", "type": "str", "description": "Charset ID3 tags", "value": "" },
                { "name": "u",	"arg": "-u",	"type": "str", "description": "โž–๐™ช Useragent to send", "value": "" },
                { "name": "u",	"arg": "-u",	"type": "str", "description": "โž–๐™ช User-agent (browser id)", "value": "" },
                { "name": "p",	"arg": "-p",	"type": "str", "description": "โž–๐™ฅ Url for HTTP proxy to use", "value": "" },
                { "name": "r",	"arg": "-r",	"type": "str", "description": "โž–๐™ง Relay server 'localhost:8000'", "value": "" },
                { "name": "m",	"arg": "-m",	"type": "int", "description": "โž–๐™ข Timeout for stalled connection", "value": 15 },
                { "name": "debug", "arg": "--debug", "type": "bool", "description": "โž–โž–๐™™๐™š๐™—๐™ช๐™œ", "value": False },
                { "name": "debug", "arg": "--debug", "type": "bool", "description": "โž–โž–๐™™๐™š๐™—๐™ช๐™œ Extra verbosity", "value": False },
            ]
        },
        "fPls": {
            "title": "fPls/fIcy",
            "priority": "required",
            "type": "app",
            "category": "recording",
            "version": "1.0.19",
            "description": "Alternative recording tool",
            "description": "Alternative station recording tool",
            "config": [
                { "name": "max", "arg": "-M", "type": "int", "description": "โž–๐™ˆ Maximum cumulative playing time", "value": 0 },
                { "name": "loop", "arg": "-L", "type": "int", "description": "โž–๐™‡ Maximum playlist loops", "value": 0 },
                { "name": "retry", "arg": "-R", "type": "int", "description": "โž–๐™ Maximum per-stream retries", "value": 0 },
                { "name": "redir", "arg": "-l", "type": "int", "description": "โž–๐™ก Redirect follow limit", "value": 0 },
                { "name": "fail", "arg": "-T", "type": "int", "description": "โž–๐™ Wait time after failure", "value": 0 },
                { "name": "daemon", "arg": "-i", "type": "int", "description": "โž–๐™ž Max network idle seconds", "value": 0 },
                { "name": "authfn", "arg": "-a", "type": "str", "description": "โž–๐™› HTTP auth file (user:pass)", "value": "" },
                { "name": "verbose", "arg": "โž–๐™ซ", "type": "bool", "description": "โž–๐™ซ Verbose mode", "value": False },
                { "name": "verbose", "arg": "-v", "type": "bool", "description": "โž–๐™ซ Verbose mode", "value": False },
                { "name": "daemon", "arg": "-d", "type": "str", "description": "โž–๐™™ Daemon mode: log file", "value": "" },
                #  -L max	Maximum playlist loops
                #  -M time	Maximum cumulative playing time
                #  -P path	Specify fIcy executable name/path
                #  -R max	Maximum per-stream retries
                #  -T time	Wait the specified time after each failure
                #  -a file	Provide HTTP credentials (user:pass file)
                #  -i time	Maximum network idle time
                #  -l num	Redirect follow limit
                { "name": "ficy", "arg": "-P", "type": "str", "description": "โž–๐™‹ Path to fIcy", "value": "" },
            ]
        },
        "youtube-dl": {
            "title": "youtuble-dl",
            "priority": "required",
            "type": "app",
            "category": "download",
            "version": "2017.02.11.3",
            "description": "Youtube downloader",
            "config": [
                { "name": "freeformats", "arg": "--prefer-free-formats", "type": "bool", "description": "Prefer free audio formats", "value": False },
                { "name": "format", "arg": "-f", "type": "select", "select": "=any|b=best|249=webm audio only DASH|250=webm audio only DASH|140=m4a audio only DASH|171=webm audio only DASH|251=webm audio only DASH|278=webm 256x144 DASH|160=mp4 256x144 DASH|242=webm 426x240 DASH|133=mp4 426x240 DASH|243=webm 640x360 DASH|134=mp4 640x360 DASH|244=webm 854x480 DASH|135=mp4 854x480 DASH|247=webm 1280x720 DASH|136=mp4 1280x720 DASH|248=webm 1920x1080 DASH|137=mp4 1920x1080 DASH|17=3gp 176x144 small|36=3gp 320x180 small|43=webm 640x360 medium|18=mp4 640x360 medium|22=mp4 1280x720 hd720", "description": "โž–๐™› Format", "value": "b" },
                { "name": "c", "arg": "-c", "type": "bool", "description": "โž–๐™˜ Continue partial downloads ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ", "value": True },
                { "name": "netrc", "arg": "-n", "type": "bool", "description": "โž–๐™ฃ Use .netrc for auth/login", "value": False },
                { "name": "ignore", "arg": "-i", "type": "bool", "description": "โž–๐™ž Ignore errors", "value": False },
                { "name": "proxy", "arg": "--proxy", "type": "str", "description": "โž–๐™ฅ Proxy", "value": "" },
                { "name": "verbose", "arg": "-v", "type": "bool", "description": "โž–๐™ซ Verbose mode", "value": False },
                { "name": "ipv4", "arg": "-4", "type": "bool", "description": "โž–๐Ÿฐ Use IPv4", "value": False },
                { "name": "ipv6", "arg": "-6", "type": "bool", "description": "โž–๐Ÿฒ Use IPv6", "value": False },
            ]
        }
        },
        "wget": {
            "title": "wget",
            "priority": "required",
            "type": "app",
            "category": "download",
            "version": "1.15",
            "description": "HTTP download utility",
            "config": [
                { "name": "c", "arg": "-c", "type": "bool", "description": "โž–๐™˜ Continue partial downloads.", "value": True },
                { "name":"nc", "arg":"-nc", "type": "bool", "description": "โž–๐™ฃ๐™˜ No-clobber, keep existing files.", "value": False },
                { "name": "N", "arg": "-N", "type": "bool", "description": "โž–๐™‰ Only fetch newer files", "value": False },
                { "name": "O", "arg": "-O", "type": "str",  "description": "โž–๐™Š Output to file", "value": "" },
                { "name": "v", "arg": "-v", "type": "bool", "description": "โž–๐™ซ Verbose mode", "value": False },
                { "name": "S", "arg": "-S", "type": "bool", "description": "โž–๐™Ž Show response headers", "value": False },
                { "name": "U", "arg": "-U", "type": "str",  "description": "โž–๐™ Useragent to send", "value": "" },
            ]
        },
    }

    # current selection (dialog only runs once anyway, so we can keep flags in same object)
    app = "streamripper"
    argmap = {}    # "--xs2" => "xs2"
    namemap = {}   # "xs2" => "--xs2"
    typemap = {}   # "xs2" => "bool"
    defmap = {}    # "opt" => "default"
    
    # parameters from current action.record() call
    k = []     # avoids having to pass them around
    kw = {}    # simplifies gtk callbacks
    row = {}   # only one active instance anyway


    # hooks for user interface/handlers
    def init2(self, parent, *a, **kw):
    def init2(self, parent, *k, **kw):
        # TEMPORARY WORKAROUND: swap action.record()
        action.record = self.action_record
        # BETTER APPROACH: hook record button
        #parent.on_record_clicked = self.show_window

        # add menu entry (for simple triv#1 option)
        uikit.add_menu([parent.streammenu], "Set single MP3 record -A flag", self.set_cont)

        # default widget actions
        parent.win_recordoptions.connect("delete-event", self.hide)
        parent.recordoptions_go.connect("clicked", self.do_record)
        parent.recordoptions_save.connect("clicked", self.save_only)
        parent.recordoptions_eventbox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color("#442211"))

        # shortcuts
        self.add_plg = parent.configwin.add_plg           # create _cfg widgets
        self.load_config = parent.configwin.load_config   # populate _cfg widgets
        self.save_config = parent.configwin.save_config   # save from _cfg widgets
        self.recordoptions_cfg = parent.recordoptions_cfg # our vbox widget
        self.map_app_args(self.app)

    
    # prepares a few shortcuts
    def map_app_args(self, app):
        config = self.flag_meta[app]["config"]
        self.argmap = { row["arg"]: row["name"] for row in config if row.get("arg") }
        self.namemap = dict(zip(self.argmap.values(), self.argmap.keys()))
        self.typemap = { row["name"]: row["type"] for row in config if row.get("type") }
        self.defmap = { row["name"]: row["value"] for row in config if row.get("value") is not None }
        log.CONF(self.defmap)


    # triv #1 menu option โ†’ only saves `-A` flag to row["recordflags"]
    def set_cont(self, row):
        row[conf.recordflags_row] = "-A"
        
    # override GtkWindow.destroy/delete-event
    def hide(self, *x):
        self.parent.win_recordoptions.hide()
        return True
        
    # hook for action.record
    def action_record(self, row={}, *k, **kw):
        kw["assoc"] = conf.record
        # default
        if not self.can_handle(row):
            return action.run_fmt_url(row, *k, **kw)
        # use saved settings
        if conf.recordflags_auto and row.get(conf.recordflags_row):
            kw["append"] = " " + row[cont.recordflags_row]
            kw["append"] = row[conf.recordflags_row].strip()
            return action.run_fmt_url(row, *k, **kw)
        # else bring up win_recordoptions
        else:    
            self.show_dialog(row, *k, **kw)  # (row, audioformat, source, assoc, append=append)
        else:
            self.k = k    # stash away args: audioformat, source, assoc, append
            self.kw = kw
            self.row = row
            self.show_dialog(self.row)

    # only handle audio/* streamripper formats
    def can_handle(self, row):
        # check for general MIME types
        #if not row.get("format") in ("audio/mpeg", "audio/aac", "audio/ogg"):
        #    return False
        # search for configured (flag_meta) apps in conf.record["audio/*"] dict
        rx_apps = "\\b(?i)(" + ("|".join(self.flag_meta.keys())) + ")\\b"
        #print rx_apps
        cmd = action.mime_app(row.get("format", "audio/*"), conf.record)
        match = re.findall(rx_apps, cmd or "")
        log.PROC(cmd)
        # if both mime matched, and cmd in supported apps:
        if cmd and match:
            log.STAT(match)
            self.app = match[0]
            self.map_app_args(self.app)
            return True
        return False

    # store current dialog settings into row[], invoked by [save] button
    def save_only(self, *x):
        self.row[conf.recordflags_row] = self.args_from_configwin()
        self.parent.channel().save()

    # overriden handler
    def do_record(self, row, audioformat="audio/mpeg", source="href", assoc={}, append=None):
    # overriden handler, chains to actual recording, invoked by [record] button
    def do_record(self, *x):
        self.hide()
        append = self.args_from_configwin()
        self.kw["append"] = self.args_from_configwin().strip()
        #print append
        log.EXEC(action.run_fmt_url, row, audioformat, source, assoc or conf.record, append)
        #action.run_fmt_url(row, audioformat, source, assoc, append=append)

        action.run_fmt_url(self.row, *self.k, **self.kw)
        self.hide()

    # option window
    def show_dialog(self, row, *k, **kw):
    def show_dialog(self, row):
        p = self.parent
        # set labels, connect buttons
        p.recordoptions_title.set_text(row["title"][0:50])
        p.recordoptions_url.set_text(row["url"][0:50])
        p.recordoptions_go.connect("clicked", lambda *x: self.do_record(row, *k, **kw))
        p.recordoptions_save.connect("clicked", lambda *x: self.save_only(row, *k, **kw))
        # add option widgets
        self.load_config_widgets(row, self.app, p)
        # show window
        p.win_recordoptions.show()

    # Put config widgets into recordoptions_cfg vbox
    def add_flag(self, id=None, w=None, label=None, color=None, image=None, align=5):
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
291
292
293
294
295
296
297

298
299
300
301
302
303
304


















-
+






-
-
-
-
-
-
-
-
-
-
-
        return r

    #-- convert { name=>value, .... } dict into "--arg str"
    def args_from_configdict(self, loaded_config):
        s = ""
        for name, val in loaded_config.items():
            default = str(self.defmap.get(name))
            if val in (False, None, "", default):
            if val in (False, None, "", 0, "0", default):
                continue
            arg = self.namemap[name]
            s = s + " " + arg
            if isinstance(val, (str, unicode)): # type == "bool" check here(...)
                s = s + " " + val
        return s

    # store current dialog settings into row[]
    def save_only(self, row, *k, **kw):
        row[conf.recordflags_row] = self.args_from_configwin()
        self.parent.channel().save()

    # override GtkWindow.destroy/delete-event
    def hide(self, *x):
        self.parent.win_recordoptions.hide()
        return True