g3w-admin-plugins 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,333 @@
1
+ {% extends "base.html" %}
2
+ {% block page_header %}<h1>Plugins</h1>{% endblock %}
3
+ {% block main_content %}
4
+ <style>
5
+ .plugin-change button i, .plugin-update button i { margin-right: 0.4em; }
6
+ .plugin-update { display: inline-block; margin-left: 0.4em; }
7
+ .plugin-update[hidden], .retry-version[hidden] { display: none !important; }
8
+ .plugin-change .btn-success { background-color: #256d36; border-color: #1d562a; }
9
+ .plugin-change .btn-success:hover, .plugin-change .btn-success:focus { background-color: #1d562a; }
10
+ .plugin-change .btn-danger { background-color: #ad302a; border-color: #882722; }
11
+ .plugin-change .btn-danger:hover, .plugin-change .btn-danger:focus { background-color: #882722; }
12
+ .plugin-warning { display: block; color: #8a4b08; }
13
+ </style>
14
+ <p><b>Back up your database and plugins before making changes. Disabling a plugin preserves its data. {% if reload_available %}Changes apply automatically.{% else %}Restart G3W-SUITE and its consumer to apply changes.{% endif %}</b></p>
15
+ {% if job.status == "running" %}
16
+ <div id="job-status" class="alert alert-info" role="status" aria-live="polite">Preparing {{ job.plugin }}. Refresh this page to check progress.</div>
17
+ {% elif job.status == "succeeded" %}
18
+ <div id="job-status" class="alert {% if job.reload == 'requested' and web_applied and not consumer_required or job.reload == 'requested' and web_applied and consumer_applied %}alert-success{% else %}alert-info{% endif %}" role="status" aria-live="polite" data-plugin="{{ job.plugin }}" data-action="{{ job.action }}" data-target="{{ job.target|default:'' }}" data-requested-at="{{ job.reload_requested_at|default:''|stringformat:'s' }}" {% if job.reload == 'requested' and web_applied and not consumer_required or job.reload == 'requested' and web_applied and consumer_applied %}data-confirmed="true" hidden{% endif %}>{{ job.plugin }}: {{ job.action }} completed. {% if job.reload == "requested" %}{% if web_applied and consumer_required and consumer_applied %}Web and consumer loaded the new configuration.{% elif web_applied and not consumer_required %}Web loaded the new configuration; the consumer is disabled.{% else %}Reload requested; refresh to check web and consumer status.{% endif %}{% else %}Reload G3W-SUITE and its consumer to apply.{% endif %}</div>
19
+ <noscript><style>#job-status[hidden] { display: block !important; }</style></noscript>
20
+ {% elif job.status == "reload_failed" %}
21
+ <div id="job-status" class="alert alert-warning" role="status" aria-live="polite">Preparation completed, but automatic reload failed: {{ job.error }}. Retry the reload or restart manually.</div>
22
+ {% elif job.status == "failed" %}
23
+ <div id="job-status" class="alert alert-danger" role="status" aria-live="polite"><p>Plugin preparation failed. The previous configuration is preserved if the failure occurred before saving, but database, static files or menus may already have changed. Check the server logs and backups before retrying.</p><pre>{{ job.error }}</pre></div>
24
+ {% else %}
25
+ <div id="job-status" class="alert" role="status" aria-live="polite" hidden></div>
26
+ {% endif %}
27
+ <progress id="job-progress" aria-label="Plugin preparation in progress" {% if job.status != "running" %}hidden{% endif %}></progress>
28
+ {% if reload_available %}
29
+ <form id="manual-reload" class="job-submit" method="post" onsubmit="return confirm('Retry reloading G3W-SUITE and its consumer?');" {% if job.status != "reload_failed" and job.status != "succeeded" %}hidden{% elif job.reload == "requested" %}hidden{% endif %}>
30
+ {% csrf_token %}
31
+ <button class="job-action" type="submit" name="action" value="reload" {% if job.status == "running" %}disabled{% endif %}>Retry reload</button>
32
+ </form>
33
+ {% endif %}
34
+ <table class="table table-striped">
35
+ <thead><tr><th>Package</th><th>Version</th><th>Status</th><th>Action</th></tr></thead>
36
+ <tbody>
37
+ {% for plugin in plugins %}
38
+ <tr data-plugin="{{ plugin.package }}" data-version="{{ plugin.version|default_if_none:'' }}" data-enabled="{% if plugin.enabled %}true{% else %}false{% endif %}" data-bundled="{% if plugin.bundled %}true{% else %}false{% endif %}">
39
+ <td>{% if plugin.bundled %}<a href="https://github.com/g3w-suite/g3w-admin/tree/dev/g3w-admin/{{ plugin.app }}">{{ plugin.display_name }}</a>{% else %}<a href="https://pypi.org/project/{{ plugin.package }}/">{{ plugin.display_name }}</a>{% endif %}</td>
40
+ <td class="plugin-version"><span class="plugin-version-value">{% if plugin.bundled %}{{ VERSION|default:"Not available" }}{% elif plugin.version %}{{ plugin.version }}{% else %}Not available{% endif %}</span>
41
+ {% if not plugin.bundled %}
42
+ <span class="plugin-version-info"></span>
43
+ <form method="post" class="plugin-update job-submit" hidden>{% csrf_token %}
44
+ <input type="hidden" name="plugin" value="{{ plugin.package }}">
45
+ <input type="hidden" name="version" value="">
46
+ <button class="job-action btn btn-primary btn-sm" name="action" value="update" aria-label="Update {{ plugin.package }}" {% if job.status == "running" %}disabled{% endif %}><i class="fa fa-arrow-circle-up" aria-hidden="true"></i> <span>Update</span></button>
47
+ </form>
48
+ <button type="button" class="retry-version btn btn-default btn-xs" hidden>Retry</button>
49
+ {% endif %}
50
+ </td>
51
+ <td class="plugin-status">{{ plugin.status }}</td>
52
+ <td><form method="post" class="plugin-change job-submit">{% csrf_token %}
53
+ <input type="hidden" name="plugin" value="{{ plugin.package }}">
54
+ <button class="job-action btn {% if plugin.enabled %}btn-danger{% else %}btn-success{% endif %} btn-sm" data-blocked="{% if plugin.warning %}true{% else %}false{% endif %}" name="action" value="{% if plugin.enabled %}disable{% else %}enable{% endif %}" aria-label="{% if plugin.enabled %}Disable{% else %}Enable{% endif %} {{ plugin.display_name }}" {% if job.status == "running" or plugin.warning %}disabled{% endif %}>
55
+ <i class="fa {% if plugin.enabled %}fa-stop{% else %}fa-play{% endif %}" aria-hidden="true"></i> <span>{% if plugin.enabled %}Disable{% else %}Enable{% endif %}</span>
56
+ </button>
57
+ </form><small class="plugin-warning">{{ plugin.warning }}</small></td>
58
+ </tr>
59
+ {% endfor %}
60
+ </tbody>
61
+ </table>
62
+ <script>
63
+ (function () {
64
+ var status = document.getElementById('job-status');
65
+ var progress = document.getElementById('job-progress');
66
+ var manualReload = document.getElementById('manual-reload');
67
+ var statusUrl = '{{ status_url|escapejs }}';
68
+ var alternateStatusUrl = '{{ alternate_status_url|escapejs }}';
69
+ var versionUrl = '{{ version_url|escapejs }}';
70
+ var versions = {};
71
+ var pending = false;
72
+ var submitError = '';
73
+ var successStorageKey = 'g3w-plugins-seen-success';
74
+ var previouslySeenSuccess = null;
75
+ try {
76
+ previouslySeenSuccess = sessionStorage.getItem(successStorageKey);
77
+ } catch (error) {
78
+ console.warn('Cannot remember plugin success notifications:', error);
79
+ }
80
+ var navigation = typeof performance !== 'undefined' && performance.getEntriesByType
81
+ ? performance.getEntriesByType('navigation')[0] : null;
82
+ if (navigation && navigation.type === 'reload' && status.dataset.confirmed === 'true') {
83
+ previouslySeenSuccess = successKey({
84
+ plugin: status.dataset.plugin,
85
+ action: status.dataset.action,
86
+ target: status.dataset.target,
87
+ reload_requested_at: status.dataset.requestedAt
88
+ });
89
+ }
90
+ var phases = {
91
+ starting: 'Starting preparation',
92
+ install: 'Installing plugin packages and dependencies',
93
+ migrate: 'Applying database migrations',
94
+ collectstatic: 'Collecting static files (this may take several minutes)',
95
+ sitetree_resync_apps: 'Updating menus',
96
+ save: 'Saving the plugin configuration',
97
+ reload: 'Requesting reload of G3W-SUITE and its consumer'
98
+ };
99
+ function lockActions(locked) {
100
+ document.querySelectorAll('.job-action').forEach(function (button) {
101
+ button.disabled = locked || button.dataset.blocked === 'true';
102
+ });
103
+ }
104
+ function show(message, type) {
105
+ status.hidden = false;
106
+ progress.hidden = type !== 'info';
107
+ status.className = 'alert alert-' + type;
108
+ status.textContent = message;
109
+ }
110
+ function successKey(job) {
111
+ return JSON.stringify([job.plugin, job.action, job.target || '',
112
+ job.reload_requested_at ? Number(job.reload_requested_at) : null]);
113
+ }
114
+ function showSuccess(job, message) {
115
+ var key = successKey(job);
116
+ if (key === previouslySeenSuccess) {
117
+ status.hidden = true;
118
+ progress.hidden = true;
119
+ } else {
120
+ show(message, 'success');
121
+ }
122
+ try {
123
+ sessionStorage.setItem(successStorageKey, key);
124
+ } catch (error) {
125
+ console.warn('Cannot remember plugin success notifications:', error);
126
+ }
127
+ }
128
+ function renderVersion(row, entry) {
129
+ var value = row.querySelector('.plugin-version-value');
130
+ var info = row.querySelector('.plugin-version-info');
131
+ var form = row.querySelector('.plugin-update');
132
+ value.textContent = entry.installed || entry.latest || 'Not available';
133
+ if (entry.error) {
134
+ info.textContent = ' (' + entry.error + ')';
135
+ } else if (entry.checking) {
136
+ info.textContent = entry.installed ? ' (checking for updates...)' : ' (checking PyPI...)';
137
+ } else if (entry.available && !entry.enabled) {
138
+ info.textContent = ' (enable to update to ' + entry.latest + ')';
139
+ } else {
140
+ info.textContent = '';
141
+ }
142
+ row.querySelector('.retry-version').hidden = !entry.error;
143
+ form.hidden = !(entry.installed && entry.available && entry.enabled);
144
+ if (entry.latest) {
145
+ form.querySelector('input[name=version]').value = entry.latest;
146
+ form.querySelector('button').title = 'Update to ' + entry.latest;
147
+ form.querySelector('button span').textContent = 'Update to ' + entry.latest;
148
+ }
149
+ }
150
+ function checkVersion(row, installed, enabled) {
151
+ var packageName = row.dataset.plugin;
152
+ var entry = {installed: installed, enabled: enabled, checking: true};
153
+ versions[packageName] = entry;
154
+ renderVersion(row, entry);
155
+ fetch(versionUrl + '?plugin=' + encodeURIComponent(packageName), {
156
+ credentials: 'same-origin', cache: 'no-store'
157
+ }).then(function (response) {
158
+ if (response.redirected) throw new Error('Session expired. Sign in again.');
159
+ return response.json().then(function (data) {
160
+ if (!response.ok) throw new Error(data.error || 'Version check failed');
161
+ if (response.status === 202) return null;
162
+ if (data.installed !== installed) throw new Error('Web worker version changed; retry');
163
+ return data;
164
+ });
165
+ }).then(function (data) {
166
+ if (versions[packageName] !== entry) return;
167
+ if (!data) {
168
+ window.setTimeout(function () {
169
+ if (versions[packageName] === entry) checkVersion(row, installed, entry.enabled);
170
+ }, 1500);
171
+ return;
172
+ }
173
+ entry.latest = data.latest;
174
+ entry.available = data.available;
175
+ entry.checking = false;
176
+ renderVersion(row, entry);
177
+ }).catch(function (error) {
178
+ if (versions[packageName] !== entry) return;
179
+ entry.error = error.message;
180
+ entry.checking = false;
181
+ renderVersion(row, entry);
182
+ });
183
+ }
184
+ function update(data) {
185
+ var job = data.job;
186
+ var awaitingWeb = job && job.status === 'succeeded' && job.reload === 'requested' &&
187
+ !data.web_applied && job.reload_requested_at && data.server_time - job.reload_requested_at < 60;
188
+ var reloadTimedOut = job && job.status === 'succeeded' && job.reload === 'requested' &&
189
+ !data.web_applied && !awaitingWeb;
190
+ var awaitingConsumer = job && job.status === 'succeeded' && job.reload === 'requested' &&
191
+ data.consumer_required && !data.consumer_applied;
192
+ var consumerTimedOut = awaitingConsumer &&
193
+ (!job.reload_requested_at || data.server_time - job.reload_requested_at >= 60);
194
+ lockActions(pending || awaitingWeb || awaitingConsumer || (job && job.status === 'running'));
195
+ if (manualReload) {
196
+ manualReload.hidden = !(job && (job.status === 'reload_failed' ||
197
+ (job.status === 'succeeded' && ((job.reload !== 'requested' &&
198
+ (job.reload || !data.web_applied)) || reloadTimedOut || consumerTimedOut))));
199
+ if (consumerTimedOut) manualReload.querySelector('button').disabled = pending;
200
+ }
201
+ if (pending) {
202
+ return;
203
+ } else if (job && job.status === 'running') {
204
+ show((job.plugin ? job.plugin + ': ' : '') +
205
+ (phases[job.phase] || 'Starting preparation') + '. Please wait.', 'info');
206
+ } else if (submitError) {
207
+ show('Could not confirm the operation: ' + submitError + '. Check the status before retrying.', 'danger');
208
+ } else if (job && job.status === 'reload_failed') {
209
+ show('Preparation completed, but automatic reload failed: ' + job.error +
210
+ '. Retry the reload or restart G3W-SUITE and its consumer manually.', 'warning');
211
+ } else if (job && job.status === 'succeeded') {
212
+ if (awaitingWeb) {
213
+ show('Preparation completed. Waiting for the web process to load the new configuration.', 'info');
214
+ } else if (reloadTimedOut) {
215
+ show('Reload was requested, but the web process has not confirmed the new configuration. Retry the reload or restart manually.', 'warning');
216
+ } else if (awaitingConsumer) {
217
+ show(consumerTimedOut
218
+ ? 'The consumer has not confirmed the new configuration. It may still be finishing tasks; retry the reload or restart it manually if needed.'
219
+ : 'Web configuration loaded. Waiting for the consumer to finish reloading.', consumerTimedOut ? 'warning' : 'info');
220
+ } else if (job.reload === 'requested') {
221
+ showSuccess(job, job.plugin + ': ' + job.action + ' completed. ' +
222
+ (data.consumer_required ? 'Web and consumer loaded the new configuration.' :
223
+ 'Web loaded the new configuration; the consumer is disabled.'));
224
+ } else if (!job.reload && data.web_applied) {
225
+ show(job.plugin + ': ' + job.action + ' completed. A web worker has loaded the current configuration; consumer status cannot be confirmed.', 'success');
226
+ } else {
227
+ show(job.plugin + ': ' + job.action + ' completed. Restart G3W-SUITE and its consumer to apply.', 'success');
228
+ }
229
+ } else if (job && job.status === 'failed') {
230
+ show('Plugin preparation failed: ' + job.error +
231
+ ' The previous configuration is preserved if the failure occurred before saving, but database, static files or menus may already have changed. Check server logs and backups before retrying.', 'danger');
232
+ } else {
233
+ status.hidden = true;
234
+ progress.hidden = true;
235
+ }
236
+ data.plugins.forEach(function (plugin) {
237
+ document.querySelectorAll('tr[data-plugin]').forEach(function (row) {
238
+ if (row.dataset.plugin === plugin.package) {
239
+ row.querySelector('.plugin-status').textContent = plugin.status;
240
+ var button = row.querySelector('.plugin-change button');
241
+ var enabled = plugin.desired === null ? plugin.running : plugin.desired;
242
+ var label = enabled ? 'Disable' : 'Enable';
243
+ button.value = enabled ? 'disable' : 'enable';
244
+ button.classList.toggle('btn-success', !enabled);
245
+ button.classList.toggle('btn-danger', enabled);
246
+ button.setAttribute('aria-label', label + ' ' + plugin.display_name);
247
+ button.querySelector('i').className = 'fa ' + (enabled ? 'fa-stop' : 'fa-play');
248
+ button.querySelector('span').textContent = label;
249
+ button.dataset.blocked = plugin.warning ? 'true' : 'false';
250
+ row.querySelector('.plugin-warning').textContent = plugin.warning;
251
+ if (!plugin.bundled) {
252
+ var entry = versions[plugin.package];
253
+ if (!entry || entry.installed !== plugin.version) {
254
+ checkVersion(row, plugin.version, enabled);
255
+ } else {
256
+ entry.enabled = enabled;
257
+ renderVersion(row, entry);
258
+ }
259
+ }
260
+ }
261
+ });
262
+ });
263
+ lockActions(pending || awaitingWeb || awaitingConsumer || (job && job.status === 'running'));
264
+ if (manualReload && consumerTimedOut) manualReload.querySelector('button').disabled = pending;
265
+ }
266
+ function fetchStatus(url) {
267
+ return fetch(url, {credentials: 'same-origin', cache: 'no-store'}).then(function (response) {
268
+ if (response.status === 404 && url === statusUrl && alternateStatusUrl) {
269
+ return fetchStatus(alternateStatusUrl);
270
+ }
271
+ if (!response.ok || response.redirected) throw new Error('Status request failed');
272
+ return response.json().then(function (data) {
273
+ if (url === alternateStatusUrl && data.manager_url) {
274
+ window.location.assign(data.manager_url);
275
+ return null;
276
+ }
277
+ return data;
278
+ });
279
+ });
280
+ }
281
+ function poll() {
282
+ fetchStatus(statusUrl)
283
+ .then(function (data) { if (data) update(data); })
284
+ .catch(function () {
285
+ lockActions(true);
286
+ show('Unable to check preparation status. Retrying; actions are disabled until the connection is restored.', 'warning');
287
+ })
288
+ .finally(function () { window.setTimeout(poll, 3000); });
289
+ }
290
+ document.querySelectorAll('.job-submit').forEach(function (form) {
291
+ form.addEventListener('submit', function (event) {
292
+ if (!event.submitter) return;
293
+ if (event.submitter.value === 'update' &&
294
+ !window.confirm('Update this plugin? Database migrations may change data. Ensure you have a current backup.')) {
295
+ event.preventDefault();
296
+ return;
297
+ }
298
+ event.preventDefault();
299
+ var data = new FormData(form);
300
+ data.append('action', event.submitter.value);
301
+ submitError = '';
302
+ pending = true;
303
+ lockActions(true);
304
+ show(event.submitter.value === 'reload' ? 'Requesting process reload. Please wait.' :
305
+ 'Starting preparation. Please wait.', 'info');
306
+ fetch(form.getAttribute('action') || window.location.href, {
307
+ method: 'POST', body: data, credentials: 'same-origin',
308
+ headers: {'X-Requested-With': 'XMLHttpRequest'}
309
+ }).then(function (response) {
310
+ if (response.redirected) throw new Error('Session expired. Sign in again.');
311
+ if (!(response.headers.get('content-type') || '').includes('application/json')) {
312
+ throw new Error('Unexpected response (HTTP ' + response.status + ')');
313
+ }
314
+ return response.json().then(function (data) {
315
+ if (!response.ok) throw new Error(data.error || 'Could not start preparation');
316
+ });
317
+ }).catch(function (error) {
318
+ submitError = error.message;
319
+ show('Could not confirm the operation: ' + submitError + '. Check the status before retrying.', 'danger');
320
+ }).finally(function () { pending = false; });
321
+ });
322
+ });
323
+ document.querySelectorAll('tr[data-plugin][data-bundled="false"]').forEach(function (row) {
324
+ checkVersion(row, row.dataset.version || null, row.dataset.enabled === 'true');
325
+ row.querySelector('.retry-version').addEventListener('click', function () {
326
+ var entry = versions[row.dataset.plugin];
327
+ checkVersion(row, entry.installed, entry.enabled);
328
+ });
329
+ });
330
+ poll();
331
+ }());
332
+ </script>
333
+ {% endblock %}
g3w_plugins/urls.py ADDED
@@ -0,0 +1,11 @@
1
+ from django.urls import path
2
+
3
+ from . import views
4
+
5
+ BASE_URLS = "plugins"
6
+
7
+ urlpatterns = [
8
+ path("", views.index, name="g3w-plugins"),
9
+ path("status/", views.job_status, name="g3w-plugins-status"),
10
+ path("version/", views.latest_version, name="g3w-plugins-version"),
11
+ ]
g3w_plugins/views.py ADDED
@@ -0,0 +1,241 @@
1
+ """Expose superuser plugin actions, status and PyPI version checks."""
2
+
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from functools import lru_cache
5
+ from importlib.metadata import PackageNotFoundError, version
6
+ import json
7
+ import threading
8
+ import time
9
+ from urllib.error import URLError
10
+ from urllib.request import Request, urlopen
11
+
12
+ from django.conf import settings
13
+ from django.apps import apps
14
+ from django.contrib import messages
15
+ from django.contrib.auth.decorators import user_passes_test
16
+ from django.http import JsonResponse
17
+ from django.shortcuts import redirect, render
18
+ from django.urls import reverse
19
+ from django.views.decorators.http import require_http_methods
20
+ from packaging.version import InvalidVersion, Version
21
+
22
+ from . import jobs
23
+ from . import manager
24
+ from .manager import BUNDLED, CATALOG, MANAGED, change, read_state
25
+ from .reload import available, consumer_applied, consumer_enabled, fingerprint, prepare
26
+
27
+
28
+ version_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="plugin-version")
29
+ version_lock = threading.Lock()
30
+ version_checks = {}
31
+
32
+
33
+ @user_passes_test(lambda user: user.is_active and user.is_superuser)
34
+ @require_http_methods(["GET", "POST"])
35
+ def index(request):
36
+ if request.method == "POST":
37
+ name = request.POST.get("plugin", "")
38
+ action = request.POST.get("action", "")
39
+ try:
40
+ if action == "reload":
41
+ jobs.retry_reload()
42
+ elif action in ("enable", "disable", "update"):
43
+ manager.validate_change(name, action != "disable")
44
+ update_version = request.POST.get("version", "") if action == "update" else None
45
+ if action == "update" and not update_version:
46
+ raise ValueError("An update version is required")
47
+ if action == "update" and name not in CATALOG:
48
+ raise ValueError("Only PyPI plugins can be updated here")
49
+ if jobs.available():
50
+ if action == "update":
51
+ jobs.start(name, action, update_version)
52
+ else:
53
+ jobs.start(name, action)
54
+ else:
55
+ if action == "update":
56
+ change(name, True, prepare=prepare, update_version=update_version,
57
+ unmanaged_enabled=CATALOG.get(name) in settings.G3WADMIN_LOCAL_MORE_APPS)
58
+ else:
59
+ change(name, action == "enable", prepare=prepare)
60
+ else:
61
+ raise ValueError("Invalid action")
62
+ except (ValueError, RuntimeError, OSError) as error:
63
+ if request.headers.get("X-Requested-With") == "XMLHttpRequest":
64
+ return JsonResponse({"error": str(error)}, status=400)
65
+ messages.error(request, str(error))
66
+ else:
67
+ if request.headers.get("X-Requested-With") == "XMLHttpRequest":
68
+ return JsonResponse({"ok": True})
69
+ if action == "reload":
70
+ messages.success(request, "Reload requested. Refresh this page after a few seconds.")
71
+ elif jobs.available():
72
+ messages.success(request, "Preparation started.")
73
+ else:
74
+ messages.success(request, "Saved and prepared. Reload G3W-SUITE and its consumer to apply.")
75
+ return redirect("g3w-plugins")
76
+
77
+ status_url = reverse("g3w-plugins-status")
78
+ suffix = "plugins/status/"
79
+ alternate = ""
80
+ if status_url.endswith(suffix):
81
+ prefix = status_url[:-len(suffix)]
82
+ if getattr(settings, "FRONTEND", False) and prefix.endswith("admin/"):
83
+ alternate = prefix[:-len("admin/")] + suffix
84
+ elif not getattr(settings, "FRONTEND", False):
85
+ alternate = prefix + "admin/" + suffix
86
+ job, web_applied, consumer_required, consumer_ready, now = job_context()
87
+ return render(request, "plugins/index.html", {
88
+ "plugins": plugin_status(job, web_applied, now, consumer_required, consumer_ready),
89
+ "reload_available": available(), "job": job, "web_applied": web_applied,
90
+ "consumer_required": consumer_required, "consumer_applied": consumer_ready,
91
+ "status_url": status_url, "alternate_status_url": alternate,
92
+ "version_url": reverse("g3w-plugins-version"),
93
+ })
94
+
95
+
96
+ @lru_cache(maxsize=len(CATALOG))
97
+ def package_version(package):
98
+ try:
99
+ return version(package)
100
+ except PackageNotFoundError:
101
+ return None
102
+
103
+
104
+ def plugin_status(job=None, web_applied=False, now=None, consumer_required=False, consumer_ready=False):
105
+ if now is None:
106
+ now = time.time()
107
+ desired = read_state()["plugins"]
108
+ plugins = [
109
+ {
110
+ "package": package,
111
+ "display_name": f"g3w-admin-{package}" if package in BUNDLED else package,
112
+ "app": app,
113
+ "running": app in settings.G3WADMIN_LOCAL_MORE_APPS,
114
+ "desired": desired.get(package),
115
+ "enabled": desired.get(package, app in settings.G3WADMIN_LOCAL_MORE_APPS),
116
+ "version": package_version(package) if package in CATALOG else None,
117
+ "bundled": package in BUNDLED,
118
+ "warning": (
119
+ "qes requires editing. Disable qes before disabling editing."
120
+ if package == "editing" and desired.get(package, app in settings.G3WADMIN_LOCAL_MORE_APPS)
121
+ and apps.is_installed("qes") else ""
122
+ ),
123
+ }
124
+ for package, app in MANAGED.items()
125
+ ]
126
+ plugins.sort(key=lambda plugin: plugin["display_name"])
127
+ for plugin in plugins:
128
+ plugin["status"] = display_status(plugin, job, web_applied, now, consumer_required, consumer_ready)
129
+ return plugins
130
+
131
+
132
+ def display_status(plugin, job, web_applied, now, consumer_required=False, consumer_ready=False):
133
+ if job and job.get("plugin") == plugin["package"]:
134
+ if job["status"] == "running":
135
+ phases = {
136
+ "install": "Installing packages",
137
+ "migrate": "Applying migrations",
138
+ "collectstatic": "Collecting static files",
139
+ "sitetree_resync_apps": "Updating menus",
140
+ "save": "Saving configuration",
141
+ "reload": "Requesting reload",
142
+ }
143
+ actions = {"enable": "Enabling", "disable": "Disabling", "update": "Updating"}
144
+ return phases.get(job.get("phase"), actions.get(job.get("action"), "Preparing"))
145
+ if job["status"] == "failed":
146
+ return "Operation failed"
147
+ if job["status"] == "reload_failed":
148
+ return "Reload failed"
149
+ if job["status"] == "succeeded" and not web_applied:
150
+ if job.get("reload") == "requested":
151
+ requested_at = job.get("reload_requested_at")
152
+ if requested_at and now - requested_at < 60:
153
+ return "Waiting for web reload"
154
+ return "Reload not confirmed"
155
+ return "Reload required"
156
+ if (job["status"] == "succeeded" and job.get("reload") == "requested"
157
+ and consumer_required and not consumer_ready):
158
+ requested_at = job.get("reload_requested_at")
159
+ if requested_at and now - requested_at < 60:
160
+ return "Waiting for consumer reload"
161
+ return "Consumer reload not confirmed"
162
+ if plugin["desired"] is not None and plugin["desired"] != plugin["running"]:
163
+ return "Enable pending reload" if plugin["desired"] else "Disable pending reload"
164
+ return "Running" if plugin["running"] else "Disabled"
165
+
166
+
167
+ def fetch_latest_version(package):
168
+ req = Request(f"https://pypi.org/pypi/{package}/json",
169
+ headers={"User-Agent": "g3w-admin-plugins"})
170
+ with urlopen(req, timeout=8) as response:
171
+ content = response.read(5 * 1024 * 1024 + 1)
172
+ if len(content) > 5 * 1024 * 1024:
173
+ raise ValueError("PyPI response is too large")
174
+ latest = json.loads(content)["info"]["version"]
175
+ newest = Version(latest)
176
+ if newest.is_prerelease or newest.is_devrelease:
177
+ raise ValueError("PyPI did not return a stable release")
178
+ return latest
179
+
180
+
181
+ @user_passes_test(lambda user: user.is_active and user.is_superuser)
182
+ @require_http_methods(["GET"])
183
+ def latest_version(request):
184
+ package = request.GET.get("plugin", "")
185
+ if package not in CATALOG:
186
+ return JsonResponse({"error": "Unknown plugin"}, status=400)
187
+ installed = package_version(package)
188
+ with version_lock:
189
+ entry = version_checks.get(package)
190
+ if not entry or (entry[0].done() and time.monotonic() - entry[1] > 300):
191
+ entry = (version_executor.submit(fetch_latest_version, package), time.monotonic())
192
+ version_checks[package] = entry
193
+ future = entry[0]
194
+ if not future.done():
195
+ response = JsonResponse({"status": "checking"}, status=202)
196
+ response["Cache-Control"] = "no-store"
197
+ return response
198
+ try:
199
+ latest = future.result()
200
+ newest = Version(latest)
201
+ current = Version(installed) if installed else None
202
+ except (OSError, URLError, ValueError, KeyError, TypeError) as error:
203
+ with version_lock:
204
+ if version_checks.get(package) is entry:
205
+ del version_checks[package]
206
+ return JsonResponse({"error": f"Could not check PyPI: {error}"}, status=502)
207
+ response = JsonResponse({"installed": installed, "latest": latest,
208
+ "available": current is not None and newest > current})
209
+ response["Cache-Control"] = "no-store"
210
+ return response
211
+
212
+
213
+ def job_context():
214
+ job = jobs.status()
215
+ now = time.time()
216
+ target = job.get("target") if job else None
217
+ if job and job["status"] == "succeeded" and "reload" not in job:
218
+ target = fingerprint(read_state())
219
+ web_applied = bool(
220
+ target and manager.configured_state is not None
221
+ and fingerprint(manager.configured_state) == target
222
+ )
223
+ consumer_required = consumer_enabled()
224
+ consumer_ready = bool(
225
+ consumer_required and job and job.get("reload") == "requested"
226
+ and consumer_applied(target, job.get("reload_requested_at"), now)
227
+ )
228
+ return job, web_applied, consumer_required, consumer_ready, now
229
+
230
+
231
+ @user_passes_test(lambda user: user.is_active and user.is_superuser)
232
+ @require_http_methods(["GET"])
233
+ def job_status(request):
234
+ job, web_applied, consumer_required, consumer_ready, now = job_context()
235
+ response = JsonResponse({
236
+ "job": job, "plugins": plugin_status(job, web_applied, now, consumer_required, consumer_ready),
237
+ "web_applied": web_applied, "consumer_required": consumer_required, "consumer_applied": consumer_ready,
238
+ "manager_url": reverse("g3w-plugins"), "server_time": now,
239
+ })
240
+ response["Cache-Control"] = "no-store"
241
+ return response