This repository has been archived by the owner on Aug 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
iview-gtk
executable file
·394 lines (316 loc) · 11 KB
/
iview-gtk
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
#!/usr/bin/env python
import iview.config
import iview.comm
import iview.fetch
import gtk
import gobject
import threading
import sys
import re
import urllib2
cr = '\015' # carriage return
num_windows = 0
def add_window():
global num_windows
num_windows += 1
def del_window(widget=None):
global num_windows
num_windows -= 1
if num_windows == 0:
gtk.main_quit()
def readupto(fh, upto):
""" Reads up to (and not including) the character
specified by arg 'upto'.
"""
result = ''
while True:
char = fh.read(1)
if char == '' or char == upto:
return result
else:
result = ''.join((result,char))
class DownloadWorker(threading.Thread):
def __init__(self, parent):
threading.Thread.__init__(self)
self.parent = parent
def run(self):
progress_pattern = re.compile(r'\d+\.\d%')
size_pattern = re.compile(r'\d+\.\d+ kB', re.IGNORECASE)
rate = 0
self.parent.progress.set_text('')
while True:
r = readupto(self.parent.job.stderr, cr)
if r == '': # i.e. EOF, the process has quit
break
progress_search = progress_pattern.search(r)
size_search = size_pattern.search(r)
if progress_search is not None:
p = float(progress_search.group()[:-1]) / 100. # [:-1] shaves the % off the end
gtk.gdk.threads_enter()
self.parent.progress.set_fraction(p)
self.parent.set_title("(%0.1f%%) %s" %(p*100, self.parent.my_title))
gtk.gdk.threads_leave()
if size_search is not None:
gtk.gdk.threads_enter()
self.parent.labels[2][1] \
.set_text('%.1f' % (float(size_search.group()[:-3]) / 1024.) + ' MB')
gtk.gdk.threads_leave()
if progress_search is None and size_search is None:
print 'Backend debug:\t' + r
returncode = self.parent.job.wait()
gtk.gdk.threads_enter()
if returncode == 0: # EXIT_SUCCESS
self.parent.progress.set_fraction(1.)
self.parent.progress.set_text('Download finished')
self.parent.set_title(self.parent.my_title)
self.parent.close_btn.set_label(gtk.STOCK_CLOSE)
self.parent.pause_btn.hide()
self.parent.resume_btn.hide()
else:
print 'Backend aborted with code %d (either it crashed, or you paused it)' % returncode
if returncode == 1: # connection timeout results in code 1
self.parent.progress.set_text('Download failed')
self.parent.pause_btn.hide()
self.parent.resume_btn.show()
gtk.gdk.threads_leave()
class Downloader(gtk.Window):
def __init__(self, url, title=None, dest_file=None):
self.url = url
self.dest_file = dest_file
gtk.Window.__init__(self)
self.connect('destroy', del_window)
self.connect('destroy', self.on_destroy)
add_window()
if title is None:
title = url
self.my_title = dest_file.split("/")[-1]
self.set_title(title)
self.set_resizable(False)
self.set_default_size(400,0)
self.set_border_width(10)
xpadding = 5
ypadding = 2
table = gtk.Table(3, 3, homogeneous=False)
self.labels = []
for i in range(3):
label_term = gtk.Label()
label_term.set_alignment(0., 0.5)
label_desc = gtk.Label()
label_desc.set_alignment(1., 0.5)
self.labels.append([label_term, label_desc])
table.attach(label_term, 0,1, i,i+1, xpadding=xpadding, ypadding=ypadding)
table.attach(label_desc, 1,2, i,i+1, xpadding=xpadding, ypadding=ypadding)
self.labels[0][0].set_text('Name')
self.labels[0][1].set_text(title)
self.labels[1][0].set_text('Filename')
self.labels[1][1].set_text(dest_file.split('/')[-1])
self.labels[2][0].set_text('Download size')
self.labels[2][1].set_text('0.0 MB')
self.progress = gtk.ProgressBar()
table.attach(self.progress, 0,2, 3,4, xpadding=xpadding, ypadding=8)
bb = gtk.HButtonBox()
bb.set_layout(gtk.BUTTONBOX_END)
self.pause_btn = gtk.Button('Pause')
self.pause_btn.connect('clicked', self.pause_download)
self.resume_btn = gtk.Button('Resume')
self.resume_btn.connect('clicked', self.start_download)
self.close_btn = gtk.Button(stock=gtk.STOCK_STOP)
self.close_btn.connect('clicked', self.destroy)
bb.pack_end(self.pause_btn)
bb.pack_end(self.resume_btn)
bb.pack_end(self.close_btn)
vbox = gtk.VBox()
vbox.pack_start(table)
vbox.pack_start(bb, expand=False)
self.add(vbox)
self.show_all()
self.start_download() # kick off the DownloadWorker thread
def start_download(self, widget=None):
self.resume_btn.hide()
self.pause_btn.show()
self.job = iview.fetch.fetch_program(self.url, dest_file=self.dest_file)
if not self.job:
message = gtk.MessageDialog(
parent=None,
type=gtk.MESSAGE_ERROR,
buttons=gtk.BUTTONS_CLOSE)
message.set_markup('<big><b>Download backend failed</b></big>\n\n' \
'Either the download backend in question failed for some reason, or one could not be found with which to download iView programmes. Please check the README file for instructions on setting this up.')
message.run()
message.destroy()
return
self.download_worker = DownloadWorker(self).start()
def pause_download(self, widget=None):
self.job.terminate()
self.pause_btn.hide()
self.resume_btn.show()
def on_destroy(self, widget=None):
try:
self.job.terminate()
except OSError: # this would trigger if it was
pass # already killed for some reason
def destroy(self, null_param=None):
""" Allow destroy() to be called with a parameter, thus allowing it to
be attached to the "clicked" event of a button.
"""
gtk.Window.destroy(self)
def on_download_clicked(widget, data=None):
global window, save_location
model, selected_iter = listing.get_selection().get_selected()
if selected_iter is None:
return
item = model.get(selected_iter, 0, 2)
if item[1] is None:
return
save_dialog = gtk.FileChooserDialog('Save Video',
parent=window,
action=gtk.FILE_CHOOSER_ACTION_SAVE,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE, gtk.RESPONSE_OK))
try:
save_dialog.set_current_folder(save_location)
except NameError: # if we haven't set a save_location yet
pass
# build a nice filename
# could use this ugly version instead:
# save_dialog.set_current_name(iview.fetch.get_filename(item[1]))
# TODO: This may hamper (future) GTK+-based subtitle downloading unless
# this is made into a shared function
program = model.get(model.iter_parent(selected_iter), 0, 1)[0]
title = item[0]
ext = 'flv' # ABC always provides us with an FLV container
# for specials that title == program, just use program.ext
if program == title:
filename = "%s.%s" %(program, ext)
else:
filename = "%s - %s.%s" %(program, title, ext)
# strip invalid filename characters < > : " / \ | ? *
filename = re.sub('[\<\>\:\"\/\\\|\?\*]', '-', filename)
save_dialog.set_current_name(filename)
save_dialog.set_local_only(False) # allow saving to, e.g., SFTP
save_response = save_dialog.run()
save_dialog.hide()
if save_response == gtk.RESPONSE_OK:
dest_file = save_dialog.get_filename()
save_location = save_dialog.get_current_folder()
Downloader(item[1], item[0], dest_file)
save_dialog.destroy()
def on_listing_cursor_changed(widget):
global description
description.set_text('')
download_btn.set_sensitive(False)
model, selected_iter = listing.get_selection().get_selected()
if selected_iter is None:
return
item = model.get(selected_iter, 0, 2, 3)
if item[1] is None or item[2] is None:
return
description.set_text(item[2])
download_btn.set_sensitive(True)
def load_programme():
global programme
for series in iview.comm.get_index():
series_iter = programme.append(None, [series['title'], series['id'], None, None])
programme.append(series_iter, ['Loading...', None, None, None])
def load_series_items(widget, iter, path):
model = widget.get_model()
child = model.iter_children(iter)
if model.get(child, 2)[0] is not None:
# This is not a "Loading..." item, so we've already fetched this.
# Better pull out.
return
series_id = model.get(iter, 1)[0]
items = iview.comm.get_series_items(series_id)
for item in items:
model.append(iter, [
item['title'],
None,
item['url'],
item['description'],
])
model.remove(child)
def about(widget, data=None):
d = gtk.AboutDialog()
d.set_version(iview.config.version)
d.set_copyright('Copyright \302\251 2009-2010 by Jeremy Visser')
d.set_license("""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 3 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
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, see <http://www.gnu.org/licenses/>.""")
d.run()
d.destroy()
gtk.gdk.threads_init()
window = gtk.Window()
window.set_title('iView')
window.set_default_size(400,450)
window.set_border_width(5)
window.connect('destroy', del_window)
add_window()
vbox = gtk.VBox()
programme_label = gtk.Label()
programme_label.set_markup('<big><b>iView Programme</b></big>')
vbox.pack_start(programme_label, expand=False)
listing_scroller = gtk.ScrolledWindow()
listing_scroller.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
listing_scroller.set_shadow_type(gtk.SHADOW_IN)
# name, id, url, description
programme = gtk.TreeStore(str, str, str, str)
listing = gtk.TreeView(programme)
listing.set_headers_visible(False)
listing.get_selection().set_mode(gtk.SELECTION_SINGLE)
listing.connect('cursor-changed', on_listing_cursor_changed)
listing.connect('row-expanded', load_series_items)
tvcolumn = gtk.TreeViewColumn('Program Name')
listing.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 0)
listing_scroller.set_border_width(5)
listing_scroller.add(listing)
vbox.pack_start(listing_scroller)
description = gtk.Label()
description.set_line_wrap(True)
vbox.pack_start(description, expand=False)
bb = gtk.HButtonBox()
bb.set_layout(gtk.BUTTONBOX_EDGE)
bb.set_border_width(5)
about_btn = gtk.Button(stock=gtk.STOCK_ABOUT)
about_btn.connect('clicked', about)
download_btn = gtk.Button('Download')
download_btn.set_sensitive(False)
download_btn.connect('clicked', on_download_clicked)
bb.pack_start(about_btn)
bb.pack_start(download_btn)
vbox.pack_start(bb, expand=False)
window.add(vbox)
try:
if sys.argv[1] in ('-c', '--cache'):
iview.comm.cache = True
except IndexError:
pass
try:
iview.comm.get_config()
load_programme()
except urllib2.HTTPError, error:
message = gtk.MessageDialog(
parent=window,
type=gtk.MESSAGE_ERROR,
buttons=gtk.BUTTONS_CLOSE)
message.set_markup('<big><b>Download failed</b></big>\n\n' \
'Could not retrieve an important configuration file from iView.' \
' Please make sure you are connected to the Internet.\n\n' \
'If iView works fine in your web browser, then the iView API' \
' has most likely changed. Try and find an updated version of this'
' program, or contact the author.\n\n' \
'URL: %s' % error.url)
message.run()
gtk.main_quit()
sys.exit(1)
window.show_all()
gtk.main()