-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpodcast.zig
1687 lines (1412 loc) · 70.5 KB
/
podcast.zig
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const dvui = @import("dvui");
const Backend = dvui.backend;
const sqlite = @import("sqlite");
pub const c = @cImport({
@cDefine("_XOPEN_SOURCE", "1");
@cInclude("time.h");
@cInclude("locale.h");
@cInclude("curl/curl.h");
@cInclude("libxml/parser.h");
@cDefine("LIBXML_XPATH_ENABLED", "1");
@cInclude("libxml/xpath.h");
@cInclude("libxml/xpathInternals.h");
@cInclude("libavformat/avformat.h");
@cInclude("libavcodec/avcodec.h");
@cInclude("libavfilter/avfilter.h");
@cInclude("libavfilter/buffersink.h");
@cInclude("libavfilter/buffersrc.h");
@cInclude("libavutil/opt.h");
});
// when set to true:
// - looks for url-{hash}.xml file instead of fetching feed from network
// - doesn't download episodes
const DEBUG = false;
var gpa_instance = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = gpa_instance.allocator();
const db_name = "podcast-db.sqlite3";
var g_db: ?sqlite.Db = null;
var g_arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const g_arena = g_arena_allocator.allocator();
var g_quit = false;
var g_win: dvui.Window = undefined;
var g_podcast_id_on_right: usize = 0;
// protected by bgtask_mutex
var bgtask_mutex = std.Thread.Mutex{};
var bgtask_condition = std.Thread.Condition{};
var bgtasks: std.ArrayList(Task) = undefined;
const Task = struct {
kind: enum {
update_feed,
download_episode,
},
rowid: u32,
cancel: bool = false,
};
const Episode = struct {
const query_base = "SELECT rowid, podcast_id, title, description, enclosure_url, position, duration, pubDate FROM episode";
const query_one = query_base ++ " WHERE rowid = ?";
const query_all = query_base ++ " WHERE podcast_id = ? ORDER BY pubDate DESC";
rowid: usize,
podcast_id: usize,
title: []const u8,
description: []const u8,
enclosure_url: []const u8,
position: f64,
duration: f64,
pubDate: usize,
};
fn dbErrorCallafter(id: u32, response: dvui.enums.DialogResponse) dvui.Error!void {
_ = id;
_ = response;
g_quit = true;
}
fn dbError(comptime fmt: []const u8, args: anytype) !void {
var buf: [512]u8 = undefined;
const msg = std.fmt.bufPrint(&buf, fmt, args) catch "fmt.bufPrint error";
try dvui.dialog(@src(), .{ .window = &g_win, .title = "DB Error", .message = msg, .callafterFn = dbErrorCallafter });
}
fn dbRow(arena: std.mem.Allocator, comptime query: []const u8, comptime return_type: type, values: anytype) !?return_type {
if (g_db) |*db| {
var stmt = db.prepare(query) catch {
try dbError("{}\n\npreparing statement:\n\n{s}", .{ db.getDetailedError(), query });
return error.DB_ERROR;
};
defer stmt.deinit();
const row = stmt.oneAlloc(return_type, arena, .{}, values) catch {
try dbError("{}\n\nexecuting statement:\n\n{s}", .{ db.getDetailedError(), query });
return error.DB_ERROR;
};
return row;
}
return null;
}
fn dbInit(arena: std.mem.Allocator) !void {
g_db = sqlite.Db.init(.{
.mode = sqlite.Db.Mode{ .File = db_name },
.open_flags = .{
.write = true,
.create = true,
},
}) catch |err| {
try dbError("Can't open/create db:\n{s}\n{}", .{ db_name, err });
return error.DB_ERROR;
};
_ = try dbRow(arena, "CREATE TABLE IF NOT EXISTS 'schema' (version INTEGER)", u8, .{});
if (try dbRow(arena, "SELECT version FROM schema", u32, .{})) |version| {
if (version != 1) {
try dbError("{s}\n\nbad schema version: {d}", .{ db_name, version });
return error.DB_ERROR;
}
} else {
// new database
_ = try dbRow(arena, "INSERT INTO schema (version) VALUES (1)", u8, .{});
_ = try dbRow(arena, "CREATE TABLE podcast (url TEXT, title TEXT, description TEXT, copyright TEXT, pubDate INTEGER, lastBuildDate TEXT, link TEXT, image_url TEXT, speed REAL)", u8, .{});
_ = try dbRow(arena, "CREATE TABLE episode (podcast_id INTEGER, visible INTEGER DEFAULT 1, guid TEXT, title TEXT, description TEXT, pubDate INTEGER, enclosure_url TEXT, position REAL, duration REAL)", u8, .{});
_ = try dbRow(arena, "CREATE TABLE player (episode_id INTEGER)", u8, .{});
_ = try dbRow(arena, "INSERT INTO player (episode_id) values (0)", u8, .{});
}
}
pub fn getContent(xpathCtx: *c.xmlXPathContext, node_name: [:0]const u8, attr_name: ?[:0]const u8) ?[]u8 {
const xpathObj = c.xmlXPathEval(node_name.ptr, xpathCtx);
defer c.xmlXPathFreeObject(xpathObj);
if (xpathObj.*.nodesetval.*.nodeNr >= 1) {
if (attr_name) |attr| {
const data = c.xmlGetProp(xpathObj.*.nodesetval.*.nodeTab[0], attr.ptr);
return std.mem.sliceTo(data, 0);
} else {
return std.mem.sliceTo(xpathObj.*.nodesetval.*.nodeTab[0].*.children.*.content, 0);
}
}
return null;
}
fn tryCurl(code: c.CURLcode) !void {
if (code != c.CURLE_OK)
return errorFromCurl(code);
}
fn errorFromCurl(code: c.CURLcode) !void {
return switch (code) {
c.CURLE_UNSUPPORTED_PROTOCOL => error.UnsupportedProtocol,
c.CURLE_FAILED_INIT => error.FailedInit,
c.CURLE_URL_MALFORMAT => error.UrlMalformat,
c.CURLE_NOT_BUILT_IN => error.NotBuiltIn,
c.CURLE_COULDNT_RESOLVE_PROXY => error.CouldntResolveProxy,
c.CURLE_COULDNT_RESOLVE_HOST => error.CouldntResolveHost,
c.CURLE_COULDNT_CONNECT => error.CounldntConnect,
c.CURLE_WEIRD_SERVER_REPLY => error.WeirdServerReply,
c.CURLE_REMOTE_ACCESS_DENIED => error.RemoteAccessDenied,
c.CURLE_FTP_ACCEPT_FAILED => error.FtpAcceptFailed,
c.CURLE_FTP_WEIRD_PASS_REPLY => error.FtpWeirdPassReply,
c.CURLE_FTP_ACCEPT_TIMEOUT => error.FtpAcceptTimeout,
c.CURLE_FTP_WEIRD_PASV_REPLY => error.FtpWeirdPasvReply,
c.CURLE_FTP_WEIRD_227_FORMAT => error.FtpWeird227Format,
c.CURLE_FTP_CANT_GET_HOST => error.FtpCantGetHost,
c.CURLE_HTTP2 => error.Http2,
c.CURLE_FTP_COULDNT_SET_TYPE => error.FtpCouldntSetType,
c.CURLE_PARTIAL_FILE => error.PartialFile,
c.CURLE_FTP_COULDNT_RETR_FILE => error.FtpCouldntRetrFile,
c.CURLE_OBSOLETE20 => error.Obsolete20,
c.CURLE_QUOTE_ERROR => error.QuoteError,
c.CURLE_HTTP_RETURNED_ERROR => error.HttpReturnedError,
c.CURLE_WRITE_ERROR => error.WriteError,
c.CURLE_OBSOLETE24 => error.Obsolete24,
c.CURLE_UPLOAD_FAILED => error.UploadFailed,
c.CURLE_READ_ERROR => error.ReadError,
c.CURLE_OUT_OF_MEMORY => error.OutOfMemory,
c.CURLE_OPERATION_TIMEDOUT => error.OperationTimeout,
c.CURLE_OBSOLETE29 => error.Obsolete29,
c.CURLE_FTP_PORT_FAILED => error.FtpPortFailed,
c.CURLE_FTP_COULDNT_USE_REST => error.FtpCouldntUseRest,
c.CURLE_OBSOLETE32 => error.Obsolete32,
c.CURLE_RANGE_ERROR => error.RangeError,
c.CURLE_HTTP_POST_ERROR => error.HttpPostError,
c.CURLE_SSL_CONNECT_ERROR => error.SslConnectError,
c.CURLE_BAD_DOWNLOAD_RESUME => error.BadDownloadResume,
c.CURLE_FILE_COULDNT_READ_FILE => error.FileCouldntReadFile,
c.CURLE_LDAP_CANNOT_BIND => error.LdapCannotBind,
c.CURLE_LDAP_SEARCH_FAILED => error.LdapSearchFailed,
c.CURLE_OBSOLETE40 => error.Obsolete40,
c.CURLE_FUNCTION_NOT_FOUND => error.FunctionNotFound,
c.CURLE_ABORTED_BY_CALLBACK => error.AbortByCallback,
c.CURLE_BAD_FUNCTION_ARGUMENT => error.BadFunctionArgument,
c.CURLE_OBSOLETE44 => error.Obsolete44,
c.CURLE_INTERFACE_FAILED => error.InterfaceFailed,
c.CURLE_OBSOLETE46 => error.Obsolete46,
c.CURLE_TOO_MANY_REDIRECTS => error.TooManyRedirects,
c.CURLE_UNKNOWN_OPTION => error.UnknownOption,
c.CURLE_SETOPT_OPTION_SYNTAX => error.SetoptOptionSyntax,
c.CURLE_OBSOLETE50 => error.Obsolete50,
c.CURLE_OBSOLETE51 => error.Obsolete51,
c.CURLE_GOT_NOTHING => error.GotNothing,
c.CURLE_SSL_ENGINE_NOTFOUND => error.SslEngineNotfound,
c.CURLE_SSL_ENGINE_SETFAILED => error.SslEngineSetfailed,
c.CURLE_SEND_ERROR => error.SendError,
c.CURLE_RECV_ERROR => error.RecvError,
c.CURLE_OBSOLETE57 => error.Obsolete57,
c.CURLE_SSL_CERTPROBLEM => error.SslCertproblem,
c.CURLE_SSL_CIPHER => error.SslCipher,
c.CURLE_PEER_FAILED_VERIFICATION => error.PeerFailedVerification,
c.CURLE_BAD_CONTENT_ENCODING => error.BadContentEncoding,
c.CURLE_LDAP_INVALID_URL => error.LdapInvalidUrl,
c.CURLE_FILESIZE_EXCEEDED => error.FilesizeExceeded,
c.CURLE_USE_SSL_FAILED => error.UseSslFailed,
c.CURLE_SEND_FAIL_REWIND => error.SendFailRewind,
c.CURLE_SSL_ENGINE_INITFAILED => error.SslEngineInitfailed,
c.CURLE_LOGIN_DENIED => error.LoginDenied,
c.CURLE_TFTP_NOTFOUND => error.TftpNotfound,
c.CURLE_TFTP_PERM => error.TftpPerm,
c.CURLE_REMOTE_DISK_FULL => error.RemoteDiskFull,
c.CURLE_TFTP_ILLEGAL => error.TftpIllegal,
c.CURLE_TFTP_UNKNOWNID => error.Tftp_Unknownid,
c.CURLE_REMOTE_FILE_EXISTS => error.RemoteFileExists,
c.CURLE_TFTP_NOSUCHUSER => error.TftpNosuchuser,
c.CURLE_CONV_FAILED => error.ConvFailed,
c.CURLE_CONV_REQD => error.ConvReqd,
c.CURLE_SSL_CACERT_BADFILE => error.SslCacertBadfile,
c.CURLE_REMOTE_FILE_NOT_FOUND => error.RemoteFileNotFound,
c.CURLE_SSH => error.Ssh,
c.CURLE_SSL_SHUTDOWN_FAILED => error.SslShutdownFailed,
c.CURLE_AGAIN => error.Again,
c.CURLE_SSL_CRL_BADFILE => error.SslCrlBadfile,
c.CURLE_SSL_ISSUER_ERROR => error.SslIssuerError,
c.CURLE_FTP_PRET_FAILED => error.FtpPretFailed,
c.CURLE_RTSP_CSEQ_ERROR => error.RtspCseqError,
c.CURLE_RTSP_SESSION_ERROR => error.RtspSessionError,
c.CURLE_FTP_BAD_FILE_LIST => error.FtpBadFileList,
c.CURLE_CHUNK_FAILED => error.ChunkFailed,
c.CURLE_NO_CONNECTION_AVAILABLE => error.NoConnectionAvailable,
c.CURLE_SSL_PINNEDPUBKEYNOTMATCH => error.SslPinnedpubkeynotmatch,
c.CURLE_SSL_INVALIDCERTSTATUS => error.SslInvalidcertstatus,
c.CURLE_HTTP2_STREAM => error.Http2Stream,
c.CURLE_RECURSIVE_API_CALL => error.RecursiveApiCall,
c.CURLE_AUTH_ERROR => error.AuthError,
c.CURLE_HTTP3 => error.Http3,
c.CURLE_QUIC_CONNECT_ERROR => error.QuicConnectError,
c.CURLE_PROXY => error.Proxy,
c.CURLE_SSL_CLIENTCERT => error.SslClientCert,
else => blk: {
std.debug.assert(false);
break :blk error.UnknownErrorCode;
},
};
}
fn bgFetchFeed(arena: std.mem.Allocator, rowid: u32, url: []const u8) !void {
var contents: [:0]const u8 = undefined;
var h = std.hash.Fnv1a_32.init();
h.update(url);
const url_hash = h.final();
const filename = try std.fmt.allocPrint(arena, "url-{d}.xml", .{url_hash});
if (DEBUG) {
std.debug.print(" bgFetchFeed fetching {s}\n", .{filename});
const file = std.fs.cwd().openFile(filename, .{}) catch |err| switch (err) {
error.FileNotFound => return,
else => |e| return e,
};
defer file.close();
contents = try file.readToEndAllocOptions(arena, 1024 * 1024 * 20, null, @alignOf(u8), 0);
} else {
std.debug.print(" bgFetchFeed fetching {s}\n", .{url});
const easy = c.curl_easy_init() orelse return error.FailedInit;
defer c.curl_easy_cleanup(easy);
const urlZ = try std.fmt.allocPrintZ(arena, "{s}", .{url});
try tryCurl(c.curl_easy_setopt(easy, c.CURLOPT_URL, urlZ.ptr));
try tryCurl(c.curl_easy_setopt(easy, c.CURLOPT_SSL_VERIFYPEER, @as(c_ulong, 0)));
try tryCurl(c.curl_easy_setopt(easy, c.CURLOPT_ACCEPT_ENCODING, "gzip"));
try tryCurl(c.curl_easy_setopt(easy, c.CURLOPT_FOLLOWLOCATION, @as(c_ulong, 1)));
try tryCurl(c.curl_easy_setopt(easy, c.CURLOPT_VERBOSE, @as(c_ulong, 1)));
const Fifo = std.fifo.LinearFifo(u8, .{ .Dynamic = {} });
try tryCurl(c.curl_easy_setopt(easy, c.CURLOPT_WRITEFUNCTION, struct {
fn writeFn(ptr: ?[*]u8, size: usize, nmemb: usize, data: ?*anyopaque) callconv(.C) usize {
_ = size;
const slice = (ptr orelse return 0)[0..nmemb];
const fifo: *Fifo = @ptrCast(@alignCast(data orelse return 0));
fifo.writer().writeAll(slice) catch return 0;
return nmemb;
}
}.writeFn));
// don't deinit the fifo, it's using arena anyway and we need the contents later
var fifo = Fifo.init(arena);
try tryCurl(c.curl_easy_setopt(easy, c.CURLOPT_WRITEDATA, &fifo));
tryCurl(c.curl_easy_perform(easy)) catch |err| {
try dvui.dialog(@src(), .{ .window = &g_win, .title = "Network Error", .message = try std.fmt.allocPrint(arena, "curl error {!}\ntrying to fetch url:\n{s}", .{ err, url }) });
};
var code: isize = 0;
try tryCurl(c.curl_easy_getinfo(easy, c.CURLINFO_RESPONSE_CODE, &code));
std.debug.print(" bgFetchFeed curl code {d}\n", .{code});
// add null byte
try fifo.writeItem(0);
const tempslice = fifo.readableSlice(0);
contents = tempslice[0 .. tempslice.len - 1 :0];
std.debug.print(" bgFetchFeed writing \"{s}\"\n", .{filename});
const file = std.fs.cwd().createFile(filename, .{}) catch |err| switch (err) {
error.FileNotFound => return,
else => |e| return e,
};
defer file.close();
try file.writeAll(contents);
}
const doc = c.xmlReadDoc(contents.ptr, null, null, 0);
defer c.xmlFreeDoc(doc);
const xpathCtx = c.xmlXPathNewContext(doc);
defer c.xmlXPathFreeContext(xpathCtx);
_ = c.xmlXPathRegisterNs(xpathCtx, "itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd");
{
const xpathObj = c.xmlXPathEval("/rss/channel", xpathCtx);
defer c.xmlXPathFreeObject(xpathObj);
if (xpathObj.*.nodesetval.*.nodeNr > 0) {
const node = xpathObj.*.nodesetval.*.nodeTab[0];
_ = c.xmlXPathSetContextNode(node, xpathCtx);
if (getContent(xpathCtx, "title", null)) |str| {
_ = try dbRow(arena, "UPDATE podcast SET title=? WHERE rowid=?", i32, .{ str, rowid });
}
if (getContent(xpathCtx, "description", null)) |str| {
_ = try dbRow(arena, "UPDATE podcast SET description=? WHERE rowid=?", i32, .{ str, rowid });
}
if (getContent(xpathCtx, "copyright", null)) |str| {
_ = try dbRow(arena, "UPDATE podcast SET copyright=? WHERE rowid=?", i32, .{ str, rowid });
}
if (getContent(xpathCtx, "pubDate", null)) |str| {
_ = c.setlocale(c.LC_ALL, "C");
var tm: c.struct_tm = undefined;
_ = c.strptime(str.ptr, "%a, %e %h %Y %H:%M:%S %z", &tm);
var buf: [256]u8 = undefined;
_ = c.strftime(&buf, buf.len, "%s", &tm);
_ = c.setlocale(c.LC_ALL, "");
_ = try dbRow(arena, "UPDATE podcast SET pubDate=? WHERE rowid=?", i32, .{ std.mem.sliceTo(&buf, 0), rowid });
}
if (getContent(xpathCtx, "lastBuildDate", null)) |str| {
_ = try dbRow(arena, "UPDATE podcast SET lastBuildDate=? WHERE rowid=?", i32, .{ str, rowid });
}
if (getContent(xpathCtx, "link", null)) |str| {
_ = try dbRow(arena, "UPDATE podcast SET link=? WHERE rowid=?", i32, .{ str, rowid });
}
if (getContent(xpathCtx, "image/url", null)) |str| {
_ = try dbRow(arena, "UPDATE podcast SET image_url=? WHERE rowid=?", i32, .{ str, rowid });
}
}
}
{
const xpathObj = c.xmlXPathEval("//item", xpathCtx);
defer c.xmlXPathFreeObject(xpathObj);
var i: usize = 0;
while (i < xpathObj.*.nodesetval.*.nodeNr) : (i += 1) {
std.debug.print("node {d}\n", .{i});
const node = xpathObj.*.nodesetval.*.nodeTab[i];
_ = c.xmlXPathSetContextNode(node, xpathCtx);
var episodeRow: ?i64 = null;
if (getContent(xpathCtx, "guid", null)) |str| {
if (try dbRow(arena, "SELECT rowid FROM episode WHERE podcast_id=? AND guid=?", i64, .{ rowid, str })) |erow| {
std.debug.print("podcast {d} existing episode {d} guid {s}\n", .{ rowid, erow, str });
episodeRow = erow;
} else {
std.debug.print("podcast {d} new episode guid {s}\n", .{ rowid, str });
_ = try dbRow(arena, "INSERT INTO episode (podcast_id, guid) VALUES (?, ?)", i64, .{ rowid, str });
if (g_db) |*db| {
episodeRow = db.getLastInsertRowID();
}
}
} else if (getContent(xpathCtx, "title", null)) |str| {
if (try dbRow(arena, "SELECT rowid FROM episode WHERE podcast_id=? AND title=?", i64, .{ rowid, str })) |erow| {
std.debug.print("podcast {d} existing episode {d} title {s}\n", .{ rowid, erow, str });
episodeRow = erow;
} else {
std.debug.print("podcast {d} new episode title {s}\n", .{ rowid, str });
_ = try dbRow(arena, "INSERT INTO episode (podcast_id, title) VALUES (?, ?)", i64, .{ rowid, str });
if (g_db) |*db| {
episodeRow = db.getLastInsertRowID();
}
}
} else if (getContent(xpathCtx, "description", null)) |str| {
if (try dbRow(arena, "SELECT rowid FROM episode WHERE podcast_id=? AND description=?", i64, .{ rowid, str })) |erow| {
std.debug.print("podcast {d} existing episode {d} description {s}\n", .{ rowid, erow, str });
episodeRow = erow;
} else {
std.debug.print("podcast {d} new episode description {s}\n", .{ rowid, str });
_ = try dbRow(arena, "INSERT INTO episode (podcast_id, description) VALUES (?, ?)", i64, .{ rowid, str });
if (g_db) |*db| {
episodeRow = db.getLastInsertRowID();
}
}
}
if (episodeRow) |erow| {
if (getContent(xpathCtx, "guid", null)) |str| {
_ = try dbRow(arena, "UPDATE episode SET guid=? WHERE rowid=?", i32, .{ str, erow });
}
if (getContent(xpathCtx, "title", null)) |str| {
_ = try dbRow(arena, "UPDATE episode SET title=? WHERE rowid=?", i32, .{ str, erow });
}
if (getContent(xpathCtx, "description", null)) |str| {
_ = try dbRow(arena, "UPDATE episode SET description=? WHERE rowid=?", i32, .{ str, erow });
}
if (getContent(xpathCtx, "pubDate", null)) |str| {
_ = c.setlocale(c.LC_ALL, "C");
var tm: c.struct_tm = undefined;
_ = c.strptime(str.ptr, "%a, %e %h %Y %H:%M:%S %z", &tm);
var buf: [256]u8 = undefined;
_ = c.strftime(&buf, buf.len, "%s", &tm);
_ = c.setlocale(c.LC_ALL, "");
_ = try dbRow(arena, "UPDATE episode SET pubDate=? WHERE rowid=?", i32, .{ std.mem.sliceTo(&buf, 0), erow });
}
if (getContent(xpathCtx, "enclosure", "url")) |str| {
_ = try dbRow(arena, "UPDATE episode SET enclosure_url=? WHERE rowid=?", i32, .{ str, erow });
//std.debug.print("enclosure_url: {s}\n", .{str});
}
if (getContent(xpathCtx, "itunes:duration", null)) |str| {
std.debug.print("duration: {s}\n", .{str});
var it = std.mem.splitBackwards(u8, str, ":");
const secs = std.fmt.parseInt(u32, it.first(), 10) catch 0;
const mins = std.fmt.parseInt(u32, it.next() orelse "0", 10) catch 0;
const hrs = std.fmt.parseInt(u32, it.next() orelse "0", 10) catch 0;
const dur = @as(f64, @floatFromInt(secs)) + 60.0 * @as(f64, @floatFromInt(mins)) + 60.0 * 60.0 * @as(f64, @floatFromInt(hrs));
_ = try dbRow(arena, "UPDATE episode SET duration=? WHERE rowid=?", i32, .{ dur, erow });
}
}
}
}
}
fn bgUpdateFeed(arena: std.mem.Allocator, rowid: u32) !void {
std.debug.print("bgUpdateFeed {d}\n", .{rowid});
if (try dbRow(arena, "SELECT url FROM podcast WHERE rowid = ?", []const u8, .{rowid})) |url| {
std.debug.print(" updating url {s}\n", .{url});
var timer = try std.time.Timer.start();
try bgFetchFeed(arena, rowid, url);
const timens = timer.read();
std.debug.print(" fetch took {d}ms\n", .{timens / 1000000});
}
}
fn mainGui() !void {
//var float = dvui.floatingWindow(@src(), false, null, null, .{});
//defer float.deinit();
var window_box = try dvui.box(@src(), .vertical, .{ .expand = .both, .color_fill = .{ .name = .fill_window }, .background = true });
defer window_box.deinit();
var b = try dvui.box(@src(), .vertical, .{ .expand = .both, .background = false });
defer b.deinit();
if (g_db) |db| {
_ = db;
var paned = try dvui.paned(@src(), .{ .direction = .horizontal, .collapsed_size = 400 }, .{ .expand = .both, .background = false });
const collapsed = paned.collapsed();
try podcastSide(paned);
try episodeSide(paned);
paned.deinit();
if (collapsed) {
try player();
}
}
}
var channel_str: []const u8 = "stereo";
var spec_str: []const u8 = "s16";
pub fn main() !void {
var backend = try Backend.initWindow(.{
.allocator = gpa,
.size = .{ .w = 360.0, .h = 600.0 },
.vsync = true,
.title = "Podcast",
//.icon = window_icon_png, // can also call setIconFromFileContent()
});
defer backend.deinit();
g_win = try dvui.Window.init(@src(), gpa, backend.backend(), .{});
g_win.snap_to_pixels = true;
defer g_win.deinit();
const winSize = backend.windowSize();
const pxSize = backend.pixelSize();
std.debug.print("initial window logical {} pixels {} natural scale {d} initial content scale {d} snap_to_pixels {}\n", .{ winSize, pxSize, pxSize.w / winSize.w, backend.initial_scale, g_win.snap_to_pixels });
defer g_arena_allocator.deinit();
{
dbInit(g_arena) catch |err| switch (err) {
error.DB_ERROR => {},
else => return err,
};
_ = g_arena_allocator.reset(.retain_capacity);
}
if (!Backend.c.SDL_InitSubSystem(Backend.c.SDL_INIT_AUDIO)) {
std.debug.print("Couldn't initialize SDL audio: {s}\n", .{Backend.c.SDL_GetError()});
return error.BackendError;
}
audio_device = Backend.c.SDL_OpenAudioDeviceStream(Backend.c.SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, null, audio_callback, null) orelse {
std.debug.print("SDL_OpenAudioDevice error: {s}\n", .{Backend.c.SDL_GetError()});
return error.BackendError;
};
defer Backend.c.SDL_DestroyAudioStream(audio_device);
_ = Backend.c.SDL_GetAudioStreamFormat(audio_device, null, &audio_spec);
std.debug.print("audio spec: {}\n", .{audio_spec});
channel_str = switch (audio_spec.channels) {
1 => "mono",
2 => "stereo",
else => {
std.debug.print("TODO: support {d} channel audio\n", .{audio_spec.channels});
return error.TOO_MANY_CHANNELS;
},
};
spec_str = switch (audio_spec.format) {
Backend.c.SDL_AUDIO_S16 => "s16",
else => {
std.debug.print("TODO: support {d} format audio\n", .{audio_spec.format});
return error.UNKNOWN_FORMAT;
},
};
std.debug.print("spec_str: {s} channel_str {s}\n", .{ spec_str, channel_str });
const pt = try std.Thread.spawn(.{}, playback_thread, .{});
pt.detach();
bgtasks = std.ArrayList(Task).init(gpa);
const bgt = try std.Thread.spawn(.{}, bg_thread, .{});
bgt.detach();
main_loop: while (true) {
const nstime = g_win.beginWait(backend.hasEvent());
try g_win.begin(nstime);
const quit = try backend.addAllEvents(&g_win);
if (quit) break :main_loop;
if (g_quit) break :main_loop;
_ = Backend.c.SDL_SetRenderDrawColor(backend.renderer, 0, 0, 0, 255);
_ = Backend.c.SDL_RenderClear(backend.renderer);
//_ = dvui.examples.demo();
mainGui() catch |err| switch (err) {
error.DB_ERROR => {},
else => return err,
};
const end_micros = try g_win.end(.{});
backend.setCursor(g_win.cursorRequested());
backend.textInputRect(g_win.textInputRequested());
backend.renderPresent();
const wait_event_micros = g_win.waitTime(end_micros, null);
backend.waitEventTimeout(wait_event_micros);
_ = g_arena_allocator.reset(.retain_capacity);
}
}
fn deleteDialogDisplay(id: u32) !void {
_ = dvui.dataGet(null, id, "podcast_id", u32);
try dvui.dialogDisplay(id);
}
fn deleteDialogCallafter(id: u32, response: dvui.enums.DialogResponse) !void {
const podcast_id = dvui.dataGet(null, id, "podcast_id", u32) orelse {
dvui.log.err("deleteDialogDisplay lost data for dialog {x}\n", .{id});
dvui.dialogRemove(id);
return;
};
if (response == .ok) {
_ = try dbRow(g_arena, "DELETE FROM podcast WHERE rowid = ?", u8, .{@as(u32, podcast_id)});
_ = try dbRow(g_arena, "DELETE FROM episode WHERE podcast_id = ?", u8, .{@as(u32, podcast_id)});
var buf: [100]u8 = undefined;
try dvui.toast(@src(), .{ .message = std.fmt.bufPrint(&buf, "deleted podcast {d}", .{podcast_id}) catch unreachable });
}
}
var add_rss_dialog: bool = false;
var delete_mode: bool = false;
const top_bar_height = 40;
fn podcastSide(paned: *dvui.PanedWidget) !void {
var b = try dvui.box(@src(), .vertical, .{ .expand = .both });
defer b.deinit();
{
var hb = try dvui.box(@src(), .horizontal, .{ .expand = .horizontal, .min_size_content = .{ .h = top_bar_height } });
defer hb.deinit();
if (try dvui.buttonIcon(@src(), "delete_podcast", dvui.entypo.trash, .{}, (if (delete_mode) dvui.themeGet().style_err else dvui.Options{}).override(.{
.expand = .ratio,
.margin = .{},
}))) {
delete_mode = !delete_mode;
}
const label_width = (dvui.themeGet().font_body.textSize("fps 12") catch dvui.Size{}).w;
try dvui.label(@src(), "fps {d}", .{@round(dvui.FPS())}, .{ .gravity_y = 0.5, .min_size_content = .{ .w = label_width } });
{
var menu = try dvui.menu(@src(), .horizontal, .{ .gravity_x = 1.0, .expand = .vertical });
defer menu.deinit();
if (try dvui.menuItemIcon(@src(), "menu", dvui.entypo.menu, .{ .submenu = true }, .{ .expand = .ratio })) |r| {
var fw = try dvui.floatingMenu(@src(), dvui.Rect.fromPoint(dvui.Point{ .x = r.x, .y = r.y + r.h }), .{});
defer fw.deinit();
if (try dvui.menuItemLabel(@src(), "Add RSS", .{}, .{ .expand = .horizontal })) |_| {
menu.close();
add_rss_dialog = true;
}
if (try dvui.menuItemLabel(@src(), "Update All", .{}, .{ .expand = .horizontal })) |_| {
menu.close();
if (g_db) |*db| {
const query = "SELECT rowid FROM podcast";
var stmt = db.prepare(query) catch {
try dbError("{}\n\npreparing statement:\n\n{s}", .{ db.getDetailedError(), query });
return error.DB_ERROR;
};
defer stmt.deinit();
var iter = try stmt.iterator(u32, .{});
while (try iter.nextAlloc(g_arena, .{})) |rowid| {
bgtask_mutex.lock();
try bgtasks.append(.{ .kind = .update_feed, .rowid = @as(u32, @intCast(rowid)) });
bgtask_mutex.unlock();
bgtask_condition.signal();
}
}
}
if (try dvui.button(@src(), "Toggle Debug Window", .{}, .{})) {
dvui.toggleDebugWindow();
}
}
}
}
if (add_rss_dialog) {
var dialog = try dvui.floatingWindow(@src(), .{ .modal = true, .open_flag = &add_rss_dialog }, .{});
defer dialog.deinit();
try dvui.labelNoFmt(@src(), "Add RSS Feed", .{ .gravity_x = 0.5, .gravity_y = 0.5 });
const TextEntryText = struct {
var text = [_]u8{0} ** 1000;
};
const msize = dvui.TextEntryWidget.defaults.fontGet().textSize("M") catch unreachable;
var te = try dvui.textEntry(@src(), .{ .text = .{ .buffer = &TextEntryText.text } }, .{ .gravity_x = 0.5, .gravity_y = 0.5, .min_size_content = .{ .w = msize.w * 26.0, .h = msize.h } });
if (dvui.firstFrame(te.data().id)) {
dvui.focusWidget(te.wd.id, null, null);
}
te.deinit();
var box2 = try dvui.box(@src(), .horizontal, .{ .gravity_x = 1.0 });
defer box2.deinit();
if (try dvui.button(@src(), "Ok", .{}, .{})) {
dialog.close();
const url = std.mem.trim(u8, &TextEntryText.text, " \x00");
const row = try dbRow(g_arena, "SELECT rowid FROM podcast WHERE url = ?", i32, .{url});
if (row) |_| {
try dvui.dialog(@src(), .{ .title = "Note", .message = try std.fmt.allocPrint(g_arena, "url already in db:\n\n{s}", .{url}) });
} else {
_ = try dbRow(g_arena, "INSERT INTO podcast (url, speed) VALUES (?, 1.0)", i32, .{url});
if (g_db) |*db| {
const rowid = db.getLastInsertRowID();
bgtask_mutex.lock();
try bgtasks.append(.{ .kind = .update_feed, .rowid = @as(u32, @intCast(rowid)) });
bgtask_mutex.unlock();
bgtask_condition.signal();
}
}
}
if (try dvui.button(@src(), "Cancel", .{}, .{})) {
dialog.close();
}
}
var scroll = try dvui.scrollArea(@src(), .{}, .{ .expand = .both, .background = false });
if (g_db) |*db| {
const num_podcasts = try dbRow(g_arena, "SELECT count(*) FROM podcast", usize, .{});
const query = "SELECT rowid FROM podcast";
var stmt = db.prepare(query) catch {
try dbError("{}\n\npreparing statement:\n\n{s}", .{ db.getDetailedError(), query });
return error.DB_ERROR;
};
defer stmt.deinit();
var iter = try stmt.iterator(u32, .{});
var i: usize = 1;
while (try iter.nextAlloc(g_arena, .{})) |rowid| {
defer i += 1;
const title = try dbRow(g_arena, "SELECT title FROM podcast WHERE rowid=?", []const u8, .{rowid}) orelse "Error: No Title";
var margin: dvui.Rect = .{ .x = 8, .y = 0, .w = 8, .h = 0 };
var border: dvui.Rect = .{ .x = 1, .y = 0, .w = 1, .h = 0 };
var corner = dvui.Rect.all(0);
if (i != 1) {
border.y = 1;
}
if (i == 1) {
margin.y = 8;
border.y = 1;
corner.x = 9;
corner.y = 9;
}
if (i == num_podcasts) {
margin.h = 8;
border.h = 1;
corner.w = 9;
corner.h = 9;
}
var box = try dvui.box(@src(), .horizontal, .{
.id_extra = i,
.expand = .horizontal,
.margin = margin,
.border = border,
.background = true,
.corner_radius = corner,
.color_fill = .{ .name = .fill },
.min_size_content = .{ .h = 40 },
});
defer box.deinit();
if (delete_mode) {
if (try dvui.buttonIcon(@src(), "delete_podcast", dvui.entypo.trash, .{}, .{
.expand = .ratio,
.gravity_y = 0.5,
})) {
const num_episodes = (try dbRow(g_arena, "SELECT count(*) FROM episode WHERE podcast_id = ?", u32, .{rowid})).?;
const id_mutex = try dvui.dialogAdd(null, @src(), 0, deleteDialogDisplay);
const id = id_mutex.id;
dvui.dataSet(null, id, "_modal", true);
dvui.dataSetSlice(null, id, "_title", @as([]const u8, "Delete Podcast?"));
dvui.dataSetSlice(null, id, "_message", try std.fmt.allocPrint(g_arena, "Delete podcast \"{s}\" and all {d} episodes?", .{ title, num_episodes }));
dvui.dataSetSlice(null, id, "_ok_label", @as([]const u8, "Delete"));
dvui.dataSetSlice(null, id, "_cancel_label", @as([]const u8, "Cancel"));
dvui.dataSet(null, id, "_callafter", @as(dvui.DialogCallAfterFn, deleteDialogCallafter));
dvui.dataSet(null, id, "podcast_id", rowid);
id_mutex.mutex.unlock();
}
}
bgtask_mutex.lock();
defer bgtask_mutex.unlock();
for (bgtasks.items) |*t| {
if (t.rowid == rowid) {
var m = margin;
m.w = 0;
margin.x = 0;
if (try dvui.buttonIcon(@src(), "cancel_refresh", dvui.entypo.circle_with_cross, .{}, .{
.expand = .ratio,
.rotation = std.math.pi * @as(f32, @floatFromInt(@mod(@divFloor(dvui.frameTimeNS(), 1_000_000), 1000))) / 1000,
.gravity_y = 0.5,
})) {
// TODO: cancel task
}
try dvui.timer(0, 250_000);
break;
}
}
if (try dvui.button(@src(), title, .{}, .{
.margin = .{},
.corner_radius = corner,
.expand = .both,
.color_fill = .{ .name = .fill },
})) {
g_podcast_id_on_right = rowid;
if (paned.collapsed()) {
paned.animateSplit(0.0);
}
}
}
}
scroll.deinit();
if (!paned.collapsed()) {
try player();
}
}
fn episodeSide(paned: *dvui.PanedWidget) !void {
var b = try dvui.box(@src(), .vertical, .{ .expand = .both });
defer b.deinit();
if (paned.collapsed()) {
var menu = try dvui.menu(@src(), .horizontal, .{ .expand = .horizontal, .min_size_content = .{ .h = top_bar_height } });
defer menu.deinit();
if (try dvui.menuItemIcon(@src(), "back", dvui.entypo.chevron_left, .{}, .{ .expand = .ratio })) |rr| {
_ = rr;
paned.animateSplit(1.0);
}
}
if (g_db) |*db| {
const num_episodes = try dbRow(g_arena, "SELECT count(*) FROM episode WHERE podcast_id = ?", usize, .{g_podcast_id_on_right}) orelse 0;
const height: f32 = 120;
const tmpId = dvui.parentGet().extendId(@src(), 0);
var scroll_info: dvui.ScrollInfo = .{ .vertical = .given };
if (dvui.dataGet(null, tmpId, "scroll_info", dvui.ScrollInfo)) |si| {
scroll_info = si;
scroll_info.virtual_size.h = height * @as(f32, @floatFromInt(num_episodes));
}
defer dvui.dataSet(null, tmpId, "scroll_info", scroll_info);
var scroll = try dvui.scrollArea(@src(), .{ .scroll_info = &scroll_info }, .{ .expand = .both, .background = false });
defer scroll.deinit();
var stmt = db.prepare(Episode.query_all) catch {
try dbError("{}\n\npreparing statement:\n\n{s}", .{ db.getDetailedError(), Episode.query_all });
return error.DB_ERROR;
};
defer stmt.deinit();
const visibleRect = scroll_info.viewport;
var cursor: f32 = 0;
var iter = try stmt.iterator(Episode, .{g_podcast_id_on_right});
while (try iter.nextAlloc(g_arena, .{})) |episode| {
defer cursor += height;
const r = dvui.Rect{ .x = 0, .y = cursor, .w = 0, .h = height };
if (visibleRect.intersect(r).h > 0) {
var tl = dvui.TextLayoutWidget.init(@src(), .{}, .{ .id_extra = episode.rowid, .expand = .horizontal, .rect = r });
try tl.install(.{});
defer tl.deinit();
var cbox = try dvui.box(@src(), .vertical, .{ .gravity_x = 1.0 });
const filename = try std.fmt.allocPrint(g_arena, "episode_{d}.aud", .{episode.rowid});
const file = std.fs.cwd().openFile(filename, .{}) catch null;
if (try dvui.buttonIcon(@src(), "play", dvui.entypo.controller_play, .{}, .{ .padding = dvui.Rect.all(6), .min_size_content = .{ .h = 18 } })) {
if (file == null) {
// TODO: make the play button disabled, and if you click it, it puts this out as a toast
try dvui.dialog(@src(), .{ .title = "Error", .message = try std.fmt.allocPrint(g_arena, "Must download first", .{}) });
} else {
_ = try dbRow(g_arena, "UPDATE player SET episode_id=?", u8, .{episode.rowid});
audio_mutex.lock();
stream_new = true;
stream_seek_time = episode.position;
buffer.discard(buffer.readableLength());
buffer_last_time = stream_seek_time.?;
current_time = stream_seek_time.?;
if (!playing) {
play();
}
audio_mutex.unlock();
audio_condition.signal();
}
}
if (file) |f| {
f.close();
if (try dvui.buttonIcon(@src(), "delete", dvui.entypo.trash, .{}, .{ .padding = dvui.Rect.all(6), .min_size_content = .{ .h = 18 } })) {
std.fs.cwd().deleteFile(filename) catch |err| {
// TODO: make this a toast
try dvui.dialog(@src(), .{ .title = "Delete Error", .message = try std.fmt.allocPrint(g_arena, "error {!}\ntrying to delete file:\n{s}", .{ err, filename }) });
};
}
} else {
bgtask_mutex.lock();
defer bgtask_mutex.unlock();
for (bgtasks.items) |*t| {
if (t.rowid == episode.rowid) {
// show progress, make download button into cancel button
if (try dvui.buttonIcon(@src(), "cancel", dvui.entypo.circle_with_cross, .{}, .{ .padding = dvui.Rect.all(6), .min_size_content = .{ .h = 18 } })) {
t.cancel = true;
}
break;
}
} else {
if (try dvui.buttonIcon(@src(), "download", dvui.entypo.download, .{}, .{ .padding = dvui.Rect.all(6), .min_size_content = .{ .h = 18 } })) {
try bgtasks.append(.{ .kind = .download_episode, .rowid = @as(u32, @intCast(episode.rowid)) });
bgtask_condition.signal();
}
}
}
cbox.deinit();
var tbox = try dvui.box(@src(), .vertical, .{ .gravity_x = 1.0, .gravity_y = 1.0 });
const epoch_secs = std.time.epoch.EpochSeconds{ .secs = episode.pubDate };
const epoch_day = epoch_secs.getEpochDay();
const year_day = epoch_day.calculateYearDay();
const month_day = year_day.calculateMonthDay();
try dvui.label(@src(), "{d}/{d}/{d}", .{ year_day.year % 1000, month_day.month.numeric(), month_day.day_index }, .{ .font_style = .caption_heading, .padding = .{} });
const hrs = @floor(episode.duration / 60.0 / 60.0);
const mins = @floor((episode.duration - (hrs * 60.0 * 60.0)) / 60.0);
const secs = @floor(episode.duration - (hrs * 60.0 * 60.0) - (mins * 60.0));
try dvui.label(@src(), "{d:0>2}:{d:0>2}:{d:0>2}", .{ hrs, mins, secs }, .{ .font_style = .caption_heading, .padding = .{} });
tbox.deinit();
tl.processEvents();
try tl.format("{s}", .{episode.title}, .{ .font = dvui.themeGet().font_heading.resize(15) });
try tl.addText("\n\n", .{ .font = dvui.themeGet().font_body.resize(8) });
//const lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
//try tl.addText(lorem, .{});
try tl.addText(episode.description, .{ .font = dvui.themeGet().font_body.resize(14) });
}
}
}
}
fn player() !void {
var box = try dvui.box(@src(), .vertical, .{ .expand = .horizontal, .background = true });
defer box.deinit();
var episode = Episode{ .rowid = 0, .podcast_id = 0, .title = "Episode Title", .description = "", .enclosure_url = "", .position = 0, .duration = 1, .pubDate = 0 };
const episode_id = try dbRow(g_arena, "SELECT episode_id FROM player", i32, .{});
if (episode_id) |id| {
episode = try dbRow(g_arena, Episode.query_one, Episode, .{id}) orelse episode;
}
try dvui.label(@src(), "{s}", .{episode.title}, .{
.expand = .horizontal,
.margin = dvui.Rect{ .x = 8, .y = 4, .w = 8, .h = 4 },
.font_style = .heading,
});