Debian Codegraph @

pynicotine/gtkgui/popovers/chathistory.py

raw
1 # COPYRIGHT (C) 2022-2024 Nicotine+ Contributors
2 #
3 # GNU GENERAL PUBLIC LICENSE
4 # Version 3, 29 June 2007
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 import os
20 import time
21
22 from collections import deque
23
24 from gi.repository import GObject
25
26 from pynicotine.config import config
27 from pynicotine.core import core
28 from pynicotine.events import events
29 from pynicotine.gtkgui.application import GTK_API_VERSION
30 from pynicotine.gtkgui.widgets import ui
31 from pynicotine.gtkgui.widgets.accelerator import Accelerator
32 from pynicotine.gtkgui.widgets.popover import Popover
33 from pynicotine.gtkgui.widgets.textentry import CompletionEntry
34 from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_NAMES
35 from pynicotine.gtkgui.widgets.theme import add_css_class
36 from pynicotine.gtkgui.widgets.treeview import TreeView
37 from pynicotine.logfacility import log
38 from pynicotine.slskmessages import UserStatus
39 from pynicotine.utils import encode_path
40
41
42 class ChatHistory(Popover):
43
44 def __init__(self, window):
45
46 (
47 self.container,
48 self.list_container,
49 self.search_entry
50 ) = ui.load(scope=self, path="popovers/chathistory.ui")
51
52 super().__init__(
53 window=window,
54 content_box=self.container,
55 width=1000,
56 height=700
57 )
58
59 self.list_view = TreeView(
60 window, parent=self.list_container, activate_row_callback=self.on_show_user,
61 search_entry=self.search_entry,
62 columns={
63 "status": {
64 "column_type": "icon",
65 "title": _("Status"),
66 "width": 25,
67 "hide_header": True
68 },
69 "user": {
70 "column_type": "text",
71 "title": _("User"),
72 "width": 175,
73 "iterator_key": True
74 },
75 "latest_message": {
76 "column_type": "text",
77 "title": _("Latest Message")
78 },
79
80 # Hidden data columns
81 "timestamp_data": {
82 "data_type": GObject.TYPE_UINT64,
83 "default_sort_type": "descending"
84 }
85 }
86 )
87
88 Accelerator("<Primary>f", self.widget, self.on_search_accelerator)
89 self.completion_entry = CompletionEntry(window.private_entry, self.list_view.model, column=1)
90
91 if GTK_API_VERSION >= 4:
92 inner_button = next(iter(window.private_history_button))
93 add_css_class(widget=inner_button, css_class="arrow-button")
94
95 self.set_menu_button(window.private_history_button)
96 self.load_users()
97
98 for event_name, callback in (
99 ("server-login", self.server_login),
100 ("server-disconnect", self.server_disconnect),
101 ("user-status", self.user_status)
102 ):
103 events.connect(event_name, callback)
104
105 def destroy(self):
106
107 self.list_view.destroy()
108 self.completion_entry.destroy()
109
110 super().destroy()
111
112 def server_login(self, msg):
113
114 if not msg.success:
115 return
116
117 for iterator in self.list_view.iterators.values():
118 username = self.list_view.get_row_value(iterator, "user")
119 core.users.watch_user(username, context="chathistory")
120
121 def server_disconnect(self, *_args):
122 for iterator in self.list_view.iterators.values():
123 self.list_view.set_row_value(iterator, "status", USER_STATUS_ICON_NAMES[UserStatus.OFFLINE])
124
125 @staticmethod
126 def load_user(file_path):
127 """Reads the username and latest message from a given log file path.
128
129 Usernames are first extracted from the file name. In case the
130 extracted username contains underscores, attempt to fetch the
131 original username from logged messages, since illegal filename
132 characters are substituted with underscores.
133 """
134
135 username = os.path.basename(file_path[:-4]).decode("utf-8", "replace")
136 is_safe_username = ("_" not in username)
137 login_username = config.sections["server"]["login"]
138 timestamp = os.path.getmtime(file_path)
139
140 read_num_lines = 1 if is_safe_username else 25
141 latest_message = None
142
143 with open(file_path, "rb") as lines:
144 lines = deque(lines, read_num_lines)
145
146 for line in lines:
147 try:
148 line = line.decode("utf-8")
149
150 except UnicodeDecodeError:
151 line = line.decode("latin-1")
152
153 if latest_message is None:
154 latest_message = line
155
156 if is_safe_username:
157 break
158
159 username_chars = set(username.replace("_", ""))
160
161 if login_username in line:
162 continue
163
164 if " [" not in line or "] " not in line:
165 continue
166
167 start = line.find(" [") + 2
168 end = line.find("] ", start)
169 line_username_len = (end - start)
170
171 if len(username) != line_username_len:
172 continue
173
174 line_username = line[start:end]
175
176 if username == line_username:
177 # Nothing to do, username is already correct
178 break
179
180 if username_chars.issubset(line_username):
181 username = line_username
182 break
183
184 return username, latest_message, timestamp
185
186 def load_users(self):
187
188 self.list_view.freeze()
189
190 try:
191 with os.scandir(encode_path(log.private_chat_folder_path)) as entries:
192 for entry in entries:
193 if not entry.is_file() or not entry.name.endswith(b".log"):
194 continue
195
196 try:
197 username, latest_message, timestamp = self.load_user(entry.path)
198
199 except OSError:
200 continue
201
202 if latest_message is not None:
203 self.update_user(username, latest_message.strip(), timestamp)
204
205 except OSError:
206 pass
207
208 self.list_view.unfreeze()
209
210 def remove_user(self, username):
211
212 iterator = self.list_view.iterators.get(username)
213
214 if iterator is not None:
215 self.list_view.remove_row(iterator)
216
217 def update_user(self, username, message, timestamp=None):
218
219 self.remove_user(username)
220 core.users.watch_user(username, context="chathistory")
221
222 if not timestamp:
223 timestamp_format = config.sections["logging"]["log_timestamp"]
224 timestamp = time.time()
225 h_timestamp = time.strftime(timestamp_format)
226 message = f"{h_timestamp} {message}"
227
228 status = core.users.statuses.get(username, UserStatus.OFFLINE)
229
230 self.list_view.add_row([
231 USER_STATUS_ICON_NAMES[status],
232 username,
233 message,
234 int(timestamp)
235 ], select_row=False)
236
237 def user_status(self, msg):
238
239 iterator = self.list_view.iterators.get(msg.user)
240
241 if iterator is None:
242 return
243
244 status_icon_name = USER_STATUS_ICON_NAMES.get(msg.status)
245
246 if status_icon_name and status_icon_name != self.list_view.get_row_value(iterator, "status"):
247 self.list_view.set_row_value(iterator, "status", status_icon_name)
248
249 def on_show_user(self, *_args):
250
251 for iterator in self.list_view.get_selected_rows():
252 username = self.list_view.get_row_value(iterator, "user")
253
254 core.privatechat.show_user(username)
255 self.close(use_transition=False)
256 return
257
258 def on_search_accelerator(self, *_args):
259 """Ctrl+F - Search users."""
260
261 self.search_entry.grab_focus()
262 return True