pyca 4.6__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.
pyca/ui/static/app.js ADDED
@@ -0,0 +1,324 @@
1
+ // pyCA web interface
2
+ //
3
+ // Loads the state of the capture agent from the JSON API and renders it. The
4
+ // data is reloaded every `refresh` seconds (URL parameter, default: 10).
5
+
6
+ // Icons from Font Awesome Free (https://fontawesome.com), CC BY 4.0 License
7
+ const ICONS = {
8
+ 'exclamation-triangle': 'M256 0c14.7 0 28.2 8.1 35.2 21l216 400c6.7 12.4 6.4 27.4-.8 39.5S486.1 480 472 480L40 480c-14.1 0-27.2-7.4-34.4-19.5s-7.5-27.1-.8-39.5l216-400c7-12.9 20.5-21 35.2-21zm0 352a32 32 0 1 0 0 64 32 32 0 1 0 0-64zm0-192c-18.2 0-32.7 15.5-31.4 33.7l7.4 104c.9 12.5 11.4 22.3 23.9 22.3 12.6 0 23-9.7 23.9-22.3l7.4-104c1.3-18.2-13.1-33.7-31.4-33.7z',
9
+ 'sync': 'M65.9 228.5c13.3-93 93.4-164.5 190.1-164.5 53 0 101 21.5 135.8 56.2 .2 .2 .4 .4 .6 .6l7.6 7.2-47.9 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l128 0c17.7 0 32-14.3 32-32l0-128c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 53.4-11.3-10.7C390.5 28.6 326.5 0 256 0 127 0 20.3 95.4 2.6 219.5 .1 237 12.2 253.2 29.7 255.7s33.7-9.7 36.2-27.1zm443.5 64c2.5-17.5-9.7-33.7-27.1-36.2s-33.7 9.7-36.2 27.1c-13.3 93-93.4 164.5-190.1 164.5-53 0-101-21.5-135.8-56.2-.2-.2-.4-.4-.6-.6l-7.6-7.2 47.9 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L32 320c-8.5 0-16.7 3.4-22.7 9.5S-.1 343.7 0 352.3l1 127c.1 17.7 14.6 31.9 32.3 31.7S65.2 496.4 65 478.7l-.4-51.5 10.7 10.1c46.3 46.1 110.2 74.7 180.7 74.7 129 0 235.7-95.4 253.4-219.5z',
10
+ };
11
+
12
+ const ERROR_STATES = ['partial recording', 'failed recording'];
13
+ const RETRY_STATES = ['failed uploading', 'paused after recording'];
14
+
15
+ // Terminal color codes, e.g. in log lines of the development server
16
+ const ANSI_CODES = new RegExp(String.fromCharCode(27) + '\\[[0-9;]*m', 'g');
17
+
18
+ // Number of events to show and how many more to show on request
19
+ const state = {
20
+ limit_upcoming: 5,
21
+ limit_processed: 15,
22
+ upcoming: [],
23
+ recorded: [],
24
+ // IDs of events with a pending retry request
25
+ pending: new Set(),
26
+ };
27
+
28
+ // Create an element with attributes and children (elements or strings).
29
+ function el(tag, attributes = {}, ...children) {
30
+ const element = document.createElement(tag);
31
+ for (const [key, value] of Object.entries(attributes)) {
32
+ element.setAttribute(key, value);
33
+ }
34
+ element.append(...children);
35
+ return element;
36
+ }
37
+
38
+ function icon(name, spin = false) {
39
+ const ns = 'http://www.w3.org/2000/svg';
40
+ const svg = document.createElementNS(ns, 'svg');
41
+ svg.setAttribute('class', spin ? 'icon spin' : 'icon');
42
+ svg.setAttribute('viewBox', '0 0 512 512');
43
+ svg.setAttribute('role', 'img');
44
+ svg.setAttribute('aria-hidden', 'true');
45
+ const path = document.createElementNS(ns, 'path');
46
+ path.setAttribute('fill', 'currentColor');
47
+ path.setAttribute('d', ICONS[name]);
48
+ svg.append(path);
49
+ return svg;
50
+ }
51
+
52
+ // Format a number of bytes with a suitable unit.
53
+ function format_bytes(bytes) {
54
+ if (bytes === 0) return '0 Bytes';
55
+
56
+ const k = 1024;
57
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
58
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
59
+
60
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
61
+ }
62
+
63
+ function format_time(seconds) {
64
+ return new Date(seconds * 1000).toLocaleString();
65
+ }
66
+
67
+ async function get(path) {
68
+ const response = await fetch(path);
69
+ if (!response.ok) {
70
+ throw new Error(`Request to ${path} failed: ${response.status}`);
71
+ }
72
+ return response.json();
73
+ }
74
+
75
+ function update_name(response) {
76
+ document.getElementById('name').textContent = response.meta.name;
77
+ }
78
+
79
+ function update_services(response) {
80
+ const set = (id, busy, text) => {
81
+ const element = document.getElementById(id);
82
+ element.textContent = busy ? text : 'Idle';
83
+ element.className = busy ? 'active' : 'inactive';
84
+ };
85
+ set('capture', response.meta.services.capture === 'busy', 'Recording');
86
+ set('upload', response.meta.services.ingest === 'busy', 'Uploading');
87
+ }
88
+
89
+ function update_events(response) {
90
+ state.recorded = response.data.filter(x => x.attributes.status !== 'upcoming');
91
+ // An event being recorded is still listed as upcoming event as well
92
+ const in_processing = state.recorded.length ? state.recorded[0].id : null;
93
+ state.upcoming = response.data
94
+ .filter(x => x.attributes.status === 'upcoming')
95
+ .filter(x => x.id !== in_processing);
96
+ document.getElementById('upcoming').textContent = state.upcoming.length;
97
+ document.getElementById('processed').textContent = state.recorded.length;
98
+ render_events();
99
+ }
100
+
101
+ function more_row(text, on_click) {
102
+ const button = el('button', { type: 'button' }, text);
103
+ button.addEventListener('click', on_click);
104
+ return el('tr', { class: 'extendlist' },
105
+ el('td', { colspan: 4, class: 'more' }, button));
106
+ }
107
+
108
+ function event_row(event) {
109
+ const pending = state.pending.has(event.id);
110
+ const status = pending ? 'action pending' : event.attributes.status;
111
+ const status_cell = el('div', { class: 'event_status' }, status);
112
+ if (ERROR_STATES.includes(status)) {
113
+ status_cell.append(el('span', { class: 'warning' },
114
+ icon('exclamation-triangle')));
115
+ }
116
+ if (pending || RETRY_STATES.includes(status)) {
117
+ const button = el('button', {
118
+ type: 'button',
119
+ class: 'action',
120
+ title: 'Retry upload',
121
+ }, icon('sync', pending));
122
+ button.addEventListener('click', () => retry_ingest(event));
123
+ status_cell.append(button);
124
+ }
125
+ const title = event.attributes.title;
126
+ return el('tr', {},
127
+ el('td', { class: 'title', title: title }, title),
128
+ el('td', {}, format_time(event.attributes.start)),
129
+ el('td', {}, format_time(event.attributes.end)),
130
+ el('td', {}, status_cell));
131
+ }
132
+
133
+ function render_events() {
134
+ const rows = [];
135
+ if (state.upcoming.length > state.limit_upcoming) {
136
+ rows.push(more_row('more upcoming events…', () => {
137
+ state.limit_upcoming += 5;
138
+ render_events();
139
+ }));
140
+ }
141
+ rows.push(...state.upcoming.slice(0, state.limit_upcoming).map(event_row));
142
+ rows.push(...state.recorded.slice(0, state.limit_processed).map(event_row));
143
+ if (state.recorded.length > state.limit_processed) {
144
+ rows.push(more_row('more recorded events…', () => {
145
+ state.limit_processed += 5;
146
+ render_events();
147
+ }));
148
+ }
149
+ document.getElementById('events').replaceChildren(...rows);
150
+ }
151
+
152
+ async function retry_ingest(event) {
153
+ if (state.pending.has(event.id)) {
154
+ return;
155
+ }
156
+ state.pending.add(event.id);
157
+ render_events();
158
+ try {
159
+ const response = await fetch('/api/events/' + event.id, {
160
+ method: 'PATCH',
161
+ headers: { 'Content-Type': 'application/vnd.api+json' },
162
+ body: JSON.stringify({
163
+ data: [{
164
+ attributes: { status: 'finished recording' },
165
+ id: event.id,
166
+ type: 'event',
167
+ }]
168
+ }),
169
+ });
170
+ if (!response.ok) {
171
+ throw new Error(`Retry failed: ${response.status}`);
172
+ }
173
+ event.attributes.status = 'finished recording';
174
+ } catch (error) {
175
+ console.error(error);
176
+ } finally {
177
+ state.pending.delete(event.id);
178
+ render_events();
179
+ }
180
+ }
181
+
182
+ function update_previews(response) {
183
+ const container = document.getElementById('preview-images');
184
+ const images = response.data.map(x => {
185
+ const src = `/img/${x.attributes.id}?${Date.now()}`;
186
+ return el('img', { src: src, alt: `Preview image ${x.id}` });
187
+ });
188
+ container.replaceChildren(...images);
189
+ document.getElementById('no-preview').hidden = images.length > 0;
190
+ }
191
+
192
+ function metric_group(header, metrics) {
193
+ return el('tbody', {},
194
+ el('tr', {}, el('th', { colspan: 2 }, header)),
195
+ ...metrics.map(([name, value]) =>
196
+ el('tr', {}, el('td', {}, name), el('td', {}, value))));
197
+ }
198
+
199
+ function update_metrics(response) {
200
+ const meta = response.meta;
201
+ const groups = [];
202
+
203
+ const machine = [];
204
+ if (meta.load) {
205
+ const load = meta.load;
206
+ machine.push(['Load Averages', `${load['1m']} ${load['5m']} ${load['15m']}`]);
207
+ }
208
+ const disk = meta.disk_usage_in_bytes;
209
+ if (disk) {
210
+ const used = (disk.used / disk.total) * 100;
211
+ machine.push(['Disk Usage',
212
+ `${used.toFixed(0)}% (${format_bytes(disk.free)} free)`]);
213
+ }
214
+ const memory = meta.memory_usage_in_bytes;
215
+ if (memory) {
216
+ const used = (memory.used / memory.total) * 100;
217
+ let value = `${used.toFixed(0)}% (${format_bytes(memory.free)} free`;
218
+ // Buffers and cache are not available on all systems
219
+ if (memory.buffers !== null || memory.cached !== null) {
220
+ const cached = (memory.buffers || 0) + (memory.cached || 0);
221
+ value += `, ${format_bytes(cached)} buffers/cached`;
222
+ }
223
+ machine.push(['Memory Usage', value + ')']);
224
+ }
225
+ if (machine.length) {
226
+ groups.push(metric_group('Machine', machine));
227
+ }
228
+
229
+ if (meta.services.length) {
230
+ groups.push(metric_group('Services', meta.services.map(service => [
231
+ service.name[0].toUpperCase() + service.name.slice(1),
232
+ service.status,
233
+ ])));
234
+ }
235
+
236
+ // The time of the last update is in UTC but without time zone
237
+ let last_synchronized = meta.upstream.last_synchronized;
238
+ if (last_synchronized) {
239
+ if (!/(Z|[+-]\d\d:?\d\d)$/.test(last_synchronized)) {
240
+ last_synchronized += 'Z';
241
+ }
242
+ last_synchronized = new Date(last_synchronized).toLocaleString();
243
+ }
244
+ groups.push(metric_group('Upstream',
245
+ [['Last Schedule Update', last_synchronized || 'never']]));
246
+
247
+ document.getElementById('metrics').replaceChildren(...groups);
248
+ }
249
+
250
+ async function update_logs() {
251
+ const response = await fetch('/api/logs');
252
+ // Logs are disabled if there is no log command
253
+ if (response.status === 404) {
254
+ document.getElementById('logs').hidden = true;
255
+ return;
256
+ }
257
+ if (!response.ok) {
258
+ throw new Error(`Request to /api/logs failed: ${response.status}`);
259
+ }
260
+ const lines = (await response.json()).data[0].attributes.lines;
261
+ const section = document.getElementById('logs');
262
+ section.querySelector('pre').textContent = lines
263
+ .map(line => line.replace(ANSI_CODES, ''))
264
+ .join('\n');
265
+ section.hidden = lines.length === 0;
266
+ }
267
+
268
+ // Load all data from the backend and update the page.
269
+ function update() {
270
+ const updates = [
271
+ get('/api/name').then(update_name),
272
+ get('/api/services').then(update_services),
273
+ get('/api/events').then(update_events),
274
+ get('/api/previews').then(update_previews),
275
+ get('/api/metrics').then(update_metrics),
276
+ update_logs(),
277
+ ];
278
+ return Promise.allSettled(updates).then(results => {
279
+ results
280
+ .filter(result => result.status === 'rejected')
281
+ .forEach(result => console.error(result.reason));
282
+ });
283
+ }
284
+
285
+ async function schedule(event) {
286
+ event.preventDefault();
287
+ const form = event.target;
288
+ const scheduling = document.getElementById('scheduling');
289
+ form.hidden = true;
290
+ scheduling.hidden = false;
291
+ try {
292
+ const response = await fetch('/api/schedule', {
293
+ method: 'POST',
294
+ headers: { 'Content-Type': 'application/vnd.api+json' },
295
+ body: JSON.stringify({
296
+ data: [{
297
+ title: form.elements.title.value,
298
+ creator: form.elements.creator.value,
299
+ duration: Math.round(form.elements.duration.valueAsNumber * 60),
300
+ }]
301
+ }),
302
+ });
303
+ if (response.status === 409) {
304
+ alert('Conflict: A scheduled recording exists during this time.');
305
+ } else if (!response.ok) {
306
+ throw new Error(`Scheduling failed: ${response.status}`);
307
+ }
308
+ } catch (error) {
309
+ console.error(error);
310
+ } finally {
311
+ form.hidden = false;
312
+ scheduling.hidden = true;
313
+ }
314
+ }
315
+
316
+ document.getElementById('schedule').addEventListener('submit', schedule);
317
+
318
+ // Reload the data periodically. Wait for one update to finish before
319
+ // scheduling the next one so that slow requests do not pile up.
320
+ const refresh = new URLSearchParams(window.location.search).get('refresh') || 10;
321
+ (async function loop() {
322
+ await update();
323
+ setTimeout(loop, refresh * 1000);
324
+ })();
@@ -0,0 +1,107 @@
1
+ <!doctype html>
2
+ <html lang=en>
3
+
4
+ <head>
5
+ <meta charset=utf-8>
6
+ <meta name=viewport content="width=device-width, initial-scale=1">
7
+ <title>pyCA</title>
8
+ <link rel=stylesheet href="style.css">
9
+ <script type=module src="app.js"></script>
10
+ </head>
11
+
12
+ <body>
13
+ <header class=center>
14
+ <a href="/">pyCA</a>
15
+ </header>
16
+
17
+ <h1>
18
+ <span class=center>Capture Agent “<span id=name></span>”</span>
19
+ </h1>
20
+
21
+ <div class=summary>
22
+ <div id=status class=center>
23
+ <div>
24
+ <div>Capture</div>
25
+ <div id=capture class=inactive>Idle</div>
26
+ </div>
27
+
28
+ <div>
29
+ <div>Upload</div>
30
+ <div id=upload class=inactive>Idle</div>
31
+ </div>
32
+
33
+ <div>
34
+ <div>Upcoming</div>
35
+ <div id=upcoming class=inactive></div>
36
+ </div>
37
+
38
+ <div>
39
+ <div>Processed</div>
40
+ <div id=processed class=inactive></div>
41
+ </div>
42
+ </div>
43
+ </div>
44
+
45
+ <main class=center>
46
+
47
+ <section id=preview>
48
+ <h2>Preview Images</h2>
49
+ <div id=preview-images></div>
50
+ <div id=no-preview>No preview image</div>
51
+ </section>
52
+
53
+ <section id=recordings>
54
+ <h2>Recordings</h2>
55
+ <div class=table-wrapper>
56
+ <table>
57
+ <thead>
58
+ <tr>
59
+ <th>Title</th>
60
+ <th>Start</th>
61
+ <th>End</th>
62
+ <th>Status</th>
63
+ </tr>
64
+ </thead>
65
+ <tbody id=events></tbody>
66
+ </table>
67
+ </div>
68
+ </section>
69
+
70
+ <section>
71
+ <h2>Status</h2>
72
+ <table id=metrics></table>
73
+ </section>
74
+
75
+ <section id=logs hidden>
76
+ <h2>Logs</h2>
77
+ <div class=logs>
78
+ <pre></pre>
79
+ </div>
80
+ </section>
81
+
82
+ <section>
83
+ <h2 id=_schedule>Start Recording</h2>
84
+ <div>
85
+ Schedule a recording on this capture agent for right now.
86
+ The maximum time before the recording actually starts
87
+ depends on the capture agent's update frequency. It should
88
+ start with the next update.
89
+ </div>
90
+ <form id=schedule>
91
+ <label for=title>Title</label>
92
+ <input id=title type=text placeholder='pyCA Recording' value='pyCA Recording' required>
93
+ <br>
94
+ <label for=creator>Creator</label>
95
+ <input id=creator type=text placeholder=Administrator value=Administrator required>
96
+ <br>
97
+ <label for=duration>Duration (min)</label>
98
+ <input id=duration type=number min=1 placeholder=30 value=5 required>
99
+ <br>
100
+ <input type=submit value=Start>
101
+ </form>
102
+ <div id=scheduling hidden>Event is being scheduled…</div>
103
+ </section>
104
+ </main>
105
+ </body>
106
+
107
+ </html>
@@ -0,0 +1,208 @@
1
+ body {
2
+ font-family: "Open Sans", Helvetica, sans-serif;
3
+ font-size: 14px;
4
+ padding: 0px;
5
+ margin: 0px;
6
+ }
7
+
8
+ .center {
9
+ max-width: 800px;
10
+ margin: 0 auto;
11
+ }
12
+
13
+ /* Topmost: pyCA */
14
+ header {
15
+ font-size: 20px;
16
+ font-weight: bold;
17
+ padding: 24px;
18
+ }
19
+
20
+ header a {
21
+ color: black;
22
+ display: block;
23
+ text-decoration: none;
24
+ }
25
+
26
+ /* Second from top: agent name */
27
+ h1 {
28
+ background-color: #2075b1;
29
+ color: white;
30
+ font-size: 16px;
31
+ padding: 16px;
32
+ margin: 0;
33
+ }
34
+
35
+ h1 .center {
36
+ display: block;
37
+ }
38
+
39
+ /* Third from top: Stats */
40
+ .summary {
41
+ padding: 10px 20px;
42
+ background-color: #24425c;
43
+ color: white;
44
+ margin-bottom: 10px;
45
+ }
46
+
47
+ #status {
48
+ text-align: center;
49
+ }
50
+
51
+ #status > div {
52
+ display: inline-block;
53
+ min-width: 90px;
54
+ height: 75px;
55
+ margin: 5px;
56
+ padding: 20px;
57
+ vertical-align: middle;
58
+ }
59
+
60
+ #status > div > div {
61
+ padding: 10px;
62
+ }
63
+
64
+ #stats span {
65
+ display: inline-block;
66
+ min-width: 30px;
67
+ }
68
+
69
+ #status .active, #status .inactive {
70
+ font-size: x-large;
71
+ border-top: 1px solid gray;
72
+ }
73
+
74
+ #status .inactive {
75
+ color: gray;
76
+ }
77
+
78
+ main {
79
+ padding: 20px;
80
+ }
81
+
82
+ table {
83
+ width: 100%;
84
+ border-spacing: 0;
85
+ border-collapse: collapse;
86
+ }
87
+
88
+ th {
89
+ font-weight: bold;
90
+ background-color: #eee;
91
+ }
92
+
93
+ td, th {
94
+ text-align: left;
95
+ padding: 10px;
96
+ border: 1px solid silver;
97
+ border-radius: 4px;
98
+ margin: 0;
99
+ }
100
+
101
+ tr.extendlist a {
102
+ display: block;
103
+ text-decoration: none;
104
+ }
105
+
106
+ tr.extendlist td {
107
+ padding: 5px 10px;
108
+ text-align: center;
109
+ }
110
+
111
+ td.more {
112
+ padding: 0;
113
+ }
114
+
115
+ td.more button {
116
+ width: 100%;
117
+ padding: 5px 10px;
118
+ border: none;
119
+ background: none;
120
+ font: inherit;
121
+ font-style: italic;
122
+ cursor: pointer;
123
+ }
124
+
125
+ td.more button:hover {
126
+ background-color: #eee;
127
+ }
128
+
129
+ div.table-wrapper {
130
+ overflow-x: auto;
131
+ }
132
+
133
+ td.title {
134
+ max-width: 150px;
135
+ white-space: nowrap;
136
+ overflow: hidden;
137
+ text-overflow: ellipsis;
138
+ }
139
+
140
+ div.logs {
141
+ width: 100%;
142
+ overflow-x: scroll;
143
+ border: 1px solid silver;
144
+ }
145
+
146
+ div.logs pre {
147
+ white-space: pre;
148
+ padding: 10px;
149
+ font-family: sans;
150
+ }
151
+
152
+ form#schedule {
153
+ padding: 20px;
154
+ }
155
+
156
+ form#schedule label {
157
+ display: inline-block;
158
+ width: 120px;
159
+ margin: 10px;
160
+ }
161
+
162
+ form#schedule input[type=submit] {
163
+ margin-left: 140px;
164
+ }
165
+
166
+ div.event_status {
167
+ display: flex;
168
+ justify-content: space-between;
169
+ }
170
+
171
+ div.event_status .warning {
172
+ color: red;
173
+ }
174
+
175
+ div.event_status button.action {
176
+ padding: 0;
177
+ border: none;
178
+ background: none;
179
+ color: inherit;
180
+ cursor: pointer;
181
+ }
182
+
183
+ #preview img {
184
+ max-width: 90%;
185
+ max-height: 300px;
186
+ }
187
+
188
+ #scheduling {
189
+ color: green;
190
+ padding: 15px;
191
+ }
192
+
193
+ svg.icon {
194
+ display: inline-block;
195
+ height: 1em;
196
+ overflow: visible;
197
+ vertical-align: -0.125em;
198
+ }
199
+
200
+ svg.spin {
201
+ animation: spin 2s linear infinite;
202
+ }
203
+
204
+ @keyframes spin {
205
+ to {
206
+ transform: rotate(360deg);
207
+ }
208
+ }
pyca/ui/utils.py ADDED
@@ -0,0 +1,35 @@
1
+ # -*- coding: utf-8 -*-
2
+ '''
3
+ Helper methods used for the web interface.
4
+ '''
5
+
6
+ from functools import wraps
7
+ from flask import request, Response
8
+ from pyca.config import config
9
+
10
+
11
+ def requires_auth(f):
12
+ @wraps(f)
13
+ def decorated(*args, **kwargs):
14
+ headers = {'WWW-Authenticate': 'Basic realm="pyCA Login"'}
15
+ auth = request.authorization
16
+ if config('ui', 'password'):
17
+ auth_provided = (auth.username, auth.password) if auth else None
18
+ auth_expected = config('ui', 'username'), config('ui', 'password')
19
+ if auth_provided != auth_expected:
20
+ return Response('pyCA: Login required\n', 401, headers)
21
+ return f(*args, **kwargs)
22
+ return decorated
23
+
24
+
25
+ def jsonapi_mediatype(f):
26
+ @wraps(f)
27
+ def decorated(*args, **kwargs):
28
+ if request.headers.get('Content-Type') != 'application/vnd.api+json'\
29
+ and request.method != 'GET':
30
+ return Response('Unsupported Media Type '
31
+ '(expected: application/vnd.api+json)', 415)
32
+ response = f(*args, **kwargs)
33
+ response.headers['Content-Type'] = 'application/vnd.api+json'
34
+ return response
35
+ return decorated