-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathaccount.py
More file actions
194 lines (166 loc) · 7.81 KB
/
Copy pathaccount.py
File metadata and controls
194 lines (166 loc) · 7.81 KB
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
# rhythmbox-telegram
# Copyright (C) 2023-2026 Andrey Izman <izmanw@gmail.com>
#
# 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 os
import re
from rb import rbconfig # pyright: ignore[reportMissingImports] # noqa
from gi.repository import Gio
from common import SingletonMeta, show_error
from typing import Tuple, Union, Dict, Any, MutableMapping, cast
# settings keys
KEY_API_ID = "api-id"
KEY_API_HASH = "api-hash"
KEY_PHONE = "phone"
KEY_CONNECTED = "connected"
KEY_CHANNELS = "channels"
KEY_LIBRARY_PATH = "library-path"
KEY_CONFLICT_RESOLVE = "conflict-resolve"
KEY_FOLDER_HIERARCHY = "folder-hierarchy"
KEY_FILENAME_TEMPLATE = "filename-template"
KEY_PAGE_GROUP = "page-group"
KEY_AUDIO_VISIBILITY = "audio-visibility"
KEY_DISPLAY_AUDIO_FORMATS = "display-audio-formats"
VAL_AV_VISIBLE = "visible"
VAL_AV_HIDDEN = "hidden"
VAL_AV_ALL = "all"
VAL_AV_DUAL = "dual"
KEY_TOP_PICKS_COLUMN = "top-picks-column"
KEY_RATING_COLUMN = "rating-column"
KEY_DATE_ADDED_COLUMN = "date-added-column"
KEY_FILE_SIZE_COLUMN = "file-size-column"
KEY_AUDIO_FORMAT_COLUMN = "audio-format-column"
KEY_IN_LIBRARY_COLUMN = "in-library-column"
KEY_PRELOAD_NEXT_TRACK = "preload-next-track"
KEY_PRELOAD_PREV_TRACK = "preload-prev-track"
KEY_PRELOAD_HIDDEN_TRACK = "preload-hidden-track"
KEY_PRELOAD_MAX_FILE_SIZE = "preload-max-file-size"
KEY_PRELOAD_FILE_FORMATS = "preload-file-formats"
AUDIO_FORMAT_ALL = 'any'
KEY_DETECT_DIRS_IGNORE_CASE = "detect-dirs-ignore-case"
KEY_DETECT_FILES_IGNORE_CASE = "detect-files-ignore-case"
Secret = None
if rbconfig.libsecret_enabled:
try:
import gi
gi.require_version('Secret', '1')
from gi.repository import Secret # pyright: ignore[reportAttributeAccessIssue]
except ImportError:
pass
class SettingsInterface(Gio.Settings):
def __getitem__(self, key: str) -> Any: ...
class Account(metaclass=SingletonMeta):
"""
Singleton class managing Telegram account credentials and settings.
Provides methods to securely store and retrieve API keys, phone numbers,
and connection status. Handles integration with GNOME keyring via libsecret
with fallback to plaintext storage when unavailable.
"""
def __init__(self, plugin=None):
""" Initialize instance """
self.settings: SettingsInterface
self.plugin = plugin
self.activated = False
self.secret = None
def unlock_keyring(self):
""" Attempt to unlock the system keyring for credential storage. """
schema_test = Secret.Schema.new('org.gnome.rhythmbox.plugins.telegram-test', Secret.SchemaFlags.DONT_MATCH_NAME,
{"test": Secret.SchemaAttributeType.STRING})
return Secret.password_store_sync(schema_test, {"test": "test"}, Secret.COLLECTION_DEFAULT, "test", 'test', None)
def init(self):
"""
Initialize the account manager.
Sets up GSettings schema and attempts to initialize libsecret integration.
Shows error if libsecret is not available.
"""
if self.activated:
return
self.activated = True
schema_source = Gio.SettingsSchemaSource.get_default()
schema: Gio.SettingsSchema = schema_source.lookup('org.gnome.rhythmbox.plugins.telegram', False)
self.settings = cast(SettingsInterface, Gio.Settings.new_full(schema, None, None))
if Secret is None:
print("You need to install libsecret for secure storage of Telegram secret keys")
show_error("You need to install libsecret for secure storage of Telegram secret keys",
"Due to the absence of libsecret, Telegram secret keys will be stored in plaintext in the Gnome GSettings")
else:
self.unlock_keyring()
self.schema = Secret.Schema.new('org.gnome.rhythmbox.plugins.telegram', Secret.SchemaFlags.DONT_MATCH_NAME,
{"rhythmbox-plugin": Secret.SchemaAttributeType.STRING})
self.keyring_attributes = {"rhythmbox-plugin": "telegram"}
self.secret_service = Secret.Service.get_sync(Secret.ServiceFlags.OPEN_SESSION, None)
items = self.secret_service.search_sync(self.schema, self.keyring_attributes,
Secret.SearchFlags.LOAD_SECRETS, None)
if not items or len(items) == 0 or not items[0].get_secret():
print("Couldn't find an existing keyring entry")
return
self.secret = items[0].get_secret().get().decode("utf-8")
def get_secure(self) -> Tuple[str, str, str, bool]:
"""
Retrieve secure credentials from storage.
Returns either from libsecret or fallback plaintext storage based on availability.
Can return individual values or all credentials as a tuple.
"""
if self.secret is None:
connected = self.settings[KEY_CONNECTED]
return str(self.settings[KEY_API_ID]), str(self.settings[KEY_API_HASH]), str(self.settings[KEY_PHONE]), \
connected is True or connected == 'True'
try:
(api_id, api_hash, phone, connected) = self.secret.split("\n")
if not api_id or not api_hash or not phone:
connected = False
return api_id, api_hash, phone, connected is True or connected == 'True'
except ValueError:
return '', '', '', False
def get_library_path(self):
"""
Get the configured music library path.
Checks plugin settings first, falls back to Rhythmbox's configured locations,
and ultimately defaults to ~/Music if no other path is set.
"""
# from settings
if KEY_LIBRARY_PATH in self.settings and self.settings[KEY_LIBRARY_PATH]: # pyright: ignore[reportOperatorIssue]
return self.settings[KEY_LIBRARY_PATH]
# from rhythmbox global settings
locations = self.plugin.rhythmdb_settings.get_strv('locations')
if locations and len(locations):
path = locations[0]
# get default music path
else:
path = os.path.expanduser('~/Music')
return re.sub(r'^file://', '', path)
def update(self, api_id, api_hash, phone, connected=False):
""" Update stored account credentials. """
if not api_id or not api_hash or not phone:
connected = False
connected = connected is True or connected == 'True'
if Secret is None:
print("No secret, use default storage")
self.settings.set_string(KEY_API_ID, api_id)
self.settings.set_string(KEY_API_HASH, api_hash)
self.settings.set_string(KEY_PHONE, phone)
self.settings.set_boolean(KEY_CONNECTED, connected)
return
secret = '\n'.join((api_id, api_hash, phone, str(connected)))
if secret == self.secret:
return
self.secret = secret
result = Secret.password_store_sync(self.schema, self.keyring_attributes, Secret.COLLECTION_DEFAULT,
"Rhythmbox: Telegram credentials", secret, None)
if not result:
print("Couldn't create keyring item!")
def set_connected(self, connected):
""" Update connection status without changing credentials. """
api_id, api_hash, phone, connected_ = self.get_secure()
self.update(api_id, api_hash, phone, connected)