-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroups.js
More file actions
217 lines (183 loc) · 8.08 KB
/
Copy pathgroups.js
File metadata and controls
217 lines (183 loc) · 8.08 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// --- Configuration ---
const API_URL = "http://127.0.0.1:5000";
const groupsContainer = document.getElementById('groupsContainer');
const groupMessage = document.getElementById('groupMessage');
const createGroupButton = document.getElementById('createGroupButton');
// --- Utility Functions ---
function getToken() {
const token = localStorage.getItem('token');
if (!token) {
logout(); // Redirect to login if no token
return null;
}
return token;
}
function showMessage(element, text, isSuccess = true) {
element.textContent = text;
element.className = `mt-3 text-sm font-medium p-2 rounded ${isSuccess ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`;
}
// --- Group API Functions ---
/**
* Handles the creation of a new group.
*/
async function handleCreateGroup(event) {
event.preventDefault();
const token = getToken();
if (!token) return;
const nameInput = document.getElementById('groupName');
const groupName = nameInput.value.trim();
if (!groupName) {
showMessage(groupMessage, "Group name cannot be empty.", false);
return;
}
createGroupButton.disabled = true;
createGroupButton.textContent = 'Creating...';
groupMessage.textContent = ''; // Clear previous message
try {
const res = await axios.post(`${API_URL}/groups`, { name: groupName }, {
headers: { Authorization: `Bearer ${token}` }
});
showMessage(groupMessage, `Group "${res.data.name}" created! Invite link: ${res.data.invite_link}`, true);
nameInput.value = ''; // Clear input
fetchGroups(); // Refresh the list of groups
} catch (err) {
console.error('Error creating group:', err);
const errorMessage = err.response?.data?.error || 'Failed to create group.';
showMessage(groupMessage, errorMessage, false);
} finally {
createGroupButton.disabled = false;
createGroupButton.textContent = 'Create Group';
}
}
/**
* Deletes a group (Owner only).
*/
async function deleteGroup(groupId) {
if (!confirm('Are you sure you want to delete this group? This action is irreversible.')) {
return;
}
const token = getToken();
if (!token) return;
try {
await axios.delete(`${API_URL}/groups/${groupId}`, {
headers: { Authorization: `Bearer ${token}` }
});
showMessage(document.getElementById('groupMessage'), `Group ID ${groupId} deleted successfully.`, true);
fetchGroups(); // Refresh the list
} catch (err) {
console.error('Error deleting group:', err);
const errorMessage = err.response?.data?.error || 'Failed to delete group.';
showMessage(document.getElementById('groupMessage'), errorMessage, false);
}
}
/**
* Removes a member from a group (Admin/Self only).
*/
async function removeMember(groupId, userId) {
if (!confirm(`Are you sure you want to remove User ID ${userId} from the group?`)) {
return;
}
const token = getToken();
if (!token) return;
try {
await axios.delete(`${API_URL}/groups/${groupId}/remover/${userId}`, {
headers: { Authorization: `Bearer ${token}` }
});
showMessage(document.getElementById('groupMessage'), `User ${userId} removed from Group ${groupId}.`, true);
fetchGroups(); // Refresh the list
} catch (err) {
console.error('Error removing member:', err);
const errorMessage = err.response?.data?.error || 'Failed to remove member.';
showMessage(document.getElementById('groupMessage'), errorMessage, false);
}
}
// --- Display/Rendering Functions ---
/**
* Fetches and renders the user's groups.
*/
async function fetchGroups() {
// Check if the loading element exists before trying to access its outerHTML
const loadingEl = document.getElementById('loadingGroups');
if (loadingEl) {
groupsContainer.innerHTML = loadingEl.outerHTML; // Show loading state
} else {
groupsContainer.innerHTML = '<p class="text-gray-500 text-center py-4">Loading your groups...</p>';
}
// --- TEMPORARY DUMMY DATA (REPLACE WITH REAL API CALL) ---
// Assuming a GET /groups endpoint would return this format:
// (You will need to implement this GET endpoint on your backend)
const dummyGroups = [
// Assume User ID 101 is the current user
{ id: 1, name: "Admin's Group", is_owner: true, members: [{ id: 101, username: "Alice (You)", is_current_user: true }, { id: 102, username: "Bob", is_admin: false }] },
{ id: 2, name: "The Dreamers", is_owner: false, members: [{ id: 101, username: "Alice (You)", is_current_user: true }, { id: 103, username: "Charlie", is_admin: true }] },
];
// const groups = res.data; // Use this line after implementing the GET endpoint
// Simulation delay
await new Promise(resolve => setTimeout(resolve, 500));
// --- END DUMMY DATA ---
const groups = dummyGroups; // REMOVE THIS LINE LATER
groupsContainer.innerHTML = '';
if (groups.length === 0) {
groupsContainer.innerHTML = '<p class="text-gray-600 text-center py-8 bg-white rounded-lg shadow">You are not a member of any group.</p>';
return;
}
groups.forEach(group => {
const groupHTML = createGroupHTML(group);
groupsContainer.insertAdjacentHTML('beforeend', groupHTML);
});
}
/**
* Generates the HTML card for a single group, including the chat link.
*/
function createGroupHTML(group) {
// Member list HTML
const membersHTML = group.members.map(member => `
<li class="flex justify-between items-center py-1.5 border-b border-gray-100 last:border-b-0">
<span class="text-gray-700">${member.username}</span>
${group.is_owner && !member.is_current_user ? // Only owner can remove others
`<button onclick="removeMember(${group.id}, ${member.id})"
class="text-xs text-red-500 hover:text-red-700 transition duration-150 ml-4 p-1 rounded hover:bg-red-50">
Remove
</button>`
: ''}
${member.is_current_user && !group.is_owner ? // Non-owner can leave
`<button onclick="removeMember(${group.id}, ${member.id})"
class="text-xs text-orange-500 hover:text-orange-700 transition duration-150 ml-4 p-1 rounded hover:bg-orange-50">
Leave
</button>`
: ''}
</li>
`).join('');
return `
<div class="bg-white shadow-lg rounded-xl p-6 border ${group.is_owner ? 'border-brand-primary' : 'border-gray-200'}">
<div class="flex justify-between items-start mb-4">
<div>
<a href="chat.html?id=${group.id}" class="hover:underline transition duration-150">
<h3 class="text-xl font-bold text-gray-900">${group.name}</h3>
</a>
<span class="text-sm font-medium text-brand-primary">${group.is_owner ? 'Owner (Admin)' : 'Member'}</span>
</div>
${group.is_owner ? // Only show delete button for the owner
`<button onclick="deleteGroup(${group.id})"
class="text-sm font-medium text-white bg-red-600 hover:bg-red-700 py-1.5 px-3 rounded-lg transition duration-200 shadow-sm">
Delete Group
</button>`
: ''}
</div>
<div class="mt-4 border-t pt-4">
<h4 class="font-bold text-gray-800 mb-2">Members (${group.members.length}):</h4>
<ul class="space-y-1 text-sm bg-gray-50 p-3 rounded-lg">
${membersHTML}
</ul>
</div>
</div>
`;
}
// --- Initialization ---
// Expose functions globally for HTML calls
window.logout = () => { localStorage.removeItem('token'); window.location.href = '/login.html'; };
window.handleCreateGroup = handleCreateGroup;
window.deleteGroup = deleteGroup;
window.removeMember = removeMember;
// Load groups on page load
fetchGroups();