-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtelegram_source.py
563 lines (457 loc) · 19.7 KB
/
telegram_source.py
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
# rhythmbox-telegram
# Copyright (C) 2023-2025 Andrey Izman <[email protected]>
#
# 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/>.
import rb
from gi.repository import RB
from gi.repository import GObject, Gtk, Gio, Gdk, GLib
from common import to_location, get_location_data, empty_cb, SingletonMeta, get_first_artist, get_entry_location
from common import get_location_audio_id, pretty_file_size
from common import file_uri, get_entry_state, set_entry_state
from loader import PlaylistLoader
from storage import Audio
from account import KEY_RATING_COLUMN, KEY_DATE_ADDED_COLUMN, KEY_FILE_SIZE_COLUMN, KEY_AUDIO_FORMAT_COLUMN
import gettext
gettext.install('rhythmbox', RB.locale_dir())
class FormatColumn:
def __init__(self, source):
self.source = source
entry_view = source.get_entry_view()
column = Gtk.TreeViewColumn()
renderer = Gtk.CellRendererText()
column.set_title(_("Format"))
column.set_cell_data_func(renderer, self.data_func, None) # noqa
column.pack_start(renderer, expand=False)
column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
entry_view.set_fixed_column_width(column, renderer, ["mp3", "flac"])
column.set_expand(False)
column.set_resizable(True)
entry_view.append_column_custom(column, _("Format"), "tg-format", empty_cb, None, None)
visible_columns = entry_view.get_property("visible-columns")
if 'tg-format' not in visible_columns:
visible_columns.append('tg-format')
entry_view.set_property("visible-columns", visible_columns)
def data_func(self, column, cell, model, iter, *data): # noqa
entry = model.get_value(iter, 0)
idx = get_location_audio_id(get_entry_location(entry))
cell.set_property("text", "%s" % self.source.get_custom_model(idx)[1])
class SizeColumn:
def __init__(self, source):
self.source = source
entry_view = source.get_entry_view()
column = Gtk.TreeViewColumn()
renderer = Gtk.CellRendererText()
column.set_title(_("Size"))
column.set_cell_data_func(renderer, self.data_func, None) # noqa
column.pack_start(renderer, expand=False)
column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
entry_view.set_fixed_column_width(column, renderer, ["4kb", "121.1MB"])
column.set_expand(False)
column.set_resizable(True)
entry_view.append_column_custom(column, _("Size"), "tg-size", empty_cb, None, None)
visible_columns = entry_view.get_property("visible-columns")
if 'tg-size' not in visible_columns:
visible_columns.append('tg-size')
entry_view.set_property("visible-columns", visible_columns)
def data_func(self, column, cell, model, iter, *data): # noqa
entry = model.get_value(iter, 0)
idx = get_location_audio_id(get_entry_location(entry))
cell.set_property("text", "%s" % self.source.get_custom_model(idx)[0])
state_icons = {
Audio.STATE_DEFAULT : 'tg-state-download-symbolic',
Audio.STATE_ERROR : 'tg-state-error',
Audio.STATE_IN_LIBRARY : 'tg-state-library-symbolic',
Audio.STATE_HIDDEN : 'tg-state-visibility-off-symbolic',
Audio.STATE_DOWNLOADED : None,
}
class StateColumn:
_icon_cache = {}
def __init__(self, source):
self._pulse = 0
self._models = {}
self.timeout_id = None
column = Gtk.TreeViewColumn()
pixbuf_renderer = Gtk.CellRendererPixbuf()
spinner_renderer = Gtk.CellRendererSpinner()
column.set_title(" ")
column.set_cell_data_func(pixbuf_renderer, self.model_data_func, "pixbuf") # noqa
column.set_cell_data_func(spinner_renderer, self.model_data_func, "spinner") # noqa
column.pack_start(spinner_renderer, expand=True)
column.pack_start(pixbuf_renderer, expand=True)
column.set_expand(False)
column.set_resizable(False)
column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
column.set_fixed_width(36)
entry_view = source.get_entry_view()
self.entry_view = entry_view
entry_view.append_column_custom(column, ' ', "tg-state", empty_cb, None, None)
visible_columns = entry_view.get_property("visible-columns")
if 'tg-state' not in visible_columns:
visible_columns.append('tg-state')
entry_view.set_property("visible-columns", visible_columns)
def activate(self):
if not self.timeout_id:
self.timeout_id = GLib.timeout_add(100, self.spinner_pulse)
def deactivate(self):
if self.timeout_id:
GLib.source_remove(self.timeout_id)
self.timeout_id = None
def spinner_pulse(self):
self._pulse = 0 if self._pulse == 999999 else self._pulse + 1
for idx in self._models.keys():
model, iter = self._models[idx]
if model and iter:
model.emit("row_changed", model.get_path(iter), iter)
else:
del self._models[idx]
return True
def model_data_func(self, column, cell, model, iter, cell_type): # noqa
entry = model.get_value(iter, 0)
idx = model.get_value(iter, 1)
state = get_entry_state(entry)
is_spinner = cell_type == 'spinner'
if state == Audio.STATE_LOADING:
cell.props.visible = is_spinner
if is_spinner:
self._models[idx] = [model, iter]
cell.props.active = True
cell.props.pulse = self._pulse
else:
cell.props.visible = not is_spinner
if is_spinner:
if idx in self._models:
del self._models[idx]
cell.props.active = False
else:
if state in StateColumn._icon_cache:
gicon = StateColumn._icon_cache[state]
else:
icon_name = state_icons[state] if state in state_icons else state_icons[Audio.STATE_DEFAULT]
gicon = Gio.ThemedIcon.new(icon_name) if icon_name is not None else None
StateColumn._icon_cache[state] = gicon
cell.props.gicon = gicon
class DownloadBar(metaclass=SingletonMeta):
def __init__(self, plugin):
self.plugin = plugin
self.source = None
self.active = False
self.info = {}
plugin.connect('update_download_info', self.update_download_info)
def deactivate(self, source):
self.active = False
def activate(self, source):
self.source = source
if source.bar_ui is None:
entry_view = source.get_entry_view()
builder = Gtk.Builder()
builder.add_from_file(rb.find_plugin_file(source.plugin, "ui/status.ui"))
status_box = builder.get_object('status_box')
source.bar_ui = {
"box": status_box,
"counter": builder.get_object('counter_label'),
"filename": builder.get_object('filename_label'),
"progress": builder.get_object('progress_bar'),
}
entry_view.pack_end(status_box, False, False, 0)
status_box.show_all()
status_box.props.visible = False
self.active = True
self._update_ui()
def _update_ui(self):
if not self.active:
return
if self.source:
is_visible = self.info.get('active', False)
self.source.bar_ui["box"].props.visible = is_visible
if is_visible:
self.source.bar_ui["counter"].set_text(_('File %s of %s') % (self.info.get('index', 1), self.info.get('total', 1)))
self.source.bar_ui["filename"].set_text(self.info.get('filename', ''))
self.source.bar_ui["progress"].set_fraction(self.info.get('fraction', 0.0))
def update_download_info(self, plugin, info):
self.info = info
self._update_ui()
class RefreshBtn:
activated = False
def __init__(self, source):
self.source = source
def activate(self):
if self.activated:
return
entry_view = self.source.get_entry_view()
paned = entry_view.get_parent()
grid = paned.get_parent()
toolbar = None
for child in grid.get_children():
if 'RB.SourceToolbar' in '%s' % type(child):
toolbar = child
break
if toolbar:
toolbar.set_column_homogeneous(False)
button = Gtk.Button(label=_("Refresh"))
button.get_style_context().add_class("flat")
button.props.visible = True
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
box.props.visible = True
toolbar.attach(box, 3, 0, 1, 1)
box.pack_start(button, False, False, 0)
spinner = Gtk.Spinner()
spinner.props.visible = False
# spinner.start()
label = Gtk.Label(label=" %s" % _("Loading..."))
label.props.visible = False
box.pack_start(spinner, False, False, 0)
box.pack_start(label, False, False, 0)
self.button = button
self.spinner = spinner
self.label = label
self.source.connect("playlist-fetch-started", self.fetch_started_cb)
self.source.connect("playlist-fetch-end", self.fetch_end_cb)
self.activated = True
button.connect("clicked", self.clicked_cb)
def clicked_cb(self, *obj):
if self.source.loader:
self.source.loader.fetch()
def fetch_started_cb(self, *obj):
self.button.props.visible = False
self.spinner.props.visible = True
self.label.props.visible = True
self.spinner.start()
def fetch_end_cb(self, *obj):
self.spinner.stop()
self.button.props.visible = True
self.spinner.props.visible = False
self.label.props.visible = False
class TelegramSource(RB.BrowserSource):
__gsignals__ = {
'playlist_fetch_started': (GObject.SignalFlags.RUN_FIRST, None, ()),
'playlist_fetch_end': (GObject.SignalFlags.RUN_FIRST, None, ()),
}
def __str__(self) -> str:
return f'TelegramSource <{self.chat_id}>'
def __init__(self):
self.is_activated = False
RB.BrowserSource.__init__(self)
self.app = Gio.Application.get_default()
self.initialised = False
self.activated = False
self.shell = None
self.db = None
self.entry_type = None
self.loader = None
self.plugin = None
self.chat_id = None
self.chat_title = None
self.visibility = None
self.refresh_btn = RefreshBtn(self)
self.bar = None
self.bar_ui = None
self.entry_updated_id = None
self.loaded_entries = []
self.custom_model = {}
def setup(self, plugin, chat_id, chat_title, visibility):
self.initialised = False
shell = self.props.shell
self.shell = shell
self.db = shell.props.db
self.set_property("query-model", RB.RhythmDBQueryModel.new_empty(self.db))
self.entry_type = self.props.entry_type
self.plugin = plugin
self.chat_id = chat_id
self.chat_title = chat_title
self.visibility = visibility
self.loader = None
self.init_columns()
self.activate()
# add shared menu (add to playlist)
self.set_property("playlist-menu", self.shell.props.application.get_shared_menu("playlist-page-menu"))
def init_columns(self):
if self.plugin.account.settings[KEY_RATING_COLUMN]:
self.get_entry_view().append_column(rb.RB.EntryViewColumn.RATING, True)
if self.plugin.account.settings[KEY_FILE_SIZE_COLUMN]:
SizeColumn(self)
if self.plugin.account.settings[KEY_AUDIO_FORMAT_COLUMN]:
FormatColumn(self)
if self.plugin.account.settings[KEY_DATE_ADDED_COLUMN]:
self.get_entry_view().append_column(rb.RB.EntryViewColumn.FIRST_SEEN, True)
self.state_column = StateColumn(self) # noqa
def activate(self):
self.refresh_btn.activate()
self.activated = True
self.entry_updated_id = self.db.connect('entry-changed', self.on_entry_changed)
self.props.entry_type.activate()
def deactivate(self):
if self.activated:
self.activated = False
if self.loader is not None:
self.loader.stop()
self.loader = None
self.db.disconnect(self.entry_updated_id)
self.props.entry_type.deactivate()
def on_entry_changed(self, db, entry, changes):
if self.entry_type != entry.get_entry_type():
return
for change in changes:
if change.prop == RB.RhythmDBPropType.PLAY_COUNT:
play_count = entry.get_ulong(RB.RhythmDBPropType.PLAY_COUNT)
audio = self.plugin.storage.get_entry_audio(entry)
audio.save({"play_count": play_count})
elif change.prop == RB.RhythmDBPropType.RATING:
rating = entry.get_double(RB.RhythmDBPropType.RATING)
audio = self.plugin.storage.get_entry_audio(entry)
audio.save({"rating": round(rating)})
def hide_thyself(self):
# self.deactivate()
self.set_property('visibility', False)
def show_thyself(self):
self.activate()
self.set_property('visibility', True)
def do_deselected(self):
self.bar.deactivate(self)
self.state_column.deactivate()
if self.loader is not None:
self.loader.stop()
self.loader = None
self.plugin.remove_plugin_menu()
def do_selected(self):
self.plugin.source = self
self.state_column.activate()
self.get_entry_view().set_sorting_order("FirstSeen", Gtk.SortType.DESCENDING)
self.bar = DownloadBar(self.plugin)
self.bar.activate(self)
if not self.initialised:
self.initialised = True
GLib.idle_add(self.add_entries)
self.plugin.add_plugin_menu()
if self.visibility in (1, None):
if self.loader is not None:
self.loader.stop()
self.loader = PlaylistLoader(self, self.chat_id, self.add_entry)
self.loader.start()
def add_entries(self):
self.plugin.storage.load_entries(self.chat_id, self.add_entry, self.visibility)
def add_entry(self, audio):
if audio.id not in self.loaded_entries:
self.loaded_entries.append(audio.id)
location = to_location(self.plugin.api.hash, self.chat_id, audio.message_id, audio.id)
self.custom_model["%s" % audio.id] = [pretty_file_size(audio.size, 1), audio.get_file_ext()]
entry = self.db.entry_lookup_by_location(location)
if not entry:
entry = RB.RhythmDBEntry.new(self.db, self.entry_type, location)
audio.update_entry(entry, self.db)
def get_custom_model(self, idx):
return self.custom_model[idx]
def do_copy(self):
tg_entries = self.get_entry_view().get_selected_entries()
if len(tg_entries) == 0:
return None
sort_audio = []
albums = {}
num_format = '%0' + str(len(str(len(tg_entries))) + 2) + 'i'
key_format = '%s|%s|%s' % (num_format, num_format, num_format)
for idx, tg_entry in enumerate(tg_entries):
audio = self.plugin.storage.get_entry_audio(tg_entry)
if audio.is_moved:
album = f'{get_first_artist(audio.artist)}|{audio.album}|{audio.get_year()}'
albums_keys = albums.keys()
if album not in albums_keys:
albums[album] = len(albums_keys) + 1
sort_key = key_format % (albums[album], audio.track_number, idx)
sort_audio.append([sort_key, audio])
if len(sort_audio) == 0:
return None
sort_audio.sort(key=lambda d: d[0])
entry_type = self.db.entry_type_get_by_name("song")
song_entries = []
for data in sort_audio:
audio = data[1]
uri = file_uri(audio.local_path)
entry = self.db.entry_lookup_by_location(uri)
if not entry:
entry = RB.RhythmDBEntry.new(self.db, entry_type, uri)
audio.update_entry(entry, self.db, commit=False, state=False)
# self.db.entry_set(entry, RB.RhythmDBPropType.COMMENT, f'Downloaded from {self.chat_title}')
self.db.commit()
song_entries.append(entry)
return song_entries
def do_can_delete(self):
return True
def do_can_copy(self):
return False
def do_can_paste(self):
return False
def do_can_pause(self):
return True
def do_can_add_to_queue(self):
return True
def do_can_move_to_trash(self):
return False
def browse_action(self):
screen = self.props.shell.props.window.get_screen()
entries = self.get_entry_view().get_selected_entries()
if len(entries) == 0:
return
entry = entries[0]
location = entry.get_string(RB.RhythmDBPropType.LOCATION)
chat_id, message_id = get_location_data(location)
audio = Audio({"chat_id": chat_id, "message_id": message_id})
link = audio.get_link()
direct_link = self.plugin.api.get_message_direct_link(link)
if direct_link:
try:
Gtk.show_uri(screen, direct_link, Gdk.CURRENT_TIME)
except GLib.Error:
Gtk.show_uri(screen, link, Gdk.CURRENT_TIME)
elif link:
Gtk.show_uri(screen, link, Gdk.CURRENT_TIME)
def file_manager_action(self):
entries = self.get_entry_view().get_selected_entries()
if len(entries) == 0:
return
app_info = Gio.AppInfo.get_default_for_type('inode/directory', True)
if not app_info:
return
for entry in entries:
audio = self.plugin.storage.get_entry_audio(entry)
if audio.is_file_exists():
app_info.launch_uris([file_uri(audio.local_path)], None)
return
def download_action(self):
entries = self.get_entry_view().get_selected_entries()
if len(entries) == 0:
return
downloader = self.plugin.downloader
downloader.setup()
downloader.add_entries(entries)
downloader.start()
def hide_action(self):
entries = self.get_entry_view().get_selected_entries()
if len(entries) == 0:
return
for entry in entries:
audio = self.plugin.storage.get_entry_audio(entry)
if not audio.is_hidden:
audio.save({"is_hidden": True})
set_entry_state(self.db, entry, audio.get_state())
self.db.commit()
def unhide_action(self):
entries = self.get_entry_view().get_selected_entries()
if len(entries) == 0:
return
for entry in entries:
audio = self.plugin.storage.get_entry_audio(entry)
if audio.is_hidden:
audio.save({"is_hidden": False})
set_entry_state(self.db, entry, audio.get_state())
self.db.commit()
GObject.type_register(TelegramSource)