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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE QuasiQuotes #-}
module WhatcdResolver where
import AppT
import Arg
import Builder
import Comparison
import Conduit (ConduitT)
import Conduit qualified
import Control.Monad.Logger.CallStack
import Control.Monad.Reader
import Data.Aeson qualified as Json
import Data.Aeson.BetterErrors qualified as Json
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString qualified as ByteString
import Data.CaseInsensitive (CI)
import Data.Conduit ((.|))
import Data.Error.Tree
import Data.HashMap.Strict qualified as HashMap
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Map.Strict qualified as Map
import Data.Maybe (isJust)
import Data.Pool qualified as Pool
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Time (UTCTime, getCurrentTime)
import Database.PostgreSQL.Simple qualified as Postgres
import Database.PostgreSQL.Simple.Types (Only (..), PGArray (PGArray))
import Database.Postgres.Temp qualified as TmpPg
import FieldParser (FieldParser)
import FieldParser qualified as Field
import GHC.Records (HasField (..))
import Html qualified
import Http
import IHP.HSX.QQ (hsx)
import IHP.HSX.ToHtml ()
import Json qualified
import Json.Enc (Enc)
import Json.Enc qualified as Enc
import JsonLd
import Label
import Multipart2 (MultipartParseT)
import Multipart2 qualified as Multipart
import MyLabel
import MyPrelude
import Network.HTTP.Client.Conduit qualified as Http
import Network.HTTP.Simple qualified as Http
import Network.HTTP.Types
import Network.HTTP.Types qualified as Http
import Network.Wai (ResponseReceived)
import Network.Wai qualified as Wai
import Network.Wai.Handler.Warp qualified as Warp
import Network.Wai.Parse (parseContentType)
import OpenTelemetry.Attributes qualified as Otel
import OpenTelemetry.Trace qualified as Otel hiding (getTracer, inSpan, inSpan')
import OpenTelemetry.Trace.Core qualified as OtelCore
import OpenTelemetry.Trace.Monad qualified as Otel
import Parse (Parse)
import Parse qualified
import Postgres.Decoder qualified as Dec
import Postgres.MonadPostgres
import Pretty
import Redacted
import RunCommand (runCommandExpect0)
import System.Directory qualified as Dir
import System.Directory qualified as Xdg
import System.Environment qualified as Env
import System.FilePath ((</>))
import Text.Blaze.Html (Html)
import Text.Blaze.Html.Renderer.Utf8 qualified as Html
import Text.Blaze.Html5 qualified as Html
import Text.Blaze.Internal qualified as HtmlI
import Tool (readTool, readTools)
import Transmission
import UnliftIO hiding (Handler)
import UnliftIO.Async qualified as Async
import UnliftIO.Concurrent (threadDelay)
import Prelude hiding (span)
main :: IO ()
main =
runAppWith
( do
-- todo: trace that to the init functions as well
Otel.inSpan "whatcd-resolver main function" Otel.defaultSpanArguments $ do
_ <- runTransaction migrate
htmlUi
)
<&> first showToError
>>= expectIOError "could not start whatcd-resolver"
htmlUi :: AppT IO ()
htmlUi = do
uniqueRunId <-
runTransaction $
querySingleRowWith
[sql|
SELECT gen_random_uuid()::text
|]
()
(Dec.fromField @Text)
ourHtmlIntegrities <- prefetchHtmlIntegrities
(counterHtmlM, counterHandler, _counterAsync) <- testCounter (label @"endpoint" "counter")
withRunInIO $ \runInIO -> Warp.run 9093 $ \req respondOrig -> do
let catchAppException act =
try act >>= \case
Right a -> pure a
Left (AppExceptionTree err) -> do
runInIO (logError (prettyErrorTree err))
respondOrig (Wai.responseLBS Http.status500 [] "")
Left (AppExceptionPretty err) -> do
runInIO (logError (err & Pretty.prettyErrsNoColor & stringToText))
respondOrig (Wai.responseLBS Http.status500 [] "")
Left (AppExceptionEnc err) -> do
runInIO (logError (Enc.encToTextPrettyColored err))
respondOrig (Wai.responseLBS Http.status500 [] "")
catchAppException $ do
let torrentIdMp span =
parseMultipartOrThrow
span
req
( do
label @"torrentId" <$> Multipart.field "torrent-id" ((Field.utf8 >>> Field.signedDecimal >>> Field.bounded @Int "int"))
)
let parseQueryArgsNewSpan spanName parser =
Parse.runParse "Unable to find the right request query arguments" (lmap Wai.queryString parser) req
& assertMNewSpan spanName (first AppExceptionTree)
let handlers :: Handlers (AppT IO)
handlers =
Map.fromList $
ourHtmlIntegrities.handlers
<> [ ( "",
HtmlStream (pure ()) $ \_dat span ->
( pure $ htmlPageChrome ourHtmlIntegrities "whatcd-resolver",
do
counterHtml <- counterHtmlM
mainHtml counterHtml uniqueRunId span
)
),
( "redacted-search",
HtmlStream (label @"searchstr" <$> singleQueryArgument "searchstr" identity) $
\dat _span ->
( pure $ htmlPageChrome ourHtmlIntegrities [fmt|whatcd-resolver – Search – {dat.queryArgs.searchstr & bytesToTextUtf8Lenient}|],
do
runTransaction $ do
res <- redactedSearchAndInsert (lbl #maxPages 0) [("searchstr", dat.queryArgs.searchstr)]
(table, settings) <-
concurrentlyTraced
( do
d <-
getBestTorrentsData
bestTorrentsDataDefault
( Just
( E21
(label @"onlyTheseTorrents" res.newTorrents)
) ::
Maybe
( E2
"onlyTheseTorrents"
[Label "torrentId" Int]
"artistRedactedId"
Int
)
)
pure $ mkBestTorrentsTableByReleaseType d
)
(getSettings)
pure $
mainHtml'
( MainHtml
{ returnUrl = dat.returnUrl,
counterHtml = "",
mainContent =
[hsx|<h1>Search results for <pre>{dat.queryArgs.searchstr}</pre></h1>{table}|],
uniqueRunId,
searchFieldContent = dat.queryArgs.searchstr & bytesToTextUtf8Lenient,
settings
}
)
)
),
( "snips/redacted/torrentDataJson",
Html $ \span -> do
dat <- torrentIdMp span
Html.mkVal <$> (runTransaction $ getTorrentById dat)
),
( "snips/redacted/getTorrentFile",
HtmlOrReferer $ \span -> do
dat <- torrentIdMp span
runTransaction $ do
settings <- getSettings
result <-
redactedGetTorrentFileAndInsert
( t2
#torrentId
dat.torrentId
#freelechTokensExhaustedAt
settings.freelechTokensExhaustedAt
)
-- Update exhaustion timestamp based on freeleech status
case result.freelechStatus of
NoTokensRemaining -> do
now <- liftIO getCurrentTime
_ <-
writeSettings
[ T2
(label @"key" "freelechTokensExhaustedAt")
(label @"val" $ Json.toJSON now)
]
pure ()
FreeleechPossible -> do
-- Clear exhaustion timestamp if tokens are working
when (isJust settings.freelechTokensExhaustedAt) $ do
_ <-
writeSettings
[ T2
(label @"key" "freelechTokensExhaustedAt")
(label @"val" Json.Null)
]
pure ()
running <-
lift @Transaction $
doTransmissionRequest' (transmissionRequestAddTorrent result)
updateTransmissionTorrentHashById
( T2
(getLabel @"torrentHash" running)
(getLabel @"torrentId" dat)
)
pure $
everySecond
"snips/transmission/getTorrentState"
(Enc.object [("torrent-hash", Enc.text running.torrentHash)])
"Starting"
),
-- TODO: this is bad duplication??
( "snips/redacted/startTorrentFile",
Html $ \span -> do
dat <- torrentIdMp span
runTransaction $ do
file <-
getTorrentFileById dat
<&> annotate [fmt|No torrent file for torrentId "{dat.torrentId}"|]
>>= orAppThrow span
running <-
lift @Transaction $
doTransmissionRequest' (transmissionRequestAddTorrent file)
updateTransmissionTorrentHashById
( T2
(getLabel @"torrentHash" running)
(getLabel @"torrentId" dat)
)
pure $
everySecond
"snips/transmission/getTorrentState"
(Enc.object [("torrent-hash", Enc.text running.torrentHash)])
"Starting"
),
( "snips/transmission/getTorrentState",
Html $ \span -> do
dat <- parseMultipartOrThrow span req $ label @"torrentHash" <$> Multipart.field "torrent-hash" Field.utf8
status <-
doTransmissionRequest'
( transmissionRequestListOnlyTorrents
( T2
(label @"ids" [label @"torrentHash" dat.torrentHash])
(label @"fields" ["hashString"])
)
(Json.keyLabel @"torrentHash" "hashString" Json.asText)
)
<&> List.find (\torrent -> torrent.torrentHash == dat.torrentHash)
pure $
case status of
Nothing -> [hsx|ERROR unknown|]
Just _torrent -> [hsx|Running|]
),
( "snips/jsonld/render",
do
HtmlWithQueryArgs
( label @"target"
<$> (singleQueryArgument "target" Field.utf8 >>> textToURI >>> Http.uriToRequestOptionsGet)
)
( \dat _span -> do
jsonld <- httpGetJsonLd dat.queryArgs.target
pure $ renderJsonld jsonld
)
),
("counter", counterHandler),
( "populate-recommendations",
HtmlOrReferer $ \span -> do
runTransaction $ do
addEventSimple span "Starting recommendation population"
-- First populate similar artists for favorites
favoritesResult <- populateSimilarArtistsForFavorites
addAttribute span "favorites-processed" (favoritesResult.processedArtists, naturalDecimalT)
-- Then populate releases for those similar artists
releasesResult <- populateReleasesForSimilarArtists
addAttribute span "releases-processed" (releasesResult.processedArtists, naturalDecimalT)
addEventSimple span "Recommendation population completed"
pure $
[hsx|
<div>
<h2>Recommendation Population Complete!</h2>
<p>Processed {favoritesResult.processedArtists} favorite artists</p>
<p>Found releases for {releasesResult.processedArtists} similar artists</p>
<p><a href="/">Return to main page</a></p>
</div>
|]
),
( "artist",
do
HtmlStream
( label @"artistRedactedId"
<$> ( singleQueryArgument
"redacted_id"
parseRedactedId
)
)
$ \dat _span ->
( do
runTransaction $ do
(artistName, _) <-
concurrentlyTraced
( inSpan' "finding artist name" $ \span -> do
addAttribute span "artist-redacted-id" (dat.queryArgs.artistRedactedId, intDecimalT)
mArtistName <- getArtistNameById (lbl #artistId dat.queryArgs.artistRedactedId)
let pageTitle = case mArtistName of
Nothing -> "whatcd-resolver"
Just a -> [fmt|{a} - Artist Page - whatcd-resolver|]
pure $ htmlPageChrome ourHtmlIntegrities pageTitle
)
( do
execute [sql|INSERT INTO redacted.artist_favourites (artist_id) VALUES (?) ON CONFLICT DO NOTHING|] (Only (dat.queryArgs.artistRedactedId :: Int))
)
pure artistName,
do
artistPage (T2 dat.queryArgs (label @"uniqueRunId" uniqueRunId))
)
),
( "artist/refresh",
HtmlOrRedirect $
\span -> do
dat <-
parseMultipartOrThrow
span
req
( label @"artistId"
<$> Multipart.field
"artist-id"
parseRedactedId
)
runTransaction $ redactedRefreshArtist dat
pure $ E22 (label @"redirectTo" $ textToBytesUtf8 $ mkArtistLink dat)
),
( "serve/torrent",
HtmlWithQueryArgsRedirect
( do
torrentId <- singleQueryArgument "torrent-id" parseRedactedId
fileId <- singleQueryArgument "file-id" (Field.utf8 >>> Field.decimalNatural)
pure $ t2 #torrentId torrentId #fileId fileId
)
( \dat _span -> runTransaction $ do
lift getTransmissionDownloads >>= \case
Nothing -> do
pure $ e31 #err "Transmission download disabled"
Just transmission -> do
mFilePath <- getTorrentFilePath dat.queryArgs
case mFilePath.torrent of
Nothing -> do
pure $ e31 #err "Torrent file not found"
Just filePath -> do
let redirectPath = transmission.staticFileEndpoint <> "/" <> (filePath & stringToText)
pure $ e32 #redirectTo (textToBytesUtf8 redirectPath)
)
),
( "serve/torrent/cover",
HtmlWithQueryArgsRedirect
( lbl #torrentId <$> singleQueryArgument "torrent-id" parseRedactedId
)
( \dat _span -> runTransaction $ do
lift getTransmissionDownloads >>= \case
Nothing -> do
pure $ e31 #err "Transmission download disabled"
Just transmission -> do
mFilePath <- getTorrentCoverArt dat.queryArgs
case mFilePath of
Nothing -> do
pure $ e31 #err "Torrent cover not found"
Just ca -> do
ca
& caseE2
( t2
#coverArtStatic
( \filePath -> do
let redirectPath = transmission.staticFileEndpoint <> "/" <> (filePath & stringToText)
pure $ e32 #redirectTo (textToBytesUtf8 redirectPath)
)
#coverArtBytes
( \c -> do
pure $ e33 #direct (t2 #contentType c.mimeType #bytes c.picture)
)
)
)
),
( "autorefresh",
Plain $ do
qry <-
parseQueryArgsNewSpan
"Autorefresh Query Parse"
( label @"hasItBeenRestarted"
<$> singleQueryArgument "hasItBeenRestarted" Field.utf8
)
pure $
Wai.responseLBS
Http.ok200
( [("Content-Type", "text/html")]
<> if uniqueRunId /= qry.hasItBeenRestarted
then -- cause the client side to refresh
[("HX-Refresh", "true")]
else []
)
""
)
]
runInIO $
runHandlers
( Html $ \span -> do
-- counterHtml <- counterHtmlM
-- mainHtml counterHtml uniqueRunId span
appThrow span "Unknown route"
)
handlers
req
respondOrig
where
everySecond :: Text -> Enc -> Html -> Html
everySecond call extraData innerHtml = [hsx|<div hx-trigger="every 1s" hx-swap="outerHTML" hx-post={call} hx-vals={Enc.encToBytesUtf8 extraData}>{innerHtml}</div>|]
mainHtml :: Html -> Text -> Otel.Span -> AppT IO Html
mainHtml counterHtml uniqueRunId _span = runTransaction $ do
-- jsonld <-
-- httpGetJsonLd
-- ( URI.parseURI "https://musicbrainz.org/work/92000fd4-d304-406d-aeb4-6bdbeed318ec" & annotate "not an URI" & unwrapError,
-- "https://musicbrainz.org/work/92000fd4-d304-406d-aeb4-6bdbeed318ec"
-- )
-- <&> renderJsonld
((bestTorrentsTable, recommendedTable), settings) <-
concurrentlyTraced
( do
-- Fetch both latest releases and recommended releases in parallel
(latestReleases, recommendedReleases) <-
concurrentlyTraced
( getBestTorrentsData
( BestTorrentsData
{ limitResults = Just 100,
ordering = ByLastReleases,
onlyFavourites = True,
disallowedReleaseTypes =
[ releaseTypeBootleg,
releaseTypeGuestAppearance
],
..
}
)
Nothing
)
( getRecommendedTorrentsData
( RecommendedTorrentsData
{ limitResults = Just 50,
disallowedReleaseTypes =
[ releaseTypeBootleg,
releaseTypeGuestAppearance,
releaseTypeRemix,
releaseTypeDJMix
]
}
)
)
let latestTable = case latestReleases & nonEmpty of
Nothing -> [hsx|<h1>Latest Releases</h1><p>No torrents found</p>|]
Just d' -> mkBestTorrentsTableSection (lbl #sectionName "Latest Releases") d'
let recommendedTableHtml = case recommendedReleases & nonEmpty of
Nothing ->
[hsx|
<h1>Recommended</h1>
<p>No recommended releases found</p>
<form action="populate-recommendations" method="post">
<button type="submit" hx-disabled-elt="this">
Fetch New Recommendations
</button>
<div class="htmx-indicator">Fetching recommendations...</div>
</form>
|]
Just d' -> mkRecommendedTorrentsTableSection (lbl #sectionName "Recommended") d'
pure (latestTable, recommendedTableHtml)
)
(getSettings)
-- transmissionTorrentsTable <- lift @Transaction getTransmissionTorrentsTable
pure $
mainHtml'
( MainHtml
{ returnUrl = "/",
counterHtml,
mainContent =
[hsx|
{bestTorrentsTable}
{recommendedTable}
|],
uniqueRunId,
settings,
searchFieldContent = ""
}
)
parseRedactedId :: Field.FieldParser' Error ByteString Int
parseRedactedId =
( Field.utf8
>>> (Field.decimalNatural <&> toInteger)
>>> (Field.bounded @Int "Int")
)
data MainHtml = MainHtml
{ returnUrl :: ByteString,
counterHtml :: Html,
mainContent :: Html,
searchFieldContent :: Text,
uniqueRunId :: Text,
settings :: Settings
}
mainHtml' :: MainHtml -> Html
mainHtml' dat = do
let freelechStatus = case dat.settings.freelechTokensExhaustedAt of
Nothing -> [hsx|<p>Using freeleech tokens (automatic)</p>|]
Just _timestamp -> [hsx|<p>Not using freeleech tokens</p>|]
[hsx|
<!-- {dat.counterHtml} -->
{freelechStatus}
{progressPlayer}
<style>
progress-player {
max-width: 400px;
}
</style>
<form action="redacted-search">
<label for="redacted-search-input">Redacted Search</label>
<input
id="redacted-search-input"
type="text"
name="searchstr"
value={dat.searchFieldContent} />
<button type="submit" hx-disabled-elt="this">Search</button>
<div class="htmx-indicator">Search running!</div>
</form>
<div>
{dat.mainContent}
</div>
<!-- refresh the page if the uniqueRunId is different -->
<!-- <input
hidden
type="text"
id="autorefresh"
name="hasItBeenRestarted"
value={dat.uniqueRunId}
hx-get="/autorefresh"
hx-trigger="every 5s"
hx-swap="none"
/> -->
|]
where
progressPlayer =
( HtmlI.customParent "progress-player"
Html.! Html.customAttribute "src" "/serve/torrent?torrent-id=4854922&file-id=0"
Html.! Html.customAttribute "coverart" "/serve/torrent/cover?torrent-id=4854922"
Html.! Html.customAttribute "artist" "Kendrick Lamar"
Html.! Html.customAttribute "title" "Not Like Us"
$ mempty
)
<> [hsx|<script src="/static/progress-player.js"></script>|]
parseMultipartOrThrow :: (MonadIO m, MonadThrow m, MonadLogger m) => Otel.Span -> Wai.Request -> Multipart.MultipartParseT m a -> m a
parseMultipartOrThrow span req parser =
Multipart.parseMultipartOrThrow
(appThrow span . AppExceptionTree)
parser
req
-- | Reload the current page (via the Referer header) if the browser has Javascript disabled (and thus htmx does not work). This should make post requests work out of the box.
htmxOrReferer :: Wai.Request -> Wai.Response -> Wai.Response
htmxOrReferer req resp = do
let fnd h = req & Wai.requestHeaders & List.find (\(hdr, _) -> hdr == h)
let referer = fnd "Referer"
if
| Just _ <- fnd "Hx-Request" -> resp
| Nothing <- referer -> resp
| Just (_, rfr) <- referer -> do
Wai.responseLBS seeOther303 [("Location", rfr)] ""
-- | Redirect to the given page, if the browser has Javascript enabled use HTMX client side redirect, otherwise use a normal HTTP redirect.
redirectOrFallback :: ByteString -> (Status -> (CI ByteString, ByteString) -> Wai.Response) -> Wai.Request -> Wai.Response
redirectOrFallback target responseFn req = do
let fnd h = req & Wai.requestHeaders & List.find (\(hdr, _) -> hdr == h)
case fnd "Hx-Request" of
Just _ -> responseFn Http.ok200 ("Hx-Redirect", target)
Nothing -> responseFn Http.seeOther303 ("Location", target)
htmlPageChrome :: OurHtmlIntegrities -> Text -> HtmlHead
htmlPageChrome integrities title =
HtmlHead
{ title,
headContent =
[hsx|
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--
prevent favicon request, based on answers in
https://stackoverflow.com/questions/1321878/how-to-prevent-favicon-ico-requests
TODO: create favicon
-->
<link rel="icon" href="data:,">
{integrities.html}
<style>
dl {
margin: 1em;
padding: 0.5em 1em;
border: thin solid;
}
</style>
|]
}
data OurHtmlIntegrities = OurHtmlIntegrities
{ html :: Html,
handlers :: [(Text, HandlerResponse)]
}
prefetchHtmlIntegrities :: App OurHtmlIntegrities
prefetchHtmlIntegrities = do
let resources =
[ HtmlIntegrity
{ integrityName = "Stylize CSS",
integrityUrl = "https://raw.githubusercontent.com/vasanthv/stylize.css/master/stylize.css",
integrityHash = "sha384-EsaVGfq7QMIquv7LCLomD9pQFZbPh2fOY3gcgN9MW/AlV2aQk/miZ1/EbrcwMr67",
localPath = "resources/stylize.css",
provideSourceMap = False,
isTag = e21 #link (),
ignoreUpstreamContentType = True,
-- The upstream repository has been deleted from GitHub, so this
-- can no longer be fetched; see resources/README.md.
vendoredFile = Just "stylize.css"
},
HtmlIntegrity
{ integrityName = "htmx",
integrityUrl = "https://unpkg.com/htmx.org@1.9.2",
integrityHash = "sha384-L6OqL9pRWyyFU3+/bjdSri+iIphTN/bvYyM37tICVyOJkWZLpP2vGn6VUEXgzg6h",
localPath = "resources/htmx.js",
provideSourceMap = False,
isTag = e22 #script (),
ignoreUpstreamContentType = False,
vendoredFile = Nothing
},
HtmlIntegrity
{ integrityName = "howler.js",
integrityUrl = "https://unpkg.com/howler@2.2.4",
integrityHash = "sha384-zh7VMq7y7iAkd4M6bmTa47ENw1qFIjBlwRMNxITqgclnztSAK/ANjxkhRtSoIxFG",
localPath = "resources/howler.js",
provideSourceMap = True,
isTag = e22 #script (),
ignoreUpstreamContentType = False,
vendoredFile = Nothing
}
]
resources
& mapConcurrentlyTraced
( \r ->
prefetchResourceIntegrity r <&> \(html, handler) ->
( html,
[(r.localPath, handler (Arg @"giveSourceMap" False))]
-- a little hacky, we provide an extra handler if there is a source map
<> ifTrue
(r.provideSourceMap)
[(r.localPath <> ".map", handler (Arg @"giveSourceMap" True))]
)
)
<&> fold
<&> \(html, handlers) -> OurHtmlIntegrities {..}
artistPage ::
( HasField "artistRedactedId" dat Int,
HasField "uniqueRunId" dat Text
) =>
dat ->
App Html
artistPage dat = runTransaction $ do
(fresh, settings) <-
concurrentlyTraced
( getBestTorrentsData
bestTorrentsDataDefault
(Just $ E22 (getLabel @"artistRedactedId" dat))
)
(getSettings)
let torrents = mkBestTorrentsTableByReleaseType fresh
let returnUrl =
textToBytesUtf8 $
mkArtistLink (label @"artistId" (dat.artistRedactedId))
let mainContent =
[hsx|
<div id="artist-torrents">
{torrents}
</div>
<form method="post" action="artist/refresh" hx-post="artist/refresh">
<input
hidden
type="text"
name="artist-id"
value={dat.artistRedactedId & buildText intDecimalT}
/>
<button type="submit" hx-disabled-elt="this">Refresh Artist Page</button>
<div class="htmx-indicator">Refreshing!</div>
</form>
|]
pure $
mainHtml'
( MainHtml
{ -- pageTitle,
returnUrl,
counterHtml = "",
mainContent,
uniqueRunId = dat.uniqueRunId,
searchFieldContent = "",
settings
}
)
type Handlers m = Map Text HandlerResponse
data QueryArgsDat a = QueryArgsDat
{ queryArgs :: a,
returnUrl :: ByteString
}
data HtmlHead = HtmlHead
{ title :: Text,
headContent :: Html
}
data HandlerResponse where
-- | render html
Html :: (Otel.Span -> App Html) -> HandlerResponse
-- | either render html or redirect to another page
HtmlOrRedirect :: (Otel.Span -> App (E2 "respond" Html "redirectTo" ByteString)) -> HandlerResponse
-- | render html after parsing some query arguments
HtmlWithQueryArgs :: Parse Query a -> (QueryArgsDat a -> Otel.Span -> App Html) -> HandlerResponse
-- | Redirect (HTTP 302) to the given path or show 404 with error message
HtmlWithQueryArgsRedirect ::
Parse Query a ->
( QueryArgsDat a ->
Otel.Span ->
App
( E3
"err"
Error
"redirectTo"
ByteString
"direct"
(T2 "contentType" Text "bytes" ByteString)
)
) ->
HandlerResponse
-- | render html or reload the page via the Referer header if no htmx
HtmlOrReferer :: (Otel.Span -> App Html) -> HandlerResponse
-- | render html and stream the head before even doing any work in the handler
HtmlStream :: Parse Query a -> (QueryArgsDat a -> Otel.Span -> (App HtmlHead, App Html)) -> HandlerResponse
-- | parse the request as POST submission, then redirect to the given endpoint
PostAndRedirect ::
forall dat.
App (MultipartParseT (AppT IO) dat) ->
(Otel.Span -> dat -> App (Label "redirectTo" ByteString)) ->
HandlerResponse
-- | render a plain wai response
Plain :: App Wai.Response -> HandlerResponse
runHandlers ::
HandlerResponse ->
(Map Text HandlerResponse) ->
Wai.Request ->
(Wai.Response -> IO ResponseReceived) ->
App ResponseReceived
runHandlers defaultHandler handlers req respond = withRunInIO $ \runInIO -> do
let path = req & Wai.pathInfo & Text.intercalate "/"
let inRouteSpan =
Otel.inSpan'
[fmt|Route /{path}|]
( Otel.defaultSpanArguments
{ Otel.attributes =
HashMap.fromList
[ ("_.server.path", Otel.toAttribute @Text path),
("_.server.query_args", Otel.toAttribute @Text (req.rawQueryString & bytesToTextUtf8Lenient))
]
}
)
let html' resp act =
inRouteSpan
( \span -> do
res <- act span <&> (\h -> label @"html" h)
addEventSimple span "Got Html result, rendering…"
liftIO $ respond (resp res)
)
let htmlResp res = Wai.responseLBS Http.ok200 ([("Content-Type", "text/html")]) . Html.renderHtml $ res.html
let html = html' htmlResp
let htmlOrReferer = html' $ \res -> htmxOrReferer req (htmlResp res)
let htmlOrRedirect :: (Otel.Span -> App (E2 "respond" Html "redirectTo" ByteString)) -> App ResponseReceived
htmlOrRedirect = html' $ \res -> case res.html of
E21 h -> htmlResp (label @"html" h.respond)
E22 r ->
redirectOrFallback
r.redirectTo
(\status header -> Wai.responseLBS status [header] "")
req
let redirectOr404 ::
( Otel.Span ->
App
( E3
"err"
Error
"redirectTo"
ByteString
"direct"
(T2 "contentType" Text "bytes" ByteString)
)
) ->
App ResponseReceived
redirectOr404 = html' $ \res ->
res.html
& caseE3
( t3
#err
( \err -> do
Wai.responseLBS Http.notFound404 [("Content-Type", "text/plain")] (err & prettyError & textToBytesUtf8 & toLazyBytes)
)
#redirectTo
(\r -> Wai.responseLBS Http.seeOther303 [("Location", r)] "")
#direct
( \direct -> do
Wai.responseLBS
Http.ok200
[("Content-Type", direct.contentType & textToBytesUtf8)]
(toLazyBytes direct.bytes)
)
)
let postAndRedirect ::
MultipartParseT (AppT IO) dat ->
(Otel.Span -> dat -> App (Label "redirectTo" ByteString)) ->
App ResponseReceived
postAndRedirect parser act = inRouteSpan $ \span -> do
if (req & Wai.requestMethod) == "POST"
then do
dat <- parseMultipartOrThrow span req parser
res <- act span dat
liftIO $ respond (Wai.responseLBS Http.seeOther303 [("Location", res.redirectTo)] "")
else do
liftIO $ respond (Wai.responseLBS Http.methodNotAllowed405 [] "")
let htmlWithQueryArgs' parser =
case req & Parse.runParse "Unable to find the right request query arguments" (lmap Wai.queryString parser) of
Right queryArgs -> Right $ QueryArgsDat {queryArgs, returnUrl = (req & Wai.rawPathInfo) <> (req & Wai.rawQueryString)}
Left err ->
Left
( \span -> do
recordException
span
( T2
(label @"type_" "Query Parse Exception")
(label @"message" (prettyErrorTree err))
)
pure
[hsx|
<h1>Error:</h1>
<pre>{err & prettyErrorTree}</pre>
|]
)
let htmlWithQueryArgs parser act = case htmlWithQueryArgs' parser of
Right dat -> html (act dat)
Left act' -> html act'
let htmlWithQueryArgsRedirect parser act = case htmlWithQueryArgs' parser of
Right dat -> redirectOr404 (act dat)
Left act' -> html act'
let htmlStream :: Parse Query a -> (QueryArgsDat a -> Otel.Span -> (App HtmlHead, App Html)) -> App ResponseReceived
htmlStream parser act = inRouteSpan $ \span -> do
case htmlWithQueryArgs' parser of
Left act' -> html act'
Right dat -> do
let (mkHead, mkBody) = act dat span
-- start the body work (heh) immediately, but stream the head first
withAsyncTraced mkBody $ \bodyAsync -> do
withRunInIO $ \runInIO' -> respond $ Wai.responseStream Http.ok200 [("Content-Type", "text/html")] $ \send flush -> do
runInIO' $ inSpan "sending <head>" $ do
htmlHead <- mkHead
liftIO $ do
send "<!DOCTYPE html>\n"
send "<html>\n"
send $
Html.renderHtmlBuilder $
[hsx|
<head>
<title>{htmlHead.title}</title>
{htmlHead.headContent}
</head>
|]
flush
htmlBody <- liftIO $ wait bodyAsync
send "<body>\n"
send $ Html.renderHtmlBuilder htmlBody
send "</body>\n"
send "</html>\n"
flush
let handler =
handlers
& Map.lookup path
& fromMaybe defaultHandler
& \case
Html act -> html act
HtmlOrRedirect act -> htmlOrRedirect act
HtmlWithQueryArgs parser act -> htmlWithQueryArgs parser act
HtmlWithQueryArgsRedirect parser act -> htmlWithQueryArgsRedirect parser act
HtmlOrReferer act -> htmlOrReferer act
HtmlStream parser act -> htmlStream parser act
PostAndRedirect mParser act -> mParser >>= \parser -> postAndRedirect parser act
Plain act -> liftIO $ runInIO act >>= respond
runInIO handler
singleQueryArgument :: Text -> FieldParser ByteString to -> Parse Http.Query to
singleQueryArgument field inner =
Parse.mkParsePushContext
field
( \qry -> case qry
& mapMaybe
( \(k, v) ->
if k == (field & textToBytesUtf8)
then Just v
else Nothing
) of
[] -> Left [fmt|No such query argument "{field}"|]
[Nothing] -> Left [fmt|Expected one query argument with a value, but "{field}" was a query flag|]
[Just one] -> Right one
more -> Left [fmt|More than one value for query argument "{field}": {show more}|]
)
>>> Parse.fieldParser inner
singleQueryArgumentMay :: Text -> FieldParser ByteString to -> Parse Http.Query (Maybe to)
singleQueryArgumentMay field inner =
Parse.mkParsePushContext
field
( \qry -> case qry
& mapMaybe
( \(k, v) ->
if k == (field & textToBytesUtf8)
then Just v
else Nothing
) of
[] -> Right Nothing
[Nothing] -> Left [fmt|Expected one query argument with a value, but "{field}" was a query flag|]
[Just one] -> Right (Just one)
more -> Left [fmt|More than one value for query argument "{field}": {show more}|]
)
>>> Parse.maybe (Parse.fieldParser inner)
data ArtistFilter = ArtistFilter
{ onlyArtist :: Maybe (Label "artistId" Text)
}
doIfJust :: (Applicative f) => (a -> f ()) -> Maybe a -> f ()
doIfJust = traverse_
data RecommendedTorrentsData = RecommendedTorrentsData
{ limitResults :: Maybe Natural,
disallowedReleaseTypes :: [ReleaseType]
}
recommendedTorrentsDataDefault :: RecommendedTorrentsData
recommendedTorrentsDataDefault =
RecommendedTorrentsData
{ limitResults = Nothing,
disallowedReleaseTypes = []
}
data BestTorrentsData = BestTorrentsData
{ limitResults :: Maybe Natural,
ordering :: BestTorrentsOrdering,
disallowedReleaseTypes :: [ReleaseType],
onlyFavourites :: Bool
}
bestTorrentsDataDefault :: BestTorrentsData
bestTorrentsDataDefault =
BestTorrentsData
{ limitResults = Nothing,
ordering = BySeedingWeight,
disallowedReleaseTypes = [],
onlyFavourites = False
}
-- | Get recommended torrents from similar artists (not already in favorites)
getRecommendedTorrentsData ::
RecommendedTorrentsData ->
AppTransaction [T2 "torrentData" (TorrentData (Label "percentDone" Percentage)) "recommendedBy" [T3 "favoritedArtistId" Int "favoritedArtistName" Text "recommendedArtistId" Int]]
getRecommendedTorrentsData opts = inSpan' "get recommended torrents data" $ \span -> do
-- Get recommendations directly from SQL with all mappings included
recommendationsWithoutPercentage <-
getBestRecommendations
( t2
#disallowedReleaseTypes
opts.disallowedReleaseTypes
#limitResults
opts.limitResults
)
case recommendationsWithoutPercentage of
[] -> do
addAttribute span "recommendations.count" (0 :: Int, intDecimalT)
pure []
recommendations -> do
addAttribute span "recommendations.count" (List.length recommendations, intDecimalT)
-- Apply transmission status updates like in getBestTorrentsData
let torrentsForStatus = recommendations <&> (.torrentData)
(statusInfo, transmissionStatus) <-
getAndUpdateTransmissionTorrentsStatus
( torrentsForStatus
& mapMaybe
( \td -> case td.torrentStatus of
InTransmission h -> Just (getLabel @"torrentHash" h, td)
_ -> Nothing
)
& Map.fromList
)
updatedRecommendations <-
if statusInfo.knownTorrentsStale
then inSpan' "Fetch recommended torrents again" $ \span' -> do
addEventSimple span' "The transmission torrent list was out of date, refetching torrent list."
getBestRecommendations
( t2
#disallowedReleaseTypes
opts.disallowedReleaseTypes
#limitResults
opts.limitResults
)
else pure recommendations
pure $
updatedRecommendations
<&> ( \rec ->
let td = rec.torrentData
updatedTd = case td.torrentStatus of
InTransmission info ->
case transmissionStatus & Map.lookup (getLabel @"torrentHash" info) of
Nothing -> td {torrentStatus = NotInTransmissionYet}
Just transmissionInfo -> td {torrentStatus = InTransmission (T2 (getLabel @"torrentHash" info) (label @"transmissionInfo" transmissionInfo))}
NotInTransmissionYet -> td {torrentStatus = NotInTransmissionYet}
NoTorrentFileYet -> td {torrentStatus = NoTorrentFileYet}
in T2
(label @"torrentData" updatedTd)
(label @"recommendedBy" rec.recommendedBy)
)
getBestTorrentsData ::
BestTorrentsData ->
Maybe (E2 "onlyTheseTorrents" [Label "torrentId" Int] "artistRedactedId" Int) ->
AppTransaction [TorrentData (Label "percentDone" Percentage)]
getBestTorrentsData opts filters = inSpan' "get torrents table data" $ \span -> do
let onlyArtist = label @"artistRedactedId" <$> (filters >>= getE22 @"artistRedactedId")
onlyArtist & doIfJust (\a -> addAttribute span "artist-filter.redacted-id" (a.artistRedactedId, intDecimalT))
let onlyTheseTorrents = filters >>= getE21 @"onlyTheseTorrents"
onlyTheseTorrents & doIfJust (\a -> addAttribute span "torrent-filter.ids" (a <&> (getLabel @"torrentId") & showToText & Otel.toAttribute))
let limitResults = getField @"limitResults" opts
let ordering = opts.ordering
let disallowedReleaseTypes = opts.disallowedReleaseTypes
let onlyFavourites = opts.onlyFavourites
let getBest = getBestTorrents GetBestTorrentsFilter {..}
bestStale :: [TorrentData ()] <- getBest
(statusInfo, transmissionStatus) <-
getAndUpdateTransmissionTorrentsStatus
( bestStale
& mapMaybe
( \td -> case td.torrentStatus of
InTransmission h -> Just (getLabel @"torrentHash" h, td)
_ -> Nothing
)
& Map.fromList
)
bestBest <-
-- Instead of serving a stale table when a torrent gets deleted, fetch
-- the whole view again. This is a little wasteful, but torrents
-- shouldn’t get deleted very often, so it’s fine.
-- Re-evaluate invariant if this happens too often.
if statusInfo.knownTorrentsStale
then inSpan' "Fetch torrents table data again" $
\span' -> do
addEventSimple span' "The transmission torrent list was out of date, refetching torrent list."
getBest
else pure bestStale
pure $
bestBest
-- filter out some kinds we don’t really care about
& filter
( \td ->
td.releaseType
`List.notElem` [ releaseTypeCompilation,
releaseTypeDJMix,
releaseTypeMixtape,
releaseTypeRemix
]
)
-- we have to update the status of every torrent that’s not in tranmission anymore
-- TODO I feel like it’s easier (& more correct?) to just do the database request again …
<&> ( \td -> case td.torrentStatus of
InTransmission info ->
case transmissionStatus & Map.lookup (getLabel @"torrentHash" info) of
-- TODO this is also pretty dumb, cause it assumes that we have the torrent file if it was in transmission before,
-- which is an internal factum that is established in getBestTorrents (and might change later)
Nothing -> td {torrentStatus = NotInTransmissionYet}
Just transmissionInfo -> td {torrentStatus = InTransmission (T2 (getLabel @"torrentHash" info) (label @"transmissionInfo" transmissionInfo))}
NotInTransmissionYet -> td {torrentStatus = NotInTransmissionYet}
NoTorrentFileYet -> td {torrentStatus = NoTorrentFileYet}
)
mkBestTorrentsTableByReleaseType ::
[TorrentData (Label "percentDone" Percentage)] ->
Html
mkBestTorrentsTableByReleaseType fresh =
fresh
& toList
& groupAllWithComparison ((.releaseType) >$< releaseTypeComparison)
& foldMap
( \ts -> do
let releaseType = ts & NonEmpty.head & (.releaseType.stringKey)
mkBestTorrentsTableSection (lbl #sectionName [fmt|{releaseType}s|]) ts
)
mkBestTorrentsTableSection ::
(HasField "sectionName" opts Text) =>
opts ->
NonEmpty (TorrentData (Label "percentDone" Percentage)) ->
Html
mkBestTorrentsTableSection opts torrents = do
let localTorrent b = case b.torrentStatus of
NoTorrentFileYet ->
[hsx|
<form method="post">
<input type="hidden" name="torrent-id" value={b.torrentId & show} />
<button
formaction="snips/redacted/getTorrentFile"
hx-post="snips/redacted/getTorrentFile"
hx-swap="outerHTML"
hx-vals={Enc.encToBytesUtf8 $ Enc.object [("torrent-id", Enc.int b.torrentId)]}>Upload Torrent</button>
</form>
|]
InTransmission info -> [hsx|{info.transmissionInfo.percentDone.unPercentage}% done|]
NotInTransmissionYet -> [hsx|<button hx-post="snips/redacted/startTorrentFile" hx-swap="outerHTML" hx-vals={Enc.encToBytesUtf8 $ Enc.object [("torrent-id", Enc.int b.torrentId)]}>Start Torrent</button>|]
let bestRows :: NonEmpty (TorrentData (Label "percentDone" Percentage)) -> Html
bestRows rowData =
rowData
& foldMap
( \b -> do
let torrentPosition :: Text = [fmt|torrent-{b.torrentId}|]
let artists =
b.artists
<&> ( \a ->
T2
(label @"url" $ mkArtistLink a)
(label @"content" $ Html.toHtml @Text a.artistName)
)
& mkLinkList
let releaseTypeTooltip rt = [fmt|{rt.stringKey} (Release type ID: {rt.intKey})|] :: Text
[hsx|
<tr id={torrentPosition}>
<td>{localTorrent b}</td>
<td>{Html.toHtml @Int b.groupId}</td>
<td>
{artists}
</td>
<td>
<a href={mkRedactedTorrentLink (Arg b.groupId)} target="_blank">
{Html.toHtml @Text b.torrentGroupJson.groupName}
</a>
</td>
<td title={releaseTypeTooltip b.releaseType}>{Html.toHtml @Text b.releaseType.stringKey}</td>
<td>{Html.toHtml @Natural b.torrentGroupJson.groupYear}</td>
<td>{Html.toHtml @Int b.seedingWeight}</td>
<td>{Html.toHtml @Text b.torrentFormat}</td>
<td><details hx-trigger="toggle once" hx-post="snips/redacted/torrentDataJson" hx-vals={Enc.encToBytesUtf8 $ Enc.object [("torrent-id", Enc.int b.torrentId)]}></details></td>
</tr>
|]
)
[hsx|
<h2>{opts.sectionName}</h2>
<table class="table">
<thead>
<tr>
<th>Local</th>
<th>Group ID</th>
<th>Artist</th>
<th>Name</th>
<th>Type</th>
<th>Year</th>
<th>Weight</th>
<th>Format</th>
<th>Torrent</th>
</tr>
</thead>
<tbody>
{bestRows torrents}
</tbody>
</table>
|]
mkRecommendedTorrentsTableSection ::
(HasField "sectionName" opts Text) =>
opts ->
NonEmpty (T2 "torrentData" (TorrentData (Label "percentDone" Percentage)) "recommendedBy" [T3 "favoritedArtistId" Int "favoritedArtistName" Text "recommendedArtistId" Int]) ->
Html
mkRecommendedTorrentsTableSection opts recommendedTorrents = do
let localTorrent b = case b.torrentStatus of
NoTorrentFileYet ->
[hsx|
<form method="post">
<input type="hidden" name="torrent-id" value={b.torrentId & show} />
<button
formaction="snips/redacted/getTorrentFile"
hx-post="snips/redacted/getTorrentFile"
hx-swap="outerHTML"
hx-vals={Enc.encToBytesUtf8 $ Enc.object [("torrent-id", Enc.int b.torrentId)]}>Upload Torrent</button>
</form>
|]
InTransmission info -> [hsx|{info.transmissionInfo.percentDone.unPercentage}% done|]
NotInTransmissionYet -> [hsx|<button hx-post="snips/redacted/startTorrentFile" hx-swap="outerHTML" hx-vals={Enc.encToBytesUtf8 $ Enc.object [("torrent-id", Enc.int b.torrentId)]}>Start Torrent</button>|]
let recommendedRows :: NonEmpty (T2 "torrentData" (TorrentData (Label "percentDone" Percentage)) "recommendedBy" [T3 "favoritedArtistId" Int "favoritedArtistName" Text "recommendedArtistId" Int]) -> Html
recommendedRows rowData =
rowData
& foldMap
( \rec -> do
let b = rec.torrentData
let reasons = rec.recommendedBy
let torrentPosition :: Text = [fmt|torrent-{b.torrentId}|]
let recommendedArtistIds = reasons <&> (.recommendedArtistId) & Set.fromList
let artists =
b.artists
<&> ( \a ->
let isRecommended = a.artistId `Set.member` recommendedArtistIds
content =
if isRecommended
then [hsx|<em>{Html.toHtml @Text a.artistName}</em>|]
else Html.toHtml @Text a.artistName
in T2
(label @"url" $ mkArtistLink a)
(label @"content" content)
)
& mkLinkList
let releaseTypeTooltip rt = [fmt|{rt.stringKey} (Release type ID: {rt.intKey})|] :: Text
let reasonLinks =
reasons
<&> ( \reason ->
T2
(label @"url" $ mkArtistLink (T2 (label @"artistId" reason.favoritedArtistId) (label @"artistName" reason.favoritedArtistName)))
(label @"content" $ Html.toHtml @Text reason.favoritedArtistName)
)
& mkLinkList
[hsx|
<tr id={torrentPosition}>
<td>{localTorrent b}</td>
<td>{Html.toHtml @Int b.groupId}</td>
<td>
{reasonLinks}
</td>
<td>
{artists}
</td>
<td>
<a href={mkRedactedTorrentLink (Arg b.groupId)} target="_blank">
{Html.toHtml @Text b.torrentGroupJson.groupName}
</a>
</td>
<td title={releaseTypeTooltip b.releaseType}>{Html.toHtml @Text b.releaseType.stringKey}</td>
<td>{Html.toHtml @Natural b.torrentGroupJson.groupYear}</td>
<td>{Html.toHtml @Int b.seedingWeight}</td>
<td>{Html.toHtml @Text b.torrentFormat}</td>
<td><details hx-trigger="toggle once" hx-post="snips/redacted/torrentDataJson" hx-vals={Enc.encToBytesUtf8 $ Enc.object [("torrent-id", Enc.int b.torrentId)]}></details></td>
</tr>
|]
)
[hsx|
<h2>{opts.sectionName}</h2>
<form action="populate-recommendations" method="post" style="margin-bottom: 1em;">
<button type="submit" hx-disabled-elt="this">
Fetch New Recommendations
</button>
<div class="htmx-indicator">Fetching recommendations...</div>
</form>
<table class="table">
<thead>
<tr>
<th>Local</th>
<th>Group ID</th>
<th>Reason</th>
<th>Artist</th>
<th>Name</th>
<th>Type</th>
<th>Year</th>
<th>Weight</th>
<th>Format</th>
<th>Torrent</th>
</tr>
</thead>
<tbody>
{recommendedRows recommendedTorrents}
</tbody>
</table>
|]
mkLinkList :: [T2 "url" Text "content" Html] -> Html
mkLinkList xs =
xs
<&> ( \x -> do
[hsx|<a href={x.url}>{x.content}</a>|]
)
& List.intersperse ", "
& mconcat
mkArtistLink :: (HasField "artistId" r Int) => r -> Text
mkArtistLink a = [fmt|/artist?redacted_id={a.artistId}|]
getTransmissionTorrentsTable ::
App Html
getTransmissionTorrentsTable = do
let fields =
[ "hashString",
"name",
"percentDone",
"percentComplete",
"downloadDir",
"files"
]
doTransmissionRequest'
( transmissionRequestListAllTorrents fields $ do
Json.asObject <&> KeyMap.toMapText
)
<&> \resp ->
Html.toTable
( resp
& List.sortOn (\m -> m & Map.lookup "percentDone" & fromMaybe (Json.Number 0))
<&> Map.toList
-- TODO
& List.take 100
)
unzip3PGArray :: [(a1, a2, a3)] -> (PGArray a1, PGArray a2, PGArray a3)
unzip3PGArray xs = xs & unzip3 & \(a, b, c) -> (PGArray a, PGArray b, PGArray c)
assertOneUpdated ::
(HasField "numberOfRowsAffected" r Natural) =>
Otel.Span ->
Text ->
r ->
App ()
assertOneUpdated span name x = case x.numberOfRowsAffected of
1 -> pure ()
n -> appThrow span ([fmt|{name :: Text}: Expected to update exactly one row, but updated {n :: Natural} row(s)|])
migrate ::
AppTransaction (Label "numberOfRowsAffected" Natural)
migrate = inSpan "Database Migration" $ do
execute
[sql|
CREATE SCHEMA IF NOT EXISTS redacted;
CREATE TABLE IF NOT EXISTS redacted.settings (
id SERIAL PRIMARY KEY,
key TEXT NOT NULL UNIQUE,
value JSONB
);
CREATE TABLE IF NOT EXISTS redacted.torrent_groups (
id SERIAL PRIMARY KEY,
group_id INTEGER,
group_name TEXT,
full_json_result JSONB,
UNIQUE(group_id)
);
CREATE TABLE IF NOT EXISTS redacted.torrents_json (
id SERIAL PRIMARY KEY,
torrent_id INTEGER,
torrent_group SERIAL NOT NULL REFERENCES redacted.torrent_groups(id) ON DELETE CASCADE,
full_json_result JSONB,
UNIQUE(torrent_id)
);
CREATE INDEX IF NOT EXISTS redacted_torrents_json_torrent_group_fk ON redacted.torrents_json (torrent_group);
ALTER TABLE redacted.torrents_json
ADD COLUMN IF NOT EXISTS torrent_file bytea NULL;
ALTER TABLE redacted.torrents_json
ADD COLUMN IF NOT EXISTS transmission_torrent_hash text NULL;
-- the seeding weight is used to find the best torrent in a group.
CREATE OR REPLACE FUNCTION calc_seeding_weight(full_json_result jsonb) RETURNS int AS $$
BEGIN
RETURN
-- three times seeders plus one times snatches
(3 * (full_json_result->'seeders')::integer
+ (full_json_result->'snatches')::integer
)
-- prefer remasters by multiplying them with 3
* (CASE
WHEN full_json_result->>'remasterTitle' ILIKE '%remaster%'
THEN 3
ELSE 1
END)
-- slightly push mp3 V0, to make sure it’s preferred over 320 CBR
* (CASE
WHEN full_json_result->>'encoding' ILIKE '%v0%'
THEN 2
ELSE 1
END)
-- remove 24bit torrents from the result (wayyy too big)
* (CASE
WHEN full_json_result->>'encoding' ILIKE '%24bit%'
THEN 0
ELSE 1
END)
-- discount FLACS, so we only use them when there’s no mp3 alternative (to save space)
/ (CASE
WHEN full_json_result->>'encoding' ILIKE '%lossless%'
THEN 5
ELSE 1
END)
;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
ALTER TABLE redacted.torrents_json
ADD COLUMN IF NOT EXISTS seeding_weight int NOT NULL GENERATED ALWAYS AS (calc_seeding_weight(full_json_result)) STORED;
CREATE OR REPLACE FUNCTION artist_record_to_id(artists jsonb) RETURNS int[]
as $$
SELECT array_agg(x::int) from jsonb_path_query(artists, '$[*].id') j(x);
$$ LANGUAGE sql IMMUTABLE;
ALTER TABLE redacted.torrents_json
ADD COLUMN IF NOT EXISTS artist_ids int[] NOT NULL GENERATED ALWAYS AS (COALESCE(artist_record_to_id(full_json_result->'artists'), ARRAY[]::int[])) STORED;
CREATE INDEX IF NOT EXISTS torrents_json_artist_ids ON redacted.torrents_json USING GIN (artist_ids);
-- inflect out values of the full json.
CREATE OR REPLACE VIEW redacted.torrents AS
SELECT
t.id,
t.torrent_id,
t.torrent_group,
-- the seeding weight is used to find the best torrent in a group.
t.seeding_weight,
t.full_json_result,
t.torrent_file,
t.transmission_torrent_hash,
t.artist_ids
FROM redacted.torrents_json t;
CREATE INDEX IF NOT EXISTS torrents_json_seeding ON redacted.torrents_json(((full_json_result->'seeding')::integer));
CREATE INDEX IF NOT EXISTS torrents_json_snatches ON redacted.torrents_json(((full_json_result->'snatches')::integer));
CREATE TABLE IF NOT EXISTS redacted.artist_favourites (
id SERIAL PRIMARY KEY,
artist_id INTEGER NOT NULL,
UNIQUE(artist_id)
);
-- table for storing related/similar artists from the API
CREATE TABLE IF NOT EXISTS redacted.similar_artists (
id SERIAL PRIMARY KEY,
artist_id INTEGER NOT NULL,
similar_artist_id INTEGER NOT NULL,
similar_artist_name TEXT NOT NULL,
score INTEGER NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(artist_id, similar_artist_id)
);
CREATE INDEX IF NOT EXISTS similar_artists_artist_id_idx ON redacted.similar_artists (artist_id);
CREATE INDEX IF NOT EXISTS similar_artists_similar_artist_id_idx ON redacted.similar_artists (similar_artist_id);
-- fast lookup table for artist id -> name mapping
CREATE TABLE IF NOT EXISTS redacted.artists (
artist_id INTEGER PRIMARY KEY,
artist_name TEXT NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Note: The slow artist_names view has been replaced by the fast redacted.artists table
|]
()
runAppWith :: AppT IO a -> IO (Either TmpPg.StartError a)
runAppWith appT = withTracer $ \tracer -> withDb $ \db -> do
tool <-
readTools
(label @"toolsEnvVar" "WHATCD_RESOLVER_TOOLS")
( do
pgFormat <- readTool "pg_format"
exiftool <- readTool "exiftool"
pure $ t2 #pgFormat pgFormat #exiftool exiftool
)
prettyPrintDatabaseQueries <-
Env.lookupEnv "WHATCD_RESOLVER_PRETTY_PRINT_DATABASE_QUERIES" >>= \case
Nothing -> pure DontPrettyPrintDatabaseQueries
Just _ -> do
pgFormat <- initPgFormatPool (label @"pgFormat" tool.pgFormat)
pure $ PrettyPrintDatabaseQueries pgFormat
let pgConfig =
T2
(label @"logDatabaseQueries" LogDatabaseQueries)
(label @"prettyPrintDatabaseQueries" prettyPrintDatabaseQueries)
pgConnPool <-
Pool.newPool $
Pool.defaultPoolConfig
{- resource init action -} ( OtelCore.inSpan
tracer
"Postgres: Create Connection"
Otel.defaultSpanArguments
(Postgres.connectPostgreSQL (db & TmpPg.toConnectionString))
)
{- resource destruction -} ( \conn ->
OtelCore.inSpan
tracer
"Postgres: Destroy Connection"
Otel.defaultSpanArguments
(Postgres.close conn)
)
{- unusedResourceOpenTime -} 600
{- max resources across all stripes -} 20
transmissionSessionId <- newIORef Nothing
redactedApiKey <-
Env.lookupEnv "WHATCD_RESOLVER_REDACTED_API_KEY" >>= \case
Just k -> pure (k & stringToBytesUtf8)
Nothing -> runStderrLoggingT $ do
logInfo "WHATCD_RESOLVER_REDACTED_API_KEY was not set, trying pass"
runCommandExpect0 "pass" ["internet/redacted/api-keys/whatcd-resolver"]
transmissionDownloadDirectory <- do
mPath <- Env.lookupEnv "WHATCD_RESOLVER_TRANSMISSION_DOWNLOAD_DIRECTORY"
case mPath of
Nothing -> pure $ Left [fmt|WHATCD_RESOLVER_TRANSMISSION_DOWNLOAD_DIRECTORY not set, no file streaming available|]
Just path -> do
Dir.doesDirectoryExist path >>= \case
False -> pure $ Left [fmt|WHATCD_RESOLVER_TRANSMISSION_DOWNLOAD_DIRECTORY directory does not exist: {path}, no file streaming available|]
True -> pure $ Right path
let newAppT = do
logInfo [fmt|Running with config: {showPretty pgConfig}|]
logInfo [fmt|Connected to database at {db & TmpPg.toDataDirectory} on socket {db & TmpPg.toConnectionString}|]
case transmissionDownloadDirectory of
Left errmsg -> logInfo errmsg
Right dir -> logInfo [fmt|Streaming torrent files from {dir}|]
appT
runReaderT
newAppT.unAppT
Context
{ tools = Tools {exiftool = tool.exiftool},
transmissionDownloads =
transmissionDownloadDirectory
<&> ( \dir ->
t2
#downloadDirectory
dir
#staticFileEndpoint
"/files"
)
& hush,
..
}
`catch` ( \case
AppExceptionPretty p -> throwM $ EscapedException (p & Pretty.prettyErrs)
AppExceptionTree t -> throwM $ EscapedException (t & prettyErrorTree & textToString)
AppExceptionEnc e -> throwM $ EscapedException (e & Enc.encToTextPrettyColored & textToString)
)
-- | Just a silly wrapper so that correctly format any 'AppException' that would escape the runAppWith scope.
newtype EscapedException = EscapedException String
deriving anyclass (Exception)
instance Show EscapedException where
show (EscapedException s) = s
withTracer :: (Otel.Tracer -> IO c) -> IO c
withTracer f = do
setDefaultEnv "OTEL_SERVICE_NAME" "whatcd-resolver"
bracket
-- Install the SDK, pulling configuration from the environment
( do
(processors, opts) <- Otel.getTracerProviderInitializationOptions
tp <-
Otel.createTracerProvider
processors
-- workaround the attribute length bug https://github.com/iand675/hs-opentelemetry/issues/113
( opts
{ Otel.tracerProviderOptionsAttributeLimits =
opts.tracerProviderOptionsAttributeLimits
{ Otel.attributeCountLimit = Just 65_000
}
}
)
Otel.setGlobalTracerProvider tp
pure tp
)
-- Ensure that any spans that haven't been exported yet are flushed
Otel.shutdownTracerProvider
-- Get a tracer so you can create spans
(\tracerProvider -> f $ Otel.makeTracer tracerProvider "whatcd-resolver" Otel.tracerOptions)
setDefaultEnv :: String -> String -> IO ()
setDefaultEnv envName defaultValue = do
Env.lookupEnv envName >>= \case
Just _env -> pure ()
Nothing -> Env.setEnv envName defaultValue
withDb :: (TmpPg.DB -> IO a) -> IO (Either TmpPg.StartError a)
withDb act = do
dataDir <- Xdg.getXdgDirectory Xdg.XdgData "whatcd-resolver"
let databaseDir = dataDir </> "database"
let socketDir = dataDir </> "database-socket"
Dir.createDirectoryIfMissing True socketDir
initDbConfig <-
Dir.doesDirectoryExist databaseDir >>= \case
True -> pure TmpPg.Zlich
False -> do
putStderrLn [fmt|Database does not exist yet, creating in "{databaseDir}"|]
Dir.createDirectoryIfMissing True databaseDir
pure TmpPg.DontCare
let cfg =
mempty
{ TmpPg.dataDirectory = TmpPg.Permanent (databaseDir),
TmpPg.socketDirectory = TmpPg.Permanent socketDir,
TmpPg.port = pure $ Just 5431,
TmpPg.initDbConfig,
TmpPg.postgresConfigFile =
[ ("shared_buffers", "2GB"),
("work_mem", "32MB"),
("effective_cache_size", "10GB"),
("maintenance_work_mem", "128MB"),
("wal_buffers", "512kB"),
("random_page_cost", "1.1")
]
}
TmpPg.withConfig cfg $ \db -> do
-- print [fmt|data dir: {db & TmpPg.toDataDirectory}|]
-- print [fmt|conn string: {db & TmpPg.toConnectionString}|]
act db
data Settings = Settings
{ freelechTokensExhaustedAt :: Maybe UTCTime
}
deriving stock (Generic, Show)
deriving anyclass (Json.FromJSON, Json.ToJSON)
instance Semigroup Settings where
a <> b = Settings {freelechTokensExhaustedAt = a.freelechTokensExhaustedAt <|> b.freelechTokensExhaustedAt}
instance Monoid Settings where
mempty = Settings {freelechTokensExhaustedAt = Nothing}
getSettings :: AppTransaction Settings
getSettings = inSpan' "Get Settings" $ \span -> do
res <-
foldRowsWithMonoid
[sql|
SELECT key, value
FROM redacted.settings
|]
()
( do
key <- Dec.text
Dec.jsonMay
( case key of
"freelechTokensExhaustedAt" -> do
freelechTokensExhaustedAt <-
( Field.toJsonParser $
Field.mapError singleError $
Field.jsonString >>> Field.utcTime
)
pure $
Settings
{ freelechTokensExhaustedAt = Just freelechTokensExhaustedAt
}
_ -> pure mempty
)
<&> fromMaybe mempty
)
lift $ addAttribute span "settings" (toOtelAttrGenericStruct res)
pure res
writeSettings ::
[T2 "key" Text "val" Json.Value] ->
AppTransaction (Label "numberOfRowsAffected" Natural)
writeSettings settings = inSpan' "Write Settings" $ \span -> do
addAttribute
span
"settings"
( toOtelJsonAttr $
Enc.list
(\s -> Enc.tuple2 Enc.text Enc.value (s.key, s.val))
settings
)
execute
[sql|
INSERT INTO redacted.settings (key, value)
SELECT * FROM UNNEST(?::text[], ?::jsonb[])
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value
|]
(settings & unzipPGArray @"key" @Text @"val" @Json.Value)
-- | Given a conduit that produces Html,
-- return a htmx html snippet which will regularly poll for new results in the conduit,
-- and a handler endpoint that returns the newest output when it happens.
conduitToHtmx ::
(HasField "endpoint" opts Text, MonadUnliftIO m) =>
opts ->
-- | initial inner html
Html ->
ConduitT () Html m () ->
m (m Html, HandlerResponse, Async.Async ())
conduitToHtmx opts init' conduit = do
let htmlPolling inner =
[hsx|
<div hx-get={opts.endpoint} hx-trigger="every 1s" hx-swap="outerHTML">
{inner :: Html}
</div>
|]
currentHtml <- newIORef $! htmlPolling init'
collectorHandle <- Async.async $ do
liftIO $ putStderrLn "spawned async collector"
lastVal <-
conduit
.| Conduit.mapMC
( \html -> do
atomicWriteIORef currentHtml $! (htmlPolling html)
pure html
)
.| Conduit.lastDefC init'
& Conduit.runConduit
-- when the original conduit finishes, we stop polling for updates.
atomicWriteIORef currentHtml $! [hsx|<div>{lastVal}</div>|]
let handler = Html $ \_span -> do
-- TODO: can we use Etags here and return 304 instead?
readIORef currentHtml
pure (readIORef currentHtml, handler, collectorHandle)
testCounter ::
(HasField "endpoint" opts Text, MonadUnliftIO m) =>
opts ->
m (m Html, HandlerResponse, Async ())
testCounter opts = conduitToHtmx opts [hsx|<p>0</p>|] counterConduit
counterConduit :: (MonadIO m) => ConduitT i Html m ()
counterConduit =
Conduit.yieldMany [0 .. 100]
.| Conduit.awaitForever
( \(i :: Int) -> do
threadDelay 300_000
Conduit.yield [hsx|<p>{i}</p>|]
)
data HtmlIntegrity = HtmlIntegrity
{ -- | The name of the resource, for debugging purposes
integrityName :: Text,
-- | The URL of the resource content
integrityUrl :: Text,
-- | The integrity hash of the resource
integrityHash :: Text,
-- | The local url path to fetch the cached resource from the frontend
localPath :: Text,
-- | Whether there is a resource map at the URL + `.map`
provideSourceMap :: Bool,
-- | is @<link>@ or @<script>@ tag?
isTag :: E2 "link" () "script" (),
-- | ignore upstream content type
ignoreUpstreamContentType :: Bool,
-- | If set, read the resource from this file in the resources directory
-- instead of fetching 'integrityUrl'.
--
-- Needed for resources whose upstream has disappeared; see
-- @resources/README.md@.
vendoredFile :: Maybe Text
}
-- | Fetch a resource, calculate its integrity hash, and return a html @<link>@ snippet and a handler to return the resource.
prefetchResourceIntegrity :: HtmlIntegrity -> App (Html, (Arg "giveSourceMap" Bool) -> HandlerResponse)
prefetchResourceIntegrity dat = inSpan' [fmt|prefetching resource {dat.integrityName}|] $ \span -> do
-- A vendored resource is read from disk; there is nothing to fetch and no
-- upstream content type to consider.
(statusCode, mContentType, bodyStrict) <- case dat.vendoredFile of
Just fileName -> do
dir <-
liftIO (Env.lookupEnv "WHATCD_RESOLVER_RESOURCES")
<&> annotate [fmt|WHATCD_RESOLVER_RESOURCES is not set, cannot read vendored resource "{fileName}"|]
>>= \case
Left err -> appThrow span (AppExceptionTree $ singleError err)
Right d -> pure d
bytes <- liftIO $ ByteString.readFile (dir </> textToString fileName)
pure (200 :: Int, Nothing, bytes)
Nothing -> do
let x =
dat.integrityUrl
& Parse.runParse "Failed to parse URI" (textToURI >>> uriToHttpClientRequest)
& unwrapErrorTree
resp <- Http.httpBS x
let !code = resp & Http.responseStatus & (.statusCode)
let !ct =
resp
& Http.responseHeaders
& List.lookup "content-type"
<&> parseContentType
<&> (\(!c, _mimeAttributes) -> c)
let !body = resp & Http.responseBody
when (code /= 200) $
appThrow span $
AppExceptionPretty [[fmt|Server returned an non-200 error code, code {code}:|], pretty resp]
pure (code, ct, body)
let !bodyLength = bodyStrict & ByteString.length
if
| statusCode == 200 -> do
let tagMatch prx1 val1 prx2 val2 =
dat.isTag
& caseE2
( t2
prx1
(\() -> val1)
prx2
(\() -> val2)
)
mSourceMap <-
if
| dat.provideSourceMap -> do
inSpan' [fmt|Get Source Map for {dat.integrityName}|] $ \span' -> do
let sourceMapUrl = dat.integrityUrl <> ".map"
let x' =
sourceMapUrl
& Parse.runParse "Failed to parse URI" (textToURI >>> uriToHttpClientRequest)
& unwrapErrorTree
resp' <- Http.httpBS x'
let !statusCode' = resp' & Http.responseStatus & (.statusCode)
if
| statusCode' == 200 -> do
pure $ Just <$> resp' & Http.responseBody
-- if it does not exist, let’s 404 as well
| statusCode' == 404 -> do
pure Nothing
| otherwise -> do
appThrow span' $ AppExceptionPretty [[fmt|Failed to fetch source map, got status code {statusCode'}|]]
| otherwise -> pure Nothing
pure
( tagMatch
#link
[hsx|<link rel="stylesheet" href={dat.localPath} integrity={dat.integrityHash} crossorigin="anonymous">|]
#script
[hsx|<script src={dat.localPath} integrity={dat.integrityHash} crossorigin="anonymous"></script>|],
\(Arg giveSourceMap) -> Plain $ do
if
| giveSourceMap,
Just sourceMap <- mSourceMap -> do
pure $
Wai.responseLBS
Http.ok200
[ ( "Content-Type",
"application/json"
),
("Content-Length", buildBytes intDecimalB (ByteString.length sourceMap))
]
(toLazyBytes sourceMap)
| giveSourceMap -> do
pure $ Wai.responseLBS Http.notFound404 [] ""
| otherwise -> do
pure $
Wai.responseLBS
Http.ok200
[ ( "Content-Type",
(if dat.ignoreUpstreamContentType then mempty else mContentType)
& fromMaybe
( tagMatch
#script
"text/javascript; charset=UTF-8"
#link
"text/css; charset=UTF-8"
)
),
("Content-Length", buildBytes intDecimalB bodyLength)
]
(toLazyBytes $ bodyStrict)
)
| code <- statusCode -> appThrow span $ AppExceptionPretty [[fmt|Resource fetch returned an non-200 error code, code {code}|]]
|