diff options
Diffstat (limited to 'fun')
96 files changed, 6817 insertions, 0 deletions
diff --git a/fun/amsterdump/default.nix b/fun/amsterdump/default.nix new file mode 100644 index 000000000000..0d98c9a7ab93 --- /dev/null +++ b/fun/amsterdump/default.nix @@ -0,0 +1,13 @@ +{ depot, ... }: + +depot.nix.buildGo.program { + name = "amsterdump"; + srcs = [ + ./main.go + ]; + + deps = with depot.third_party; map (p: p.gopkg) [ + # gopkgs."golang.org".x.oauth2.google + gopkgs."googlemaps.github.io".maps + ]; +} diff --git a/fun/amsterdump/listings-20200105.json b/fun/amsterdump/listings-20200105.json new file mode 100644 index 000000000000..251598312a31 --- /dev/null +++ b/fun/amsterdump/listings-20200105.json @@ -0,0 +1,2326 @@ +[ + { + "address": "Sumatrakade 577, 1019 PS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87026792-sumatrakade-577/?navigateSource=toppositie", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.5 km", + "value": 20475 + }, + "duration": { + "value": 2467, + "text": "41m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.2 km", + "value": 3187 + }, + "duration": { + "value": 727, + "text": "12m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Spuistraat 253, 1012 VR Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-86705763-spuistraat-253-hs/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.2 km", + "value": 14151 + }, + "duration": { + "value": 1901, + "text": "31m41s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.5 km", + "value": 1459 + }, + "duration": { + "value": 522, + "text": "8m42s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Melis Stokehof 84, 1064 JE Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87036254-melis-stokehof-84/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "16.1 km", + "value": 16086 + }, + "duration": { + "value": 2166, + "text": "36m6s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "7.3 km", + "value": 7317 + }, + "duration": { + "value": 1772, + "text": "29m32s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Churchill-laan 91D, 1078 DK Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41533400-churchill-laan-91-d/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "11.6 km", + "value": 11590 + }, + "duration": { + "value": 1921, + "text": "32m1s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.7 km", + "value": 5749 + }, + "duration": { + "value": 1609, + "text": "26m49s" + }, + "duration_in_traffic": null + } + }, + { + "address": "De Boelelaan 745, 1082 RS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41687804-de-boelelaan-745/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "9.5 km", + "value": 9466 + }, + "duration": { + "value": 907, + "text": "15m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.7 km", + "value": 6659 + }, + "duration": { + "value": 1147, + "text": "19m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Leeuwendalersweg 15G, 1055 JE Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41679332-leeuwendalersweg-15-g/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "11.4 km", + "value": 11359 + }, + "duration": { + "value": 1596, + "text": "26m36s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.5 km", + "value": 6526 + }, + "duration": { + "value": 1364, + "text": "22m44s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Singel 449, 1012 XG Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87899154-singel-449-1/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.2 km", + "value": 14169 + }, + "duration": { + "value": 1911, + "text": "31m51s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.9 km", + "value": 1945 + }, + "duration": { + "value": 568, + "text": "9m28s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Jan van Zutphenstraat 211, 1069 RR Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41671501-jan-van-zutphenstraat-211/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "10.2 km", + "value": 10160 + }, + "duration": { + "value": 1647, + "text": "27m27s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "9.1 km", + "value": 9145 + }, + "duration": { + "value": 2311, + "text": "38m31s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Parnassusweg 977, Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41670908-parnassusweg-977/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "9.6 km", + "value": 9578 + }, + "duration": { + "value": 996, + "text": "16m36s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.8 km", + "value": 6780 + }, + "duration": { + "value": 1236, + "text": "20m36s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Esplanade de Meer 179, 1098 WJ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87995311-esplanade-de-meer-179/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "17.4 km", + "value": 17441 + }, + "duration": { + "value": 2107, + "text": "35m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "7.0 km", + "value": 6989 + }, + "duration": { + "value": 1600, + "text": "26m40s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Hoofdweg 538, 1055 AB Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41521204-hoofdweg-538/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.1 km", + "value": 14073 + }, + "duration": { + "value": 1892, + "text": "31m32s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.5 km", + "value": 6468 + }, + "duration": { + "value": 1320, + "text": "22m0s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Hoofdweg 538, 1055 AB Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41521204-hoofdweg-538/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.1 km", + "value": 14073 + }, + "duration": { + "value": 1892, + "text": "31m32s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.5 km", + "value": 6468 + }, + "duration": { + "value": 1320, + "text": "22m0s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Hoofdweg 538, 1055 AB Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41521204-hoofdweg-538/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.1 km", + "value": 14073 + }, + "duration": { + "value": 1892, + "text": "31m32s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.5 km", + "value": 6468 + }, + "duration": { + "value": 1320, + "text": "22m0s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Annie Romeinplein 18, 1103 JL Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87985710-annie-romeinplein-18/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "17.4 km", + "value": 17402 + }, + "duration": { + "value": 1869, + "text": "31m9s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "10.1 km", + "value": 10129 + }, + "duration": { + "value": 1308, + "text": "21m48s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Vechtstraat 185, 1079 JJ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41512041-vechtstraat-185-ii/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "11.9 km", + "value": 11877 + }, + "duration": { + "value": 1876, + "text": "31m16s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "7.0 km", + "value": 6992 + }, + "duration": { + "value": 2142, + "text": "35m42s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Westerdok 240, 1013 BH Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41553306-westerdok-240/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "18.3 km", + "value": 18332 + }, + "duration": { + "value": 1816, + "text": "30m16s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.7 km", + "value": 1748 + }, + "duration": { + "value": 715, + "text": "11m55s" + }, + "duration_in_traffic": null + } + }, + { + "address": "IJburglaan 701, 1087 BS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87898167-ijburglaan-701/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "24.5 km", + "value": 24471 + }, + "duration": { + "value": 2556, + "text": "42m36s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "7.1 km", + "value": 7097 + }, + "duration": { + "value": 935, + "text": "15m35s" + }, + "duration_in_traffic": null + } + }, + { + "address": "IJdoornlaan 1497, 1034 Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87041092-ijdoornlaan-1497-a/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.5 km", + "value": 19524 + }, + "duration": { + "value": 2620, + "text": "43m40s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.7 km", + "value": 4704 + }, + "duration": { + "value": 1139, + "text": "18m59s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Sumatrakade 577, 1019 PS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87026792-sumatrakade-577/?navigateSource=toppositie", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.5 km", + "value": 20475 + }, + "duration": { + "value": 2467, + "text": "41m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.2 km", + "value": 3187 + }, + "duration": { + "value": 727, + "text": "12m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "George Sliekerkade 18, 1087 KK Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87030790-george-sliekerkade-18/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "24.8 km", + "value": 24761 + }, + "duration": { + "value": 2843, + "text": "47m23s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "8.0 km", + "value": 7958 + }, + "duration": { + "value": 1183, + "text": "19m43s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Sumatrakade 265, 1019 PK Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41662773-sumatrakade-265/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.6 km", + "value": 20638 + }, + "duration": { + "value": 2587, + "text": "43m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.4 km", + "value": 3350 + }, + "duration": { + "value": 847, + "text": "14m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Koggestraat 5, 1012 TA Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41531104-koggestraat-5-2/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "17.9 km", + "value": 17938 + }, + "duration": { + "value": 1748, + "text": "29m8s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.0 km", + "value": 981 + }, + "duration": { + "value": 393, + "text": "6m33s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Warmoesstraat 139B, 1012 JB Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41524099-warmoesstraat-139-b/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "18.1 km", + "value": 18072 + }, + "duration": { + "value": 1835, + "text": "30m35s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.0 km", + "value": 964 + }, + "duration": { + "value": 315, + "text": "5m15s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Parnassusweg 35, 1077 Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41579167-parnassusweg-35-i/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "10.0 km", + "value": 9986 + }, + "duration": { + "value": 1329, + "text": "22m9s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.8 km", + "value": 5754 + }, + "duration": { + "value": 1568, + "text": "26m8s" + }, + "duration_in_traffic": null + } + }, + { + "address": "De Boelelaan 389, 1082 RH Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87890510-de-boelelaan-389/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "9.6 km", + "value": 9650 + }, + "duration": { + "value": 1048, + "text": "17m28s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.9 km", + "value": 6852 + }, + "duration": { + "value": 1288, + "text": "21m28s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Theo Frenkelhof 96, 1087 JA Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87995272-theo-frenkelhof-96/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "24.9 km", + "value": 24874 + }, + "duration": { + "value": 2928, + "text": "48m48s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "8.1 km", + "value": 8101 + }, + "duration": { + "value": 1268, + "text": "21m8s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Veembroederhof 207, 1019 HD Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41539826-veembroederhof-207/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.7 km", + "value": 19731 + }, + "duration": { + "value": 2402, + "text": "40m2s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.8 km", + "value": 1845 + }, + "duration": { + "value": 501, + "text": "8m21s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Nieuwe Passeerdersstraat 174, 1016 XP Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41537370-nieuwe-passeerdersstraat-174/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "12.3 km", + "value": 12345 + }, + "duration": { + "value": 1885, + "text": "31m25s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.9 km", + "value": 2937 + }, + "duration": { + "value": 978, + "text": "16m18s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Jan van Galenstraat 1K, 1051 KE Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41513735-jan-van-galenstraat-1-k/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.0 km", + "value": 14042 + }, + "duration": { + "value": 2071, + "text": "34m31s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.1 km", + "value": 4104 + }, + "duration": { + "value": 859, + "text": "14m19s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Joan Melchior Kemperstraat 128, 1051 TX Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87924023-joan-melchior-kemperstraat-128-3/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "15.6 km", + "value": 15558 + }, + "duration": { + "value": 2675, + "text": "44m35s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.2 km", + "value": 4220 + }, + "duration": { + "value": 1015, + "text": "16m55s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Javakade 560, 1019 SE Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41438193-javakade-560/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.2 km", + "value": 20218 + }, + "duration": { + "value": 2508, + "text": "41m48s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.1 km", + "value": 2114 + }, + "duration": { + "value": 718, + "text": "11m58s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Saxen Weimarlaan 32, 1075 BZ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41427768-saxen-weimarlaan-32-ii/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "13.7 km", + "value": 13707 + }, + "duration": { + "value": 1836, + "text": "30m36s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.5 km", + "value": 5516 + }, + "duration": { + "value": 1557, + "text": "25m57s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Zeedijk 125C, 1012 AW Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87892979-zeedijk-125-c/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "18.1 km", + "value": 18074 + }, + "duration": { + "value": 1845, + "text": "30m45s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.0 km", + "value": 1031 + }, + "duration": { + "value": 269, + "text": "4m29s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Sumatrakade 577, 1019 PS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87026792-sumatrakade-577/?navigateSource=toppositie", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.5 km", + "value": 20475 + }, + "duration": { + "value": 2467, + "text": "41m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.2 km", + "value": 3187 + }, + "duration": { + "value": 727, + "text": "12m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Revaleiland 89, 1013 AX Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41685704-revaleiland-89/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.0 km", + "value": 20043 + }, + "duration": { + "value": 2208, + "text": "36m48s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.2 km", + "value": 3244 + }, + "duration": { + "value": 941, + "text": "15m41s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Rozengracht 42A, 1016 ND Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41685113-rozengracht-42-a/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "13.2 km", + "value": 13195 + }, + "duration": { + "value": 1977, + "text": "32m57s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.8 km", + "value": 1826 + }, + "duration": { + "value": 621, + "text": "10m21s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Rembrandtplein 7, 1017 CV Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87903367-rembrandtplein-7-1/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.3 km", + "value": 14276 + }, + "duration": { + "value": 1998, + "text": "33m18s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.0 km", + "value": 2033 + }, + "duration": { + "value": 574, + "text": "9m34s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Leenhofstraat 69, 1067 LA Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41576354-leenhofstraat-69-4/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.1 km", + "value": 14143 + }, + "duration": { + "value": 2126, + "text": "35m26s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "10.4 km", + "value": 10374 + }, + "duration": { + "value": 1974, + "text": "32m54s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Bolestein 300, 1081 ED Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41575228-bolestein-300/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "12.1 km", + "value": 12120 + }, + "duration": { + "value": 1939, + "text": "32m19s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "12.2 km", + "value": 12165 + }, + "duration": { + "value": 1692, + "text": "28m12s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Westerdoksdijk 263b, 1013 AD Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41562746-westerdoksdijk-263-b-pp/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "18.2 km", + "value": 18157 + }, + "duration": { + "value": 1687, + "text": "28m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.4 km", + "value": 1358 + }, + "duration": { + "value": 420, + "text": "7m0s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Brederodestraat 89, 1054 VC Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87916974-brederodestraat-89-hs/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "10.4 km", + "value": 10450 + }, + "duration": { + "value": 1677, + "text": "27m57s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.4 km", + "value": 4382 + }, + "duration": { + "value": 1384, + "text": "23m4s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Kon. Wilhelminaplein 222, 1062 KT Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41427806-koningin-wilhelminaplein-222/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "9.1 km", + "value": 9070 + }, + "duration": { + "value": 987, + "text": "16m27s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "14.1 km", + "value": 14135 + }, + "duration": { + "value": 1734, + "text": "28m54s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Tweede Hugo de Grootstraat 45, 1052 LE Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-40342170-tweede-hugo-de-grootstraat-45-c/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.8 km", + "value": 20802 + }, + "duration": { + "value": 2309, + "text": "38m29s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.8 km", + "value": 3825 + }, + "duration": { + "value": 826, + "text": "13m46s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Eerste Constantijn Huygensstraat 102, 1054 BZ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41687869-eerste-constantijn-huygensstraat-102-3/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "11.2 km", + "value": 11214 + }, + "duration": { + "value": 1758, + "text": "29m18s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.0 km", + "value": 3035 + }, + "duration": { + "value": 1210, + "text": "20m10s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Gustav Mahlerlaan 483, 1082 LS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41685852-gustav-mahlerlaan-483/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "9.3 km", + "value": 9292 + }, + "duration": { + "value": 776, + "text": "12m56s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.5 km", + "value": 6485 + }, + "duration": { + "value": 1016, + "text": "16m56s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Gustav Mahlerlaan 439, 1082 LS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41685850-gustav-mahlerlaan-439/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "9.3 km", + "value": 9255 + }, + "duration": { + "value": 748, + "text": "12m28s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "6.4 km", + "value": 6448 + }, + "duration": { + "value": 988, + "text": "16m28s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Kruitberghof 94, 1104 CA Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87033407-kruitberghof-94/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.2 km", + "value": 19210 + }, + "duration": { + "value": 2214, + "text": "36m54s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "10.9 km", + "value": 10911 + }, + "duration": { + "value": 1273, + "text": "21m13s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Kerkstraat 322, 1017 HC Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87900649-kerkstraat-322-c/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "13.3 km", + "value": 13310 + }, + "duration": { + "value": 1928, + "text": "32m8s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.4 km", + "value": 2441 + }, + "duration": { + "value": 884, + "text": "14m44s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Boerhaaveplein 12, 1091 AS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87928778-boerhaaveplein-12-1/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.7 km", + "value": 19690 + }, + "duration": { + "value": 2090, + "text": "34m50s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.7 km", + "value": 2710 + }, + "duration": { + "value": 652, + "text": "10m52s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Sumatrakade 577, 1019 PS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87026792-sumatrakade-577/?navigateSource=toppositie", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.5 km", + "value": 20475 + }, + "duration": { + "value": 2467, + "text": "41m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.2 km", + "value": 3187 + }, + "duration": { + "value": 727, + "text": "12m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Boylestraat 12I, 1098 PC Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87924456-boylestraat-12-i/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "21.1 km", + "value": 21067 + }, + "duration": { + "value": 2701, + "text": "45m1s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.4 km", + "value": 5436 + }, + "duration": { + "value": 1594, + "text": "26m34s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Kanaalstraat 88C, 1054 XL Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41557413-kanaalstraat-88-c/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "11.3 km", + "value": 11336 + }, + "duration": { + "value": 1664, + "text": "27m44s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.1 km", + "value": 4135 + }, + "duration": { + "value": 1201, + "text": "20m1s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Borneokade 285, 1019 XG Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huis-40216702-borneokade-285/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "22.9 km", + "value": 22862 + }, + "duration": { + "value": 2931, + "text": "48m51s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.6 km", + "value": 5573 + }, + "duration": { + "value": 1191, + "text": "19m51s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Spadinalaan, 1031 Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41426177-spadinalaan-240/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.1 km", + "value": 19133 + }, + "duration": { + "value": 2325, + "text": "38m45s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.4 km", + "value": 1372 + }, + "duration": { + "value": 1000, + "text": "16m40s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Pontsteiger 295, 1013 AH Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41532923-pontsteiger-295/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.6 km", + "value": 19557 + }, + "duration": { + "value": 2137, + "text": "35m37s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.8 km", + "value": 2758 + }, + "duration": { + "value": 870, + "text": "14m30s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Wielingenstraat 30, 1078 KL Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41660066-wielingenstraat-30-g/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "11.3 km", + "value": 11329 + }, + "duration": { + "value": 1469, + "text": "24m29s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.9 km", + "value": 4865 + }, + "duration": { + "value": 908, + "text": "15m8s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Karspeldreef 1443, 1104 SE Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87901941-karspeldreef-1443/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.1 km", + "value": 19138 + }, + "duration": { + "value": 2162, + "text": "36m2s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "10.8 km", + "value": 10839 + }, + "duration": { + "value": 1221, + "text": "20m21s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Joan Muyskenweg 4, 1096 CJ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41412597-joan-muyskenweg-4-h4/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "17.1 km", + "value": 17067 + }, + "duration": { + "value": 2267, + "text": "37m47s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.8 km", + "value": 5777 + }, + "duration": { + "value": 1332, + "text": "22m12s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Wibautstraat 70, 1091 GN Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41686330-wibautstraat-70-y/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "15.5 km", + "value": 15460 + }, + "duration": { + "value": 1524, + "text": "25m24s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.1 km", + "value": 3108 + }, + "duration": { + "value": 415, + "text": "6m55s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Balistraat 16D, 1094 JL Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-41675497-balistraat-16-d/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "21.0 km", + "value": 21009 + }, + "duration": { + "value": 2349, + "text": "39m9s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.2 km", + "value": 4210 + }, + "duration": { + "value": 860, + "text": "14m20s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Wamelplein 32, 1106 DP Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87035710-wamelplein-32/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.4 km", + "value": 19383 + }, + "duration": { + "value": 1694, + "text": "28m14s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "12.7 km", + "value": 12699 + }, + "duration": { + "value": 1585, + "text": "26m25s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Osdorperweg 664, 1067 SZ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huis-87858446-osdorperweg-664/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "13.7 km", + "value": 13735 + }, + "duration": { + "value": 2914, + "text": "48m34s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "12.5 km", + "value": 12469 + }, + "duration": { + "value": 3245, + "text": "54m5s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Utrechtsestraat 106, 1017 VS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87031649-utrechtsestraat-106-2/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "13.3 km", + "value": 13300 + }, + "duration": { + "value": 2112, + "text": "35m12s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.9 km", + "value": 2944 + }, + "duration": { + "value": 811, + "text": "13m31s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Vossiusstraat 17, 1054 ES Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87026796-vossiusstraat-17-1/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "16.2 km", + "value": 16171 + }, + "duration": { + "value": 2115, + "text": "35m15s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.3 km", + "value": 3285 + }, + "duration": { + "value": 1087, + "text": "18m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Sumatrakade 577, 1019 PS Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87026792-sumatrakade-577/?navigateSource=toppositie", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.5 km", + "value": 20475 + }, + "duration": { + "value": 2467, + "text": "41m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.2 km", + "value": 3187 + }, + "duration": { + "value": 727, + "text": "12m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Singel 449A, 1012 WP Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-86774627-singel-449-a/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "14.2 km", + "value": 14172 + }, + "duration": { + "value": 1914, + "text": "31m54s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.9 km", + "value": 1948 + }, + "duration": { + "value": 571, + "text": "9m31s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Gordijnensteeg 1, 1012 BT Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87925802-gordijnensteeg-1/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "21.6 km", + "value": 21578 + }, + "duration": { + "value": 2076, + "text": "34m36s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.0 km", + "value": 1046 + }, + "duration": { + "value": 285, + "text": "4m45s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Reguliersdwarsstraat 125, 1017 BL Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-87804538-reguliersdwarsstraat-125-2/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "21.3 km", + "value": 21342 + }, + "duration": { + "value": 2235, + "text": "37m15s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.2 km", + "value": 2168 + }, + "duration": { + "value": 651, + "text": "10m51s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Saxen Weimarlaan 32, 1075 BZ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/appartement-86783378-saxen-weimarlaan-32-2/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "13.7 km", + "value": 13707 + }, + "duration": { + "value": 1836, + "text": "30m36s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.5 km", + "value": 5516 + }, + "duration": { + "value": 1557, + "text": "25m57s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Joan Muyskenweg 4, 1096 CJ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-40896531-joan-muyskenweg-4a-t-m-4h/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "17.1 km", + "value": 17067 + }, + "duration": { + "value": 2267, + "text": "37m47s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.8 km", + "value": 5777 + }, + "duration": { + "value": 1332, + "text": "22m12s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Volkerakstraat & Krammerstraat, 1078 AV Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-40405375-wielingenstraat-volkerakstraat-krammerstraat-eendrachtstraat/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "11.4 km", + "value": 11405 + }, + "duration": { + "value": 1518, + "text": "25m18s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.9 km", + "value": 4941 + }, + "duration": { + "value": 957, + "text": "15m57s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Pontsteiger, 1013 AH Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-40133931-pontsteiger/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "19.4 km", + "value": 19399 + }, + "duration": { + "value": 2020, + "text": "33m40s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.6 km", + "value": 2600 + }, + "duration": { + "value": 753, + "text": "12m33s" + }, + "duration_in_traffic": null + } + }, + { + "address": "153 S Pearl St, Albany, NY 12202, USA", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-41409333-de-halve-maen/?navigateSource=resultlist", + "schiphol": { + "status": "ZERO_RESULTS", + "distance": { + "text": "", + "value": 0 + }, + "duration": { + "value": 0, + "text": "" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "ZERO_RESULTS", + "distance": { + "text": "", + "value": 0 + }, + "duration": { + "value": 0, + "text": "" + }, + "duration_in_traffic": null + } + }, + { + "address": "Stokerkade 2, 1019 XA Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-48914398-borneokade-255-313-stuurmankade-146-264-stokerkade-2-60-patio-woningen/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "22.7 km", + "value": 22749 + }, + "duration": { + "value": 2848, + "text": "47m28s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "5.5 km", + "value": 5460 + }, + "duration": { + "value": 1108, + "text": "18m28s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Tweede Hugo de Grootstraat, Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-49624585-tweede-hugo-de-grootstraat/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "21.0 km", + "value": 20980 + }, + "duration": { + "value": 2473, + "text": "41m13s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "4.0 km", + "value": 4003 + }, + "duration": { + "value": 990, + "text": "16m30s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Westerdoksdijk 243, 1013 AD Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-48925492-westerdoksdijk-243-t-m-271-d/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "18.2 km", + "value": 18168 + }, + "duration": { + "value": 1694, + "text": "28m14s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "1.4 km", + "value": 1369 + }, + "duration": { + "value": 427, + "text": "7m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Javakade 440, 1019 SC Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-48914339-javakade-440-618-imogirituin-6-8/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "20.6 km", + "value": 20578 + }, + "duration": { + "value": 2544, + "text": "42m24s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.2 km", + "value": 2211 + }, + "duration": { + "value": 786, + "text": "13m6s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Nieuwe Passeerdersstraat, 1016 XJ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-40176801-nieuwe-passeerdersstraat/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "12.4 km", + "value": 12361 + }, + "duration": { + "value": 1897, + "text": "31m37s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.9 km", + "value": 2922 + }, + "duration": { + "value": 967, + "text": "16m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Nieuwe Passeerdersstraat, 1016 XJ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-40176801-nieuwe-passeerdersstraat/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "12.4 km", + "value": 12361 + }, + "duration": { + "value": 1897, + "text": "31m37s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "2.9 km", + "value": 2922 + }, + "duration": { + "value": 967, + "text": "16m7s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Sumatrakade 13, 1019 BJ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-48925472-sumatrakade-13-1295/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "21.2 km", + "value": 21157 + }, + "duration": { + "value": 2599, + "text": "43m19s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.9 km", + "value": 3868 + }, + "duration": { + "value": 859, + "text": "14m19s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Sumatrakade 13, 1019 BJ Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-48925472-sumatrakade-13-1295/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "21.2 km", + "value": 21157 + }, + "duration": { + "value": 2599, + "text": "43m19s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "3.9 km", + "value": 3868 + }, + "duration": { + "value": 859, + "text": "14m19s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Westerdoksdijk 4, 1013 AA Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-40544531-westerdok-en-westerdoksdijk-4-6-106-t-m-270-en-35-t-m-49-89-t-m-101/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "17.9 km", + "value": 17924 + }, + "duration": { + "value": 1687, + "text": "28m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "0.9 km", + "value": 919 + }, + "duration": { + "value": 693, + "text": "11m33s" + }, + "duration_in_traffic": null + } + }, + { + "address": "Westerdoksdijk 4, 1013 AA Amsterdam, Netherlands", + "url": "https://www.funda.nl/en/huur/amsterdam/huurcomplex-40544531-westerdok-en-westerdoksdijk-4-6-106-t-m-270-en-35-t-m-49-89-t-m-101/?navigateSource=resultlist", + "schiphol": { + "status": "OK", + "distance": { + "text": "17.9 km", + "value": 17924 + }, + "duration": { + "value": 1687, + "text": "28m7s" + }, + "duration_in_traffic": null + }, + "centraal": { + "status": "OK", + "distance": { + "text": "0.9 km", + "value": 919 + }, + "duration": { + "value": 693, + "text": "11m33s" + }, + "duration_in_traffic": null + } + } +] diff --git a/fun/amsterdump/main.go b/fun/amsterdump/main.go new file mode 100644 index 000000000000..77f7392f4b7c --- /dev/null +++ b/fun/amsterdump/main.go @@ -0,0 +1,108 @@ +// Amsterdump is a small program that populates a BigQuery table with +// a matrix of origin points scattered around Amsterdam and each +// respective points travel time to a given destination. +// +// The two destinations used here are the Schiphol Airport and +// Amsterdam Central station. +// +// To accomplish this the Google Maps Distance Matrix API [1] is +// queried with the points. A visualisation is later done using +// BigQuery GeoViz[2]. +// +// [1]: https://developers.google.com/maps/documentation/distance-matrix/start#quotas +// [2]: https://bigquerygeoviz.appspot.com/ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + "log" + "os" + + "googlemaps.github.io/maps" +) + +func failOn(err error, msg string) { + if err != nil { + log.Fatalln(msg, err) + } +} + +type LocationResult struct { + Address string `json:"address"` + URL string `json:"url"` + Schiphol *maps.DistanceMatrixElement `json:"schiphol"` + Centraal *maps.DistanceMatrixElement `json:"centraal"` +} + +type Listing struct { + URL string `json:"url"` + Address string `json:"address"` +} + +func requestMatrix(ctx context.Context, client *maps.Client, listings []Listing) { + origins := make([]string, len(listings)) + for i, l := range listings { + origins[i] = l.Address + } + + request := &maps.DistanceMatrixRequest{ + Mode: maps.TravelModeTransit, + Units: maps.UnitsMetric, + Origins: origins, + + Destinations: []string{ + "Schiphol Airport", + "Amsterdam Centraal", + }, + } + + response, err := client.DistanceMatrix(ctx, request) + failOn(err, "could not retrieve distance matrix:") + + for idx, addr := range response.OriginAddresses { + result := LocationResult{ + Address: addr, + URL: listings[idx].URL, + Schiphol: response.Rows[idx].Elements[0], + Centraal: response.Rows[idx].Elements[1], + } + + j, _ := json.Marshal(result) + fmt.Println(string(j)) + } +} + +func main() { + var listings []Listing + input, err := ioutil.ReadFile("fun/amsterdump/input.json") + failOn(err, "could not read input file:") + + err = json.Unmarshal(input, &listings) + failOn(err, "could not deserialise listings:") + + ctx := context.Background() + apiKey := os.Getenv("MAPS_API_KEY") + if apiKey == "" { + log.Fatalln("API key must be supplied via MAPS_API_KEY") + } + + client, err := maps.NewClient(maps.WithAPIKey(apiKey)) + failOn(err, "could not create Google Maps API client:") + + var chunk []Listing + for _, l := range listings { + if len(chunk) == 25 { + requestMatrix(ctx, client, chunk) + chunk = []Listing{} + } else { + chunk = append(chunk, l) + } + } + + if len(chunk) > 1 { + requestMatrix(ctx, client, chunk) + } +} diff --git a/fun/amsterdump/scrape.el b/fun/amsterdump/scrape.el new file mode 100644 index 000000000000..f5537c2c8f17 --- /dev/null +++ b/fun/amsterdump/scrape.el @@ -0,0 +1,25 @@ +;; Scraping funda.nl (this file is just notes and snippets, not full code) +;; +;; Begin by copying whole page into buffer (out of inspect element +;; because encoding is difficult) + +(beginning-of-buffer) + +;; zap everything that isn't a relevant result +(keep-lines "data-object-url-tracking\\|img alt") + +;; mark all spans, move them to the end of the buffer +(cl-letf (((symbol-function 'read-regexp) + (lambda (&rest _) "</span>"))) + (mc/mark-all-in-region-regexp (point-min) (point-max))) + +;; mark all images lines (these contain street addresses for things +;; with images), clear up and join with previous +;; +;; mark all: data-image-error-fallback + +;; delete all lines that don't either contain a span or an img tag +;; (there are duplicates) +(keep-lines "span class\\|img alt") + +;; do some manual cleanup from the hrefs and done diff --git a/fun/aoc2019/default.nix b/fun/aoc2019/default.nix new file mode 100644 index 000000000000..5f1f248c504a --- /dev/null +++ b/fun/aoc2019/default.nix @@ -0,0 +1,22 @@ +# Solutions for Advent of Code 2019, written in Emacs Lisp. +# +# For each day a new file is created as "solution-day$n.el". +{ depot, ... }: + +let + inherit (builtins) attrNames filter head listToAttrs match readDir; + dir = readDir ./.; + matchSolution = match "solution-(.*)\.el"; + isSolution = f: (matchSolution f) != null; + getDay = f: head (matchSolution f); + + solutionFiles = filter (e: dir."${e}" == "regular" && isSolution e) (attrNames dir); + solutions = map (f: let day = getDay f; in { + name = day; + value = depot.writeElispBin { # TODO(tazjin): move writeElispBin to depot.nix + name = "aoc2019"; + deps = p: with p; [ dash s ht ]; + src = ./. + ("/" + f); + }; + }) solutionFiles; +in listToAttrs solutions diff --git a/fun/aoc2019/solution-day1.el b/fun/aoc2019/solution-day1.el new file mode 100644 index 000000000000..d805c22ec870 --- /dev/null +++ b/fun/aoc2019/solution-day1.el @@ -0,0 +1,28 @@ +;; Advent of Code 2019 - Day 1 +(require 'dash) + +;; Puzzle 1: + +(defvar day-1/input + '(83285 96868 121640 51455 128067 128390 141809 52325 68310 140707 124520 149678 + 87961 52040 133133 52203 117483 85643 84414 86558 65402 122692 88565 61895 + 126271 128802 140363 109764 53600 114391 98973 124467 99574 69140 144856 + 56809 149944 138738 128823 82776 77557 51994 74322 64716 114506 124074 + 73096 97066 96731 149307 135626 121413 69575 98581 50570 60754 94843 72165 + 146504 53290 63491 50936 79644 119081 70218 85849 133228 114550 131943 + 67288 68499 80512 148872 99264 119723 68295 90348 146534 52661 99146 95993 + 130363 78956 126736 82065 77227 129950 97946 132345 107137 79623 148477 + 88928 118911 75277 97162 80664 149742 88983 74518)) + +(defun calculate-fuel (mass) + (- (/ mass 3) 2)) + +(message "Solution to day1/1: %d" (apply #'+ (-map #'calculate-fuel day-1/input))) + +;; Puzzle 2: +(defun calculate-recursive-fuel (mass) + (let ((fuel (calculate-fuel mass))) + (if (< fuel 0) 0 + (+ fuel (calculate-recursive-fuel fuel))))) + +(message "Solution to day1/2: %d" (apply #'+ (-map #'calculate-recursive-fuel day-1/input))) diff --git a/fun/aoc2019/solution-day2.el b/fun/aoc2019/solution-day2.el new file mode 100644 index 000000000000..6ecac1e2016c --- /dev/null +++ b/fun/aoc2019/solution-day2.el @@ -0,0 +1,53 @@ +;; -*- lexical-binding: t; -*- +;; Advent of Code 2019 - Day 2 +(require 'dash) +(require 'ht) + +(defvar day2/input + [1 0 0 3 1 1 2 3 1 3 4 3 1 5 0 3 2 1 9 19 1 19 5 23 1 13 23 27 1 27 6 31 + 2 31 6 35 2 6 35 39 1 39 5 43 1 13 43 47 1 6 47 51 2 13 51 55 1 10 55 + 59 1 59 5 63 1 10 63 67 1 67 5 71 1 71 10 75 1 9 75 79 2 13 79 83 1 9 + 83 87 2 87 13 91 1 10 91 95 1 95 9 99 1 13 99 103 2 103 13 107 1 107 10 + 111 2 10 111 115 1 115 9 119 2 119 6 123 1 5 123 127 1 5 127 131 1 10 + 131 135 1 135 6 139 1 10 139 143 1 143 6 147 2 147 13 151 1 5 151 155 1 + 155 5 159 1 159 2 163 1 163 9 0 99 2 14 0 0]) + +;; Puzzle 1 + +(defun day2/single-op (f state idx) + (let* ((a (aref state (aref state (+ 1 idx)))) + (b (aref state (aref state (+ 2 idx)))) + (p (aref state (+ 3 idx))) + (result (funcall f a b))) + (aset state p (funcall f a b)))) + +(defun day2/operate (state idx) + (pcase (aref state idx) + (99 (aref state 0)) + (1 (day2/single-op #'+ state idx) + (day2/operate state (+ 4 idx))) + (2 (day2/single-op #'* state idx) + (day2/operate state (+ 4 idx))) + (other (error "Unknown opcode: %s" other)))) + +(defun day2/program-with-inputs (noun verb) + (let* ((input (copy-tree day2/input t))) + (aset input 1 noun) + (aset input 2 verb) + (day2/operate input 0))) + +(message "Solution to day2/1: %s" (day2/program-with-inputs 12 2)) + +;; Puzzle 2 +(let* ((used (ht)) + (noun 0) + (verb 0) + (result (day2/program-with-inputs noun verb))) + (while (/= 19690720 result) + (setq noun (random 100)) + (setq verb (random 100)) + (unless (ht-get used (format "%d%d" noun verb)) + (ht-set used (format "%d%d" noun verb) t) + (setq result (day2/program-with-inputs noun verb)))) + + (message "Solution to day2/2: %s%s" noun verb)) diff --git a/fun/aoc2019/solution-day3.el b/fun/aoc2019/solution-day3.el new file mode 100644 index 000000000000..b7dfdd245fb1 --- /dev/null +++ b/fun/aoc2019/solution-day3.el @@ -0,0 +1,64 @@ +;; -*- lexical-binding: t; -*- +;; Advent of Code 2019 - Day 3 + +(require 'cl-lib) +(require 'dash) +(require 'ht) +(require 's) + +(defvar day3/input/wire1 + "R1010,D422,L354,U494,L686,U894,R212,U777,L216,U9,L374,U77,R947,U385,L170,U916,R492,D553,L992,D890,L531,U360,R128,U653,L362,U522,R817,U198,L126,D629,L569,U300,L241,U145,R889,D196,L450,D576,L319,D147,R985,U889,L941,U837,L608,D77,L864,U911,L270,D869,R771,U132,L249,U603,L36,D328,L597,U992,L733,D370,L947,D595,L308,U536,L145,U318,R55,D773,R175,D505,R483,D13,R780,U778,R445,D107,R490,U245,L587,U502,R446,U639,R150,U35,L455,D522,R866,U858,R394,D975,R513,D378,R58,D646,L374,D675,R209,U228,R530,U543,L480,U677,L912,D164,L573,U587,L784,D626,L994,U250,L215,U985,R684,D79,L877,U811,L766,U617,L665,D246,L408,U800,L360,D272,L436,U138,R240,U735,L681,U68,L608,D59,R532,D808,L104,U968,R887,U819,R346,U698,L317,U582,R516,U55,L303,U607,L457,U479,L510,D366,L583,U519,R878,D195,R970,D267,R842,U784,R9,D946,R833,D238,L232,D94,L860,D47,L346,U951,R491,D745,R849,U273,R263,U392,L341,D808,R696,U326,R886,D296,L865,U833,R241,U644,R729,D216,R661,D712,L466,D699,L738,U5,L556,D693,R912,D13,R48,U63,L877,U628,L689,D929,R74,U924,R612,U153,R417,U425,L879,D378,R79,D248,L3,U519,R366,U281,R439,D823,R149,D668,R326,D342,L213,D735,R504,U265,L718,D842,L565,U105,L214,U963,R518,D681,R642,U170,L111,U6,R697,U572,R18,U331,L618,D255,R534,D322,L399,U595,L246,U651,L836,U757,R417,D795,R291,U759,L568,U965,R828,D570,R350,U317,R338,D173,L74,D833,L650,D844,L70,U913,R594,U407,R674,D684,L481,D564,L128,D277,R851,D274,L435,D582,R469,U729,R387,D818,R443,U504,R414,U8,L842,U845,R275,U986,R53,U660,R661,D225,R614,U159,R477") + +(defvar day3/input/wire2 + "L1010,D698,R442,U660,L719,U702,L456,D86,R938,D177,L835,D639,R166,D285,L694,U468,L569,D104,L234,D574,L669,U299,L124,D275,L179,D519,R617,U72,L985,D248,R257,D276,L759,D834,R490,U864,L406,U181,R911,U873,R261,D864,R260,U759,R648,U158,R308,D386,L835,D27,L745,U91,R840,U707,R275,U543,L663,U736,L617,D699,R924,U103,R225,U455,R708,U319,R569,U38,R315,D432,L179,D975,R519,D546,L295,U680,L685,U603,R262,D250,R7,U171,R261,U519,L832,U534,L471,U431,L474,U886,R10,D179,L79,D555,R452,U452,L832,U863,L367,U538,L237,D160,R441,U605,R942,U259,L811,D552,R646,D353,L225,D94,L35,D307,R752,U23,R698,U610,L379,D932,R698,D751,R178,D347,R325,D156,R471,D555,R558,D593,R773,U2,L955,U764,L735,U438,R364,D640,L757,U534,R919,U409,R361,U407,R336,D808,R877,D648,R610,U198,R340,U94,R795,D667,R811,U975,L965,D224,R565,D681,L64,U567,R621,U922,L665,U329,R242,U592,L727,D481,L339,U402,R213,D280,R656,U169,R976,D962,L294,D505,L251,D689,L497,U133,R230,D441,L90,D220,L896,D657,L500,U331,R502,U723,R762,D613,L447,D256,L226,U309,L935,U384,L740,D459,R309,D707,R952,D747,L304,D105,R977,D539,R941,D21,R291,U216,R132,D543,R515,U453,L854,D42,R982,U102,L469,D639,R559,D68,R302,U734,R980,D214,R107,D191,L730,D793,L63,U17,R807,U196,R412,D592,R330,D941,L87,D291,L44,D94,L272,D780,R968,U837,L712,D704,R163,U981,R537,U778,R220,D303,L196,D951,R163,D446,R11,D623,L72,D778,L158,U660,L189,D510,L247,D716,L89,U887,L115,U114,L36,U81,R927,U293,L265,U183,R331,D267,R745,D298,L561,D918,R299,U810,L322,U679,L739,D854,L581,U34,L862,D779,R23") + +;; Puzzle 1 + +(defun wire-from (raw) + (-map (lambda (s) + (cons (substring s 0 1) (string-to-number (substring s 1)))) + (s-split "," raw))) + +(defun day3/move (x y next) + (cl-flet ((steps (by op) + (-map op (reverse (number-sequence 1 by))))) + (pcase next + (`("L" . ,by) (steps by (lambda (n) (cons (- x n) y)))) + (`("R" . ,by) (steps by (lambda (n) (cons (+ x n) y)))) + (`("U" . ,by) (steps by (lambda (n) (cons x (+ y n))))) + (`("D" . ,by) (steps by (lambda (n) (cons x (- y n)))))))) + +(defun day3/wire-points (wire) + (let ((points (ht)) + (point-list (-reduce-from + (lambda (acc point) + (-let* (((x . y) (car acc)) + (next (day3/move x y point))) + (-concat next acc))) + '((0 . 0)) wire))) + (-map (-lambda ((s . p)) (ht-set! points p s)) + (-zip (reverse (number-sequence 0 (- (length point-list) 1))) point-list)) + (ht-remove! points '(0 . 0)) + points)) + +(defun day3/closest-intersection (crossed-points) + (car (-sort #'< + (-map (-lambda ((x . y)) + (+ (abs x) (abs y))) + crossed-points)))) + +(defun day3/minimum-steps (wire1 wire2 crossed) + (car (-sort #'< + (-map (-lambda (p) + (+ (ht-get wire1 p) (ht-get wire2 p))) + crossed)))) + +;; Example: +(let* ((wire1-points (day3/wire-points (wire-from day3/input/wire1))) + (wire2-points (day3/wire-points (wire-from day3/input/wire2))) + (crossed-points (-filter (lambda (p) (ht-contains? wire1-points p)) + (ht-keys wire2-points)))) + (message "Solution for day3/1: %d" (day3/closest-intersection crossed-points)) + (message "Solution for day3/2: %d" (day3/minimum-steps wire1-points + wire2-points + crossed-points))) diff --git a/fun/aoc2019/solution-day4.el b/fun/aoc2019/solution-day4.el new file mode 100644 index 000000000000..2805f3f4e9cd --- /dev/null +++ b/fun/aoc2019/solution-day4.el @@ -0,0 +1,73 @@ +;; -*- lexical-binding: t; -*- +;; Advent of Code 2019 - Day 4 + +(require 'cl-lib) +(require 'dash) + +;; Puzzle 1 + +(defun day4/to-digits (num) + "Convert NUM to a list of its digits." + (cl-labels ((steps (n digits) + (if (= n 0) digits + (steps (/ n 10) (cons (% n 10) digits))))) + (steps num '()))) + +(defvar day4/input (-map #'day4/to-digits (number-sequence 128392 643281))) + +(defun day4/filter-password (digits) + "Determines whether the given rules match the supplied + number." + + (and + ;; It is a six digit number + (= 6 (length digits)) + + ;; Value is within the range given in puzzle input + ;; (noop because the range is generated from the input) + + ;; Two adjacent digits are the same (like 22 in 122345). + (car (-reduce-from (-lambda ((acc . prev) next) + (cons (or acc (= prev next)) next)) + '(nil . 0) digits)) + + ;; Going from left to right, the digits never decrease; they only + ;; ever increase or stay the same (like 111123 or 135679). + (car (-reduce-from (-lambda ((acc . prev) next) + (cons (and acc (>= next prev)) next)) + '(t . 0) digits)))) + +;; Puzzle 2 +;; +;; Additional criteria: If there's matching digits, they're not in a group. + +(cl-defstruct day4/acc state prev count) + +(defun day4/filter-longer-groups (digits) + (let ((res (-reduce-from + (lambda (acc next) + (cond ;; sequence is broken and count was at 1 -> + ;; match! + ((and (= (day4/acc-count acc) 2) + (/= (day4/acc-prev acc) next)) + (setf (day4/acc-state acc) t)) + + ;; sequence continues, counter increment! + ((= (day4/acc-prev acc) next) + (setf (day4/acc-count acc) (+ 1 (day4/acc-count acc)))) + + ;; sequence broken, reset counter + ((/= (day4/acc-prev acc) next) + (setf (day4/acc-count acc) 1))) + + (setf (day4/acc-prev acc) next) + acc) + (make-day4/acc :prev 0 :count 0) digits))) + (or (day4/acc-state res) + (= 2 (day4/acc-count res))))) + +(let* ((simple (-filter #'day4/filter-password day4/input)) + (complex (-filter #'day4/filter-longer-groups simple))) + (message "Solution to day4/1: %d" (length simple)) + (message "Solution to day4/2: %d" (length complex))) + diff --git a/fun/clbot/backoffutil/backoffutil.go b/fun/clbot/backoffutil/backoffutil.go new file mode 100644 index 000000000000..1b1ea5f9d012 --- /dev/null +++ b/fun/clbot/backoffutil/backoffutil.go @@ -0,0 +1,43 @@ +// Package backoffutil provides useful utilities for backoff. +package backoffutil + +import ( + "time" + + backoff "github.com/cenkalti/backoff/v4" +) + +// ZeroStartingBackOff is a backoff.BackOff that returns "0" as the first Duration after a reset. +// This is useful for constructing loops and just enforcing a backoff duration on every loop, rather than incorporating this logic into the loop directly. +type ZeroStartingBackOff struct { + bo backoff.BackOff + initial bool +} + +// NewZeroStartingBackOff creates a new ZeroStartingBackOff. +func NewZeroStartingBackOff(bo backoff.BackOff) *ZeroStartingBackOff { + return &ZeroStartingBackOff{bo: bo, initial: true} +} + +// NewDefaultBackOff creates a sensibly configured BackOff that starts at zero. +func NewDefaultBackOff() backoff.BackOff { + ebo := backoff.NewExponentialBackOff() + ebo.MaxElapsedTime = 0 + return NewZeroStartingBackOff(ebo) +} + +// NextBackOff returns the next back off duration to use. +// For the first call after a call to Reset(), this is 0. For each subsequent duration, the underlying BackOff is consulted. +func (bo *ZeroStartingBackOff) NextBackOff() time.Duration { + if bo.initial == true { + bo.initial = false + return 0 + } + return bo.bo.NextBackOff() +} + +// Reset resets to the initial state, and also passes a Reset through to the underlying BackOff. +func (bo *ZeroStartingBackOff) Reset() { + bo.initial = true + bo.bo.Reset() +} diff --git a/fun/clbot/backoffutil/default.nix b/fun/clbot/backoffutil/default.nix new file mode 100644 index 000000000000..78585da236e3 --- /dev/null +++ b/fun/clbot/backoffutil/default.nix @@ -0,0 +1,14 @@ +{ depot, ... }: + +let + inherit (depot.third_party) gopkgs; +in +depot.nix.buildGo.package { + name = "code.tvl.fyi/fun/clbot/backoffutil"; + srcs = [ + ./backoffutil.go + ]; + deps = [ + gopkgs."github.com".cenkalti.backoff.gopkg + ]; +} diff --git a/fun/clbot/clbot.go b/fun/clbot/clbot.go new file mode 100644 index 000000000000..7fa12f2c3bc3 --- /dev/null +++ b/fun/clbot/clbot.go @@ -0,0 +1,101 @@ +package main + +import ( + "context" + "flag" + "io/ioutil" + "os" + "os/signal" + "time" + + "code.tvl.fyi/fun/clbot/gerrit" + "github.com/davecgh/go-spew/spew" + log "github.com/golang/glog" + "golang.org/x/crypto/ssh" +) + +var ( + gerritAddr = flag.String("gerrit_host", "cl.tvl.fyi:29418", "Gerrit SSH host:port") + gerritSSHHostKey = flag.String("gerrit_ssh_pubkey", "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIUNYBYPCCBNDFSd0BuCR+8kgeuJ7IA5S2nTNQmkQUYNyXK+ot5os7rHtCk96+grd5+J8jFCuFBWisUe8h8NC0Q=", "Gerrit SSH public key") + gerritSSHTimeout = flag.Duration("gerrit_tcp_timeout", 5*time.Second, "Gerrit SSH TCP connect timeout") + + required = flag.NewFlagSet("required flags", flag.ExitOnError) + gerritAuthUsername = required.String("gerrit_ssh_auth_username", "", "Gerrit SSH username") + gerritAuthKeyPath = required.String("gerrit_ssh_auth_key", "", "Gerrit SSH private key path") +) + +func mustFixedHostKey(f string) ssh.HostKeyCallback { + pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(f)) + if err != nil { + log.Exitf("ParseAuthorizedKey(%q): %v", f, err) + } + return ssh.FixedHostKey(pk) +} + +func mustPrivateKey(p string) ssh.AuthMethod { + pkBytes, err := ioutil.ReadFile(p) + if err != nil { + log.Exitf("reading SSH private key from %q: %v", p, err) + } + pk, err := ssh.ParsePrivateKey(pkBytes) + if err != nil { + log.Exitf("parsing private key from %q: %v", p, err) + } + return ssh.PublicKeys(pk) +} + +func checkRequired(fs *flag.FlagSet) { + missing := map[string]bool{} + fs.VisitAll(func(f *flag.Flag) { missing[f.Name] = true }) + fs.Visit(func(f *flag.Flag) { delete(missing, f.Name) }) + for f := range missing { + log.Errorf("flag %q was unset but is required", f) + } + if len(missing) > 0 { + os.Exit(1) + } +} + +var shutdownFuncs []func() + +func callOnShutdown(f func()) { + shutdownFuncs = append(shutdownFuncs, f) +} + +func main() { + flag.Parse() + checkRequired(required) + + shutdownCh := make(chan os.Signal) + signal.Notify(shutdownCh, os.Interrupt) + go func() { + <-shutdownCh + for n := len(shutdownFuncs); n >= 0; n-- { + shutdownFuncs[n]() + } + }() + + ctx, cancel := context.WithCancel(context.Background()) + callOnShutdown(cancel) + cfg := &ssh.ClientConfig{ + User: *gerritAuthUsername, + Auth: []ssh.AuthMethod{mustPrivateKey(*gerritAuthKeyPath)}, + HostKeyCallback: mustFixedHostKey(*gerritSSHHostKey), + Timeout: *gerritSSHTimeout, + } + cfg.SetDefaults() + + gw, err := gerrit.New(ctx, "tcp", *gerritAddr, cfg) + if err != nil { + log.Errorf("gerrit.New(%q): %v", *gerritAddr, err) + } + callOnShutdown(func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + gw.Close(ctx) + }) + + for e := range gw.Events() { + log.Infof("hello: %v", spew.Sdump(e)) + } +} diff --git a/fun/clbot/default.nix b/fun/clbot/default.nix new file mode 100644 index 000000000000..7a255f027a44 --- /dev/null +++ b/fun/clbot/default.nix @@ -0,0 +1,18 @@ +{ depot, ... }@args: + +let + clbot = depot.fun.clbot; + gopkgs = depot.third_party.gopkgs; +in +depot.nix.buildGo.program { + name = "clbot"; + srcs = [ + ./clbot.go + ]; + deps = [ + clbot.gerrit + gopkgs."github.com".davecgh.go-spew.spew.gopkg + gopkgs."github.com".golang.glog.gopkg + gopkgs."golang.org".x.crypto.ssh.gopkg + ]; +} diff --git a/fun/clbot/gerrit/default.nix b/fun/clbot/gerrit/default.nix new file mode 100644 index 000000000000..3b6ce0a7392f --- /dev/null +++ b/fun/clbot/gerrit/default.nix @@ -0,0 +1,18 @@ +{ depot, ... }: + +let + inherit (depot.fun) clbot; + inherit (depot.third_party) gopkgs; +in +depot.nix.buildGo.package { + name = "code.tvl.fyi/fun/clbot/gerrit"; + srcs = [ + ./watcher.go + ]; + deps = [ + clbot.gerrit.gerritevents + clbot.backoffutil + gopkgs."github.com".golang.glog.gopkg + gopkgs."golang.org".x.crypto.ssh.gopkg + ]; +} diff --git a/fun/clbot/gerrit/gerritevents/default.nix b/fun/clbot/gerrit/gerritevents/default.nix new file mode 100644 index 000000000000..024451858bbc --- /dev/null +++ b/fun/clbot/gerrit/gerritevents/default.nix @@ -0,0 +1,10 @@ +{ depot, ... }: + +depot.nix.buildGo.package { + name = "code.tvl.fyi/fun/clbot/gerrit/gerritevents"; + srcs = [ + ./time.go + ./types.go + ./events.go + ]; +} diff --git a/fun/clbot/gerrit/gerritevents/events.go b/fun/clbot/gerrit/gerritevents/events.go new file mode 100644 index 000000000000..c02b30f76ea8 --- /dev/null +++ b/fun/clbot/gerrit/gerritevents/events.go @@ -0,0 +1,321 @@ +package gerritevents + +import ( + "encoding/json" + "fmt" +) + +var events = map[string]func() Event{} + +func registerEvent(e func() Event) { + t := e().EventType() + if _, ok := events[t]; ok { + panic(fmt.Sprintf("%s already registered", t)) + } + events[t] = e +} + +// These events are taken from https://cl.tvl.fyi/Documentation/cmd-stream-events.html. + +// Event is implemented by Gerrit event structs. +type Event interface { + EventType() string +} + +type simpleEvent struct { + Type string `json:"type"` +} + +// Parse parses a Gerrit event from JSON. +func Parse(bs []byte) (Event, error) { + var s simpleEvent + if err := json.Unmarshal(bs, &s); err != nil { + return nil, fmt.Errorf("unmarshalling %q as Gerrit Event: %v", string(bs), err) + } + ef, ok := events[s.Type] + if !ok { + return nil, fmt.Errorf("unknown event type %q", s.Type) + } + e := ef() + if err := json.Unmarshal(bs, e); err != nil { + return nil, fmt.Errorf("unmarshalling %q as Gerrit Event %q: %v", string(bs), e.EventType(), err) + } + return e, nil +} + +// AssigneeChanged indicates that a change's assignee has been changed. +type AssigneeChanged struct { + Type string `json:"type"` + Change Change `json:"change"` + Changer Account `json:"changer"` + OldAssignee Account `json:"oldAssignee"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (AssigneeChanged) EventType() string { return "assignee-changed" } + +func init() { + registerEvent(func() Event { return &AssigneeChanged{} }) +} + +// ChangeAbandoned indicates that a change has been abandoned. +type ChangeAbandoned struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Abandoner Account `json:"abandoner"` + Reason string `json:"reason"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (ChangeAbandoned) EventType() string { return "change-abandoned" } + +func init() { + registerEvent(func() Event { return &ChangeAbandoned{} }) +} + +// ChangeDeleted indicates that a change has been deleted. +type ChangeDeleted struct { + Type string `json:"type"` + Change Change `json:"change"` + Deleter Account `json:"deleter"` +} + +// EventType implements Event. +func (ChangeDeleted) EventType() string { return "change-deleted" } + +func init() { + registerEvent(func() Event { return &ChangeDeleted{} }) +} + +// ChangeMerged indicates that a change has been merged into the target branch. +type ChangeMerged struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Submitter Account `json:"submitter"` + NewRev string `json:"newRev"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (ChangeMerged) EventType() string { return "change-merged" } + +func init() { + registerEvent(func() Event { return &ChangeMerged{} }) +} + +// ChangeRestored indicates a change has been restored (i.e. un-abandoned). +type ChangeRestored struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Restorer Account `json:"restorer"` + Reason string `json:"reason"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (ChangeRestored) EventType() string { return "change-restored" } + +func init() { + registerEvent(func() Event { return &ChangeRestored{} }) +} + +// CommentAdded indicates someone has commented on a patchset. +type CommentAdded struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Author Account `json:"author"` + Approvals []Approval `json:"approvals"` + Comment string `json:"comment"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (CommentAdded) EventType() string { return "comment-added" } + +func init() { + registerEvent(func() Event { return &CommentAdded{} }) +} + +// DroppedOutput indicates that some events may be missing from the stream. +type DroppedOutput struct { + Type string `json:"type"` +} + +// EventType implements Event. +func (DroppedOutput) EventType() string { return "dropped-output" } + +func init() { + registerEvent(func() Event { return &DroppedOutput{} }) +} + +// HashtagsChanged indicates that someone has added or removed hashtags from a change. +type HashtagsChanged struct { + Type string `json:"type"` + Change Change `json:"change"` + Editor Account `json:"editor"` + Added []string `json:"added"` + Removed []string `json:"removed"` + Hashtags []string `json:"hashtags"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (HashtagsChanged) EventType() string { return "hashtags-changed" } + +func init() { + registerEvent(func() Event { return &HashtagsChanged{} }) +} + +// ProjectCreated indicates that a new project has been created. +type ProjectCreated struct { + Type string `json:"type"` + ProjectName string `json:"projectName"` + ProjectHead string `json:"projectHead"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (ProjectCreated) EventType() string { return "project-created" } + +func init() { + registerEvent(func() Event { return &ProjectCreated{} }) +} + +// PatchSetCreated indicates that a new patchset has been added to a change. +type PatchSetCreated struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Uploader Account `json:"uploader"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (PatchSetCreated) EventType() string { return "patchset-created" } + +func init() { + registerEvent(func() Event { return &PatchSetCreated{} }) +} + +// RefUpdated indicates that a ref has been updated. +type RefUpdated struct { + Type string `json:"type"` + Submitter Account `json:"submitter"` + RefUpdate RefUpdate `json:"refUpdate"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (RefUpdated) EventType() string { return "ref-updated" } + +func init() { + registerEvent(func() Event { return &RefUpdated{} }) +} + +// ReviewerAdded indicates that a reviewer has been added to a change. +type ReviewerAdded struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Reviewer Account `json:"reviewer"` + Adder Account `json:"adder"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (ReviewerAdded) EventType() string { return "reviewer-added" } + +func init() { + registerEvent(func() Event { return &ReviewerAdded{} }) +} + +// ReviewerDeleted indicates that a reviewer has been removed from a change, possibly removing one or more approvals. +type ReviewerDeleted struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Reviewer Account `json:"reviewer"` + Remover Account `json:"remover"` + Approvals []Approval `json:"approvals"` + Comment string `json:"comment"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (ReviewerDeleted) EventType() string { return "reviewer-deleted" } + +func init() { + registerEvent(func() Event { return &ReviewerDeleted{} }) +} + +// TopicChanged indicates that the topic attached to a change has been changed. +type TopicChanged struct { + Type string `json:"type"` + Change Change `json:"change"` + Changer Account `json:"changer"` + OldTopic string `json:"oldTopic"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (TopicChanged) EventType() string { return "topic-changed" } + +func init() { + registerEvent(func() Event { return &TopicChanged{} }) +} + +// WIPStateChanged indicates that the work-in-progress state of a change has changed. +type WIPStateChanged struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Changer Account `json:"changer"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (WIPStateChanged) EventType() string { return "wip-state-changed" } + +func init() { + registerEvent(func() Event { return &WIPStateChanged{} }) +} + +// PrivateStateChanged indicates that the private state of a change has changed. +type PrivateStateChanged struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Changer Account `json:"changer"` + EventCreatedOn Time `json:"eventCreatedOn"` +} + +// EventType implements Event. +func (PrivateStateChanged) EventType() string { return "private-state-changed" } + +func init() { + registerEvent(func() Event { return &PrivateStateChanged{} }) +} + +// VoteDeleted indicates that an approval vote has been deleted from a change. +type VoteDeleted struct { + Type string `json:"type"` + Change Change `json:"change"` + PatchSet PatchSet `json:"patchSet"` + Reviewer Account `json:"reviewer"` + Remover Account `json:"remover"` + Approvals []Approval `json:"approvals"` + Comment string `json:"comment"` +} + +// EventType implements Event. +func (VoteDeleted) EventType() string { return "vote-deleted" } + +func init() { + registerEvent(func() Event { return &VoteDeleted{} }) +} diff --git a/fun/clbot/gerrit/gerritevents/time.go b/fun/clbot/gerrit/gerritevents/time.go new file mode 100644 index 000000000000..7fbfaa3f5c47 --- /dev/null +++ b/fun/clbot/gerrit/gerritevents/time.go @@ -0,0 +1,38 @@ +package gerritevents + +import ( + "fmt" + "strconv" + "time" +) + +// Time is a time.Time that is formatted as a Unix timestamp in JSON. +type Time struct { + time.Time +} + +// UnmarshalJSON unmarshals a Unix timestamp into a Time. +func (t *Time) UnmarshalJSON(bs []byte) error { + if string(bs) == "null" { + return nil + } + u, err := strconv.ParseInt(string(bs), 10, 64) + if err != nil { + return err + } + t.Time = time.Unix(u, 0) + return nil +} + +// MarshalJSON marshals a Time into a Unix timestamp. +func (t *Time) MarshalJSON() ([]byte, error) { + if t.IsZero() { + return []byte("null"), nil + } + return []byte(fmt.Sprintf("%d", t.Unix())), nil +} + +// IsSet returns true if the time.Time is non-zero. +func (t *Time) IsSet() bool { + return !t.IsZero() +} diff --git a/fun/clbot/gerrit/gerritevents/types.go b/fun/clbot/gerrit/gerritevents/types.go new file mode 100644 index 000000000000..75987a2da601 --- /dev/null +++ b/fun/clbot/gerrit/gerritevents/types.go @@ -0,0 +1,221 @@ +package gerritevents + +// These types are taken from https://cl.tvl.fyi/Documentation/json.html. + +// Account is a Gerrit account (or just a Git name+email pair). +type Account struct { + Name string `json:"name"` + Email string `json:"email"` + Username string `json:"username"` +} + +// ChangeStatus represents the states a change can be in. +type ChangeStatus string + +const ( + // ChangeStatusNew is the state a change is in during review. + ChangeStatusNew ChangeStatus = "NEW" + + // ChangeStatusMerged indicates a change was merged to the target branch. + ChangeStatusMerged ChangeStatus = "MERGED" + + // ChangeStatusAbandoned indicates a change was marked as abandoned. + ChangeStatusAbandoned ChangeStatus = "ABANDONED" +) + +// Message is a message left by a reviewer. +type Message struct { + Timestamp Time `json:"timestamp"` + Reviewer Account `json:"reviewer"` + Message string `json:"message"` +} + +// TrackingID allows storing identifiers from external systems, i.e. bug trackers. +type TrackingID struct { + System string `json:"system"` + ID string `json:"id"` +} + +// ChangeKind indicates the different changes that can be made to a change. +type ChangeKind string + +const ( + // ChangeKindRework indicates a non-trivial content change. + ChangeKindRework ChangeKind = "REWORK" + + // ChangeKindTrivialRebase indicates a conflict-free merge between the new parent and the prior patch set. + ChangeKindTrivialRebase ChangeKind = "TRIVIAL_REBASE" + + // ChangeKindMergeFirstParentUpdate indicates a conflict-free change of the first parent of a merge commit. + ChangeKindMergeFirstParentUpdate ChangeKind = "MERGE_FIRST_PARENT_UPDATE" + + // ChangeKindNoCodeChange indicates no code change (the tree and parent trees are unchanged) - commit message probably changed. + ChangeKindNoCodeChange ChangeKind = "NO_CODE_CHANGE" + + // ChangeKindNoChange indicates nothing changes: the commit message, tree, and parent tree are unchanged. + ChangeKindNoChange ChangeKind = "NO_CHANGE" +) + +// Approval represents the current and past state of an approval label. +type Approval struct { + Type string `json:"type"` + Description string `json:"description"` + Value string `json:"value"` + OldValue *string `json:"oldValue"` + GrantedOn *Time `json:"grantedOn"` + By *Account `json:"by"` +} + +// PatchSetComment is a single comment left on a patchset. +type PatchSetComment struct { + File string `json:"file"` + Line int `json:"line"` + Reviewer Account `json:"reviewer"` + Message string `json:"message"` +} + +// FilePatchType represents the different modifications that can be made to a file by a patchset. +type FilePatchType string + +const ( + // FilePatchTypeAdded indicates the file did not exist, and this patchset adds it to the tree. + FilePatchTypeAdded FilePatchType = "ADDED" + + // FilePatchTypeModified indicates the file exists before and after this patchset. + FilePatchTypeModified FilePatchType = "MODIFIED" + + // FilePatchTypeDeleted indicates the file is removed by this patchset. + FilePatchTypeDeleted FilePatchType = "DELETED" + + // FilePatchTypeRenamed indicates the file has a different name before this patchset than after. + FilePatchTypeRenamed FilePatchType = "RENAMED" + + // FilePatchTypeCopied indicates the file was copied from a different file. + FilePatchTypeCopied FilePatchType = "COPIED" + + // FilePatchTypeRewrite indicates the file had a significant quantity of content changed. + FilePatchTypeRewrite FilePatchType = "REWRITE" +) + +// File represents a file in a patchset as well as how it is being modified. +type File struct { + File string `json:"file"` + FileOld string `json:"fileOld"` + Type FilePatchType `json:"type"` +} + +// PatchSet represents a single patchset within a change. +type PatchSet struct { + Number int `json:"number"` + Revision string `json:"revision"` + Parents []string `json:"parents"` + Ref string `json:"ref"` + Uploader Account `json:"uploader"` + Author Account `json:"author"` + CreatedOn Time `json:"createdOn"` + Kind ChangeKind `json:"kind"` + Approvals []Approval `json:"approvals"` + Comments []PatchSetComment `json:"comments"` + Files []File `json:"file"` + SizeInsertions int `json:"sizeInsertions"` + SizeDeletions int `json:"sizeDeletions"` +} + +// Dependency represents a change on which this change is dependent. +type Dependency struct { + ID string `json:"id"` + Number int `json:"number"` + Revision string `json:"revision"` + Ref string `json:"ref"` + IsCurrentPatchSet bool `json:"isCurrentPatchSet"` +} + +// SubmitStatus indicates whether this change has met the submit conditions and is ready to submit. +type SubmitStatus string + +const ( + // SubmitStatusOK indicates this change is ready to submit - all submit requirements are met. + SubmitStatusOK SubmitStatus = "OK" + + // SubmitStatusNotReady indicates this change cannot yet be submitted. + SubmitStatusNotReady SubmitStatus = "NOT_READY" + + // SubmitStatusRuleError indicates the submit rules could not be evaluted. Administrator intervention is required. + SubmitStatusRuleError SubmitStatus = "RULE_ERROR" +) + +// LabelStatus indicates whether this label permits submission and if the label can be granted by anyone. +type LabelStatus string + +const ( + // LabelStatusOK indicates that this label provides what is necessary for submission (e.g. CR+2). + LabelStatusOK LabelStatus = "OK" + + // LabelStatusReject indicates this label prevents submission (e.g. CR-2). + LabelStatusReject LabelStatus = "REJECT" + + // LabelStatusNeed indicates this label is required for submission, but has not been satisfied (e.g. CR0). + LabelStatusNeed LabelStatus = "NEED" + + // LabelStatusMay indicates this label is not required for submission. It may or may not be set. + LabelStatusMay LabelStatus = "MAY" + + // LabelStatusImpossible indicates this label is required for submission, but cannot be satisfied. The ACLs on this label may be set incorrectly. + LabelStatusImpossible LabelStatus = "IMPOSSIBLE" +) + +// Label represents the status of a particular label. +type Label struct { + Label string `json:"label"` + Status LabelStatus `json:"status"` + By Account `json:"by"` +} + +// Requirement represents a submit requirement. +type Requirement struct { + FallbackText string `json:"fallbackText"` + Type string `json:"type"` + // TODO(lukegb): data +} + +// SubmitRecord represents the current submission state of a change. +type SubmitRecord struct { + Status SubmitStatus `json:"status"` + Labels []Label `json:"labels"` + Requirements []Requirement `json:"requirements"` +} + +// Change represents a Gerrit CL. +type Change struct { + Project string `json:"project"` + Branch string `json:"branch"` + Topic string `json:"topic"` + ID string `json:"id"` + Number int `json:"number"` + Subject string `json:"subject"` + Owner Account `json:"owner"` + URL string `json:"url"` + CommitMessage string `json:"commitMessage"` + CreatedOn Time `json:"createdOn"` + LastUpdated *Time `json:"lastUpdated"` + Open bool `json:"open"` + Status ChangeStatus `json:"status"` + Private bool `json:"private"` + WIP bool `json:"wip"` + Comments []Message `json:"comments"` + TrackingIDs []TrackingID `json:"trackingIds"` + CurrentPatchSet *PatchSet `json:"currentPatchSet"` + PatchSets []PatchSet `json:"patchSets"` + DependsOn []Dependency `json:"dependsOn"` + NeededBy []Dependency `json:"neededBy"` + SubmitRecords []SubmitRecord `json:"submitRecord"` + AllReviewers []Account `json:"allReviewers"` +} + +// RefUpdate represents a change in a ref. +type RefUpdate struct { + OldRev string `json:"oldRev"` + NewRev string `json:"newRev"` + RefName string `json:"refName"` + Project string `json:"project"` +} diff --git a/fun/clbot/gerrit/watcher.go b/fun/clbot/gerrit/watcher.go new file mode 100644 index 000000000000..d45876129b3a --- /dev/null +++ b/fun/clbot/gerrit/watcher.go @@ -0,0 +1,252 @@ +// Package gerrit implements a watcher for Gerrit events. +package gerrit + +import ( + "context" + "errors" + "fmt" + "net" + "strings" + "time" + + "code.tvl.fyi/fun/clbot/backoffutil" + "code.tvl.fyi/fun/clbot/gerrit/gerritevents" + log "github.com/golang/glog" + "golang.org/x/crypto/ssh" +) + +// closer provides an embeddable implementation of Close which awaits a main loop acknowledging it has stopped. +type closer struct { + stop chan struct{} + stopped chan struct{} +} + +// newCloser returns a closer with the channels initialised. +func newCloser() closer { + return closer{ + stop: make(chan struct{}), + stopped: make(chan struct{}), + } +} + +// Close stops the main loop, waiting for the main loop to stop until it stops or the context is cancelled, whichever happens first. +func (c *closer) Close(ctx context.Context) error { + select { + case <-c.stopped: + return nil + case <-c.stop: + return nil + case <-ctx.Done(): + return ctx.Err() + default: + } + close(c.stop) + select { + case <-c.stopped: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// lineWriter is an io.Writer which splits on \n and outputs each line (with no trailing newline) to its output channel. +type lineWriter struct { + buf string + out chan string +} + +// Write accepts a slice of bytes containing zero or more new lines. +// If the contained channel is non-buffering or is full, this will block. +func (w *lineWriter) Write(p []byte) (n int, err error) { + w.buf += string(p) + pieces := strings.Split(w.buf, "\n") + w.buf = pieces[len(pieces)-1] + for n := 0; n < len(pieces)-1; n++ { + w.out <- pieces[n] + } + return len(p), nil +} + +// restartingClient is a simple SSH client that repeatedly connects to an SSH server, runs a command, and outputs the lines output by it on stdout onto a channel. +type restartingClient struct { + closer + + network string + addr string + cfg *ssh.ClientConfig + + exec string + output chan string + shutdown func() +} + +var ( + errStopConnect = errors.New("gerrit: told to stop reconnecting by remote server") +) + +func (c *restartingClient) runOnce() error { + netConn, err := net.Dial(c.network, c.addr) + if err != nil { + return fmt.Errorf("connecting to %v/%v: %w", c.network, c.addr, err) + } + defer netConn.Close() + + sshConn, newCh, newReq, err := ssh.NewClientConn(netConn, c.addr, c.cfg) + if err != nil { + return fmt.Errorf("creating SSH connection to %v/%v: %w", c.network, c.addr, err) + } + defer sshConn.Close() + + goAway := false + passedThroughReqs := make(chan *ssh.Request) + go func() { + defer close(passedThroughReqs) + for req := range newReq { + if req.Type == "goaway" { + goAway = true + log.Warningf("remote end %v/%v told me to go away!", c.network, c.addr) + sshConn.Close() + netConn.Close() + } + passedThroughReqs <- req + } + }() + + cl := ssh.NewClient(sshConn, newCh, passedThroughReqs) + + sess, err := cl.NewSession() + if err != nil { + return fmt.Errorf("NewSession on %v/%v: %w", c.network, c.addr, err) + } + defer sess.Close() + + sess.Stdout = &lineWriter{out: c.output} + + if err := sess.Start(c.exec); err != nil { + return fmt.Errorf("Start(%q) on %v/%v: %w", c.exec, c.network, c.addr, err) + } + + log.Infof("connected to %v/%v", c.network, c.addr) + + done := make(chan struct{}) + go func() { + sess.Wait() + close(done) + }() + go func() { + select { + case <-c.stop: + sess.Close() + case <-done: + } + return + }() + <-done + + if goAway { + return errStopConnect + } + return nil +} + +func (c *restartingClient) run() { + defer close(c.stopped) + bo := backoffutil.NewDefaultBackOff() + for { + timer := time.NewTimer(bo.NextBackOff()) + select { + case <-c.stop: + timer.Stop() + return + case <-timer.C: + break + } + if err := c.runOnce(); err == errStopConnect { + if c.shutdown != nil { + c.shutdown() + return + } + } else if err != nil { + log.Errorf("SSH: %v", err) + } else { + bo.Reset() + } + } +} + +// Output returns the channel on which each newline-delimited string output by the executed command's stdout can be received. +func (c *restartingClient) Output() <-chan string { + return c.output +} + +// dialRestartingClient creates a new restartingClient. +func dialRestartingClient(network, addr string, config *ssh.ClientConfig, exec string, shutdown func()) (*restartingClient, error) { + c := &restartingClient{ + closer: newCloser(), + network: network, + addr: addr, + cfg: config, + exec: exec, + output: make(chan string), + shutdown: shutdown, + } + go c.run() + return c, nil +} + +// Watcher watches +type Watcher struct { + closer + c *restartingClient + + output chan gerritevents.Event +} + +// Close shuts down the SSH client connection, if any, and closes the output channel. +// It blocks until shutdown is complete or until the context is cancelled, whichever comes first. +func (w *Watcher) Close(ctx context.Context) { + w.c.Close(ctx) + w.closer.Close(ctx) +} + +func (w *Watcher) run() { + defer close(w.stopped) + defer close(w.output) + for { + select { + case <-w.stop: + return + case o := <-w.c.Output(): + ev, err := gerritevents.Parse([]byte(o)) + if err != nil { + log.Errorf("failed to parse event %v: %v", o, err) + continue + } + w.output <- ev + } + } +} + +// Events returns the channel upon which parsed Gerrit events can be received. +func (w *Watcher) Events() <-chan gerritevents.Event { + return w.output +} + +// New returns a running Watcher from which events can be read. +// It will begin connecting to the provided address immediately. +func New(ctx context.Context, network, addr string, cfg *ssh.ClientConfig) (*Watcher, error) { + wc := newCloser() + rc, err := dialRestartingClient(network, addr, cfg, "gerrit stream-events", func() { + wc.Close(context.Background()) + }) + if err != nil { + return nil, fmt.Errorf("dialRestartingClient: %w", err) + } + w := &Watcher{ + closer: wc, + c: rc, + output: make(chan gerritevents.Event), + } + go w.run() + return w, nil +} diff --git a/fun/clbot/gerrit/watcher_test.go b/fun/clbot/gerrit/watcher_test.go new file mode 100644 index 000000000000..ae69b2fc4c18 --- /dev/null +++ b/fun/clbot/gerrit/watcher_test.go @@ -0,0 +1,190 @@ +package gerrit + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/subtle" + "fmt" + "net" + "testing" + "time" + + "code.tvl.fyi/fun/clbot/gerrit/gerritevents" + log "github.com/golang/glog" + "github.com/google/go-cmp/cmp" + "golang.org/x/crypto/ssh" +) + +var ( + sshServerSigner, sshServerPublicKey = mustNewKey() + sshClientSigner, sshClientPublicKey = mustNewKey() +) + +func mustNewKey() (ssh.Signer, ssh.PublicKey) { + key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + if err != nil { + panic(err) + } + signer, err := ssh.NewSignerFromKey(key) + if err != nil { + panic(err) + } + publicKey, err := ssh.NewPublicKey(key.Public()) + if err != nil { + panic(err) + } + return signer, publicKey +} + +func newSSHServer(lines string) (addr string, cleanup func(), err error) { + config := &ssh.ServerConfig{ + PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) { + pkBytes := pubKey.Marshal() + wantPKBytes := sshClientPublicKey.Marshal() + if subtle.ConstantTimeCompare(pkBytes, wantPKBytes) == 0 { + return nil, fmt.Errorf("unauthorized") + } + return &ssh.Permissions{}, nil + }, + } + config.AddHostKey(sshServerSigner) + + ln, err := net.Listen("tcp", ":0") + if err != nil { + log.Fatalf("Listen on tcp/:0: %v", err) + } + handle := func(conn net.Conn) { + defer conn.Close() + + sc, newchch, newreqch, err := ssh.NewServerConn(conn, config) + if err != nil { + log.Fatalf("NewServerConn: %v", err) + } + go ssh.DiscardRequests(newreqch) + for newCh := range newchch { + if newCh.ChannelType() != "session" { + newCh.Reject(ssh.UnknownChannelType, "unknown channel type") + continue + } + + channel, reqs, err := newCh.Accept() + if err != nil { + log.Fatalf("Could not accept channel: %v", err) + } + go func(in <-chan *ssh.Request) { + for req := range in { + req.Reply(req.Type == "exec", nil) + } + }(reqs) + channel.Write([]byte(lines)) + sc.SendRequest("goaway", false, nil) + } + } + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go handle(conn) + } + }() + + cleanup = func() { + ln.Close() + } + return ln.Addr().String(), cleanup, err +} + +func ts(s string) gerritevents.Time { + t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", s) + if err != nil { + panic(err) + } + return gerritevents.Time{t} +} + +func optStr(s string) *string { return &s } + +func TestWatcher(t *testing.T) { + tcs := []struct { + name string + lines string + want []gerritevents.Event + }{{ + name: "no events", + }, { + name: "single test event", + lines: `{"author":{"name":"tazjin","email":"mail@tazj.in","username":"tazjin"},"approvals":[{"type":"Code-Review","description":"Code-Review","value":"2","oldValue":"0"}],"comment":"Patch Set 3: Code-Review+2","patchSet":{"number":3,"revision":"6fe272d3f82c6efdfe1167fab98bf918efc03fe5","parents":["d984b6018cf68c7e8b7169b475d90134fbcee767"],"ref":"refs/changes/44/244/3","uploader":{"name":"tazjin","email":"mail@tazj.in","username":"tazjin"},"createdOn":1592081910,"author":{"name":"tazjin","email":"mail@tazj.in","username":"tazjin"},"kind":"REWORK","sizeInsertions":83,"sizeDeletions":-156},"change":{"project":"depot","branch":"master","id":"I546c701145fa204b7ba7518a8a56a783588629e0","number":244,"subject":"refactor(ops/nixos): Move my NixOS configurations to //users/tazjin","owner":{"name":"tazjin","email":"mail@tazj.in","username":"tazjin"},"url":"https://cl.tvl.fyi/c/depot/+/244","commitMessage":"refactor(ops/nixos): Move my NixOS configurations to //users/tazjin\n\nNixOS modules move one level up because it\u0027s unlikely that //ops/nixos\nwill contain actual systems at this point (they\u0027re user-specific).\n\nThis is the first users folder, so it is also added to the root\nreadTree invocation for the repository.\n\nChange-Id: I546c701145fa204b7ba7518a8a56a783588629e0\n","createdOn":1592081577,"status":"NEW"},"project":"depot","refName":"refs/heads/master","changeKey":{"id":"I546c701145fa204b7ba7518a8a56a783588629e0"},"type":"comment-added","eventCreatedOn":1592081929} +`, + want: []gerritevents.Event{ + &gerritevents.CommentAdded{ + Type: "comment-added", + Change: gerritevents.Change{ + Project: "depot", + Branch: "master", + ID: "I546c701145fa204b7ba7518a8a56a783588629e0", + Number: 244, + Subject: "refactor(ops/nixos): Move my NixOS configurations to //users/tazjin", + Owner: gerritevents.Account{Name: "tazjin", Email: "mail@tazj.in", Username: "tazjin"}, + URL: "https://cl.tvl.fyi/c/depot/+/244", + CommitMessage: "refactor(ops/nixos): Move my NixOS configurations to //users/tazjin\n\nNixOS modules move one level up because it's unlikely that //ops/nixos\nwill contain actual systems at this point (they're user-specific).\n\nThis is the first users folder, so it is also added to the root\nreadTree invocation for the repository.\n\nChange-Id: I546c701145fa204b7ba7518a8a56a783588629e0\n", + CreatedOn: ts("2020-06-13 21:52:57 +0100 BST"), + Status: "NEW", + }, + PatchSet: gerritevents.PatchSet{ + Number: 3, + Revision: "6fe272d3f82c6efdfe1167fab98bf918efc03fe5", + Parents: []string{"d984b6018cf68c7e8b7169b475d90134fbcee767"}, + Ref: "refs/changes/44/244/3", + Uploader: gerritevents.Account{Name: "tazjin", Email: "mail@tazj.in", Username: "tazjin"}, + Author: gerritevents.Account{Name: "tazjin", Email: "mail@tazj.in", Username: "tazjin"}, + CreatedOn: ts("2020-06-13 21:58:30 +0100 BST"), + Kind: "REWORK", + SizeInsertions: 83, + SizeDeletions: -156, + }, + Author: gerritevents.Account{Name: "tazjin", Email: "mail@tazj.in", Username: "tazjin"}, + Approvals: []gerritevents.Approval{{Type: "Code-Review", Description: "Code-Review", Value: "2", OldValue: optStr("0")}}, + Comment: "Patch Set 3: Code-Review+2", + EventCreatedOn: ts("2020-06-13 21:58:49 +0100 BST"), + }, + }, + }} + for _, tc := range tcs { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + serverAddr, cleanup, err := newSSHServer(tc.lines) + if err != nil { + t.Fatalf("newSSHServer: %v", err) + } + t.Cleanup(cleanup) + + config := &ssh.ClientConfig{ + User: "bert", + Auth: []ssh.AuthMethod{ssh.PublicKeys(sshClientSigner)}, + HostKeyCallback: ssh.FixedHostKey(sshServerPublicKey), + Timeout: 10 * time.Millisecond, + } + w, err := New(ctx, "tcp", serverAddr, config) + if err != nil { + t.Fatalf("New: %v", err) + } + + var gotEvents []gerritevents.Event + for ev := range w.Events() { + gotEvents = append(gotEvents, ev) + } + if diff := cmp.Diff(gotEvents, tc.want); diff != "" { + t.Errorf("got events != want events: diff:\n%v", diff) + } + }) + } +} diff --git a/fun/clbot/go.mod b/fun/clbot/go.mod new file mode 100644 index 000000000000..f954c752cb79 --- /dev/null +++ b/fun/clbot/go.mod @@ -0,0 +1,11 @@ +module code.tvl.fyi/fun/clbot + +go 1.14 + +require ( + github.com/cenkalti/backoff/v4 v4.0.2 + github.com/davecgh/go-spew v1.1.1 + github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b + github.com/google/go-cmp v0.4.1 + golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 +) diff --git a/fun/clbot/go.sum b/fun/clbot/go.sum new file mode 100644 index 000000000000..0c7fb33cb900 --- /dev/null +++ b/fun/clbot/go.sum @@ -0,0 +1,19 @@ +github.com/cenkalti/backoff v1.1.0 h1:QnvVp8ikKCDWOsFheytRCoYWYPO/ObCTBGxT19Hc+yE= +github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= +github.com/cenkalti/backoff/v4 v4.0.2 h1:JIufpQLbh4DkbQoii76ItQIUFzevQSqOLZca4eamEDs= +github.com/cenkalti/backoff/v4 v4.0.2/go.mod h1:eEew/i+1Q6OrCDZh3WiXYv3+nJwBASZ8Bog/87DQnVg= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/google/go-cmp v0.4.1 h1:/exdXoGamhu5ONeUJH0deniYLWYvQwW66yvlfiiKTu0= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM= +golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/fun/defer_rs/.gitignore b/fun/defer_rs/.gitignore new file mode 100644 index 000000000000..6aa106405a4b --- /dev/null +++ b/fun/defer_rs/.gitignore @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +Cargo.lock diff --git a/fun/defer_rs/Cargo.toml b/fun/defer_rs/Cargo.toml new file mode 100644 index 000000000000..0fcd60373ff7 --- /dev/null +++ b/fun/defer_rs/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "defer" +version = "0.1.0" +authors = ["Vincent Ambo <tazjin@gmail.com>"] + +[dependencies] diff --git a/fun/defer_rs/README.md b/fun/defer_rs/README.md new file mode 100644 index 000000000000..160158d177b8 --- /dev/null +++ b/fun/defer_rs/README.md @@ -0,0 +1,53 @@ +defer in Rust +============= + +After a Hacker News discussion about implementing Go's `defer` keyword in C++, +I stumbled upon [this comment](https://news.ycombinator.com/item?id=15523589) +and more specifically this response to it by "Occivink": + +> There's plenty of one-time cases where you don't want to declare an entire +> class but still enjoy scope-based functions. + +Specificall the "don't want to declare an entire class" suggests that languages +like C++ have high friction for explaining your desired invariant (cleanup is +run when `$thing` is destroyed) to the compiler. + +It seems like most languages either hand-wave this away (*cough* Java *cough*) +or use what seems like a workaround (`defer`). + +Rust has the so-called `Drop` trait, which is a typeclass that contains a single +method with no return value that is run when a variable is dropped (i.e. goes out +of scope). + +This works fine for most general cases - i.e. closing file handlers - but can +get complicated if other use-cases of `defer` are considered: + +* returning an error-value by mutating a reference in the enclosing scope (oh boy) +* deferring a decision about when/whether to run cleanup to the caller + +While thinking about how to do this with the `Drop` trait I realised that `defer` +can actually be trivially implemented in Rust, using `Drop`. + +A simple implementation of `defer` can be seen in [defer.rs](examples/defer.rs), +an implementation using shared mutable state for error returns is in the file +[defer-with-error.rs](examples/defer-with-error.rs) and an implementation that +allows cleanup to be *cancelled* (don't _actually_ do this, it leaks a pointer) +is in [undefer.rs](examples/undefer.rs). + +Whether any of this is actually useful is not up to me to decide. I haven't +actually had a real-life need for this. + +You can run the examples with `cargo run --example defer`, etc. + +## Notes + +* `Drop` is not guaranteed to run in case of panics or program aborts, if you + need support for that check out [scopeguard](https://github.com/bluss/scopeguard) +* `undefer` could be implemented safely by, for example, carrying a boolean that + by default causes execution to happen but can be flipped to disable it + +## Further reading: + +* [The Pain Of Real Linear Types in Rust](https://gankro.github.io/blah/linear-rust/) +* [Go's defer](https://tour.golang.org/flowcontrol/12) +* [Rust's Drop](https://doc.rust-lang.org/std/ops/trait.Drop.html) diff --git a/fun/defer_rs/examples/defer-with-error.rs b/fun/defer_rs/examples/defer-with-error.rs new file mode 100644 index 000000000000..26d56d77cf1b --- /dev/null +++ b/fun/defer_rs/examples/defer-with-error.rs @@ -0,0 +1,70 @@ +// Go's defer in Rust, with error value return. + +use std::rc::Rc; +use std::sync::RwLock; + +struct Defer<F: Fn()> { + f: F +} + +impl <F: Fn()> Drop for Defer<F> { + fn drop(&mut self) { + (self.f)() + } +} + +// Only added this for Go-syntax familiarity ;-) +fn defer<F: Fn()>(f: F) -> Defer<F> { + Defer { f } +} + +// Convenience type synonym. This is a reference-counted smart pointer to +// a shareable, mutable variable. +// Rust does not allow willy-nilly mutation of shared variables, so explicit +// write-locking must be performed. +type ErrorHandle<T> = Rc<RwLock<Option<T>>>; + +/////////////////// +// Usage example // +/////////////////// + +#[derive(Debug)] // Debug trait for some default way to print the type. +enum Error { DropError } + +fn main() { + // Create a place to store the error. + let drop_err: ErrorHandle<Error> = Default::default(); // create empty error + + // Introduce an arbitrary scope block (so that we still have control after + // the defer runs): + { + let mut i = 1; + + // Rc types are safe to clone and share for multiple ownership. + let err_handle = drop_err.clone(); + + // Call defer and let the closure own the cloned handle to the error: + let token = defer(move || { + // do something! + println!("Value is: {}", i); + + // ... oh no, it went wrong! + *err_handle.write().unwrap() = Some(Error::DropError); + }); + + i += 1; + println!("Value is: {}", i); + + // token goes out of scope here - drop() is called. + } + + match *drop_err.read().unwrap() { + Some(ref err) => println!("Oh no, an error occured: {:?}!", err), + None => println!("Phew, everything went well.") + }; +} + +// Prints: +// Value is: 2 +// Value is: 1 +// Oh no, an error occured: DropError! diff --git a/fun/defer_rs/examples/defer.rs b/fun/defer_rs/examples/defer.rs new file mode 100644 index 000000000000..eadac795f8bc --- /dev/null +++ b/fun/defer_rs/examples/defer.rs @@ -0,0 +1,31 @@ +// Go's defer in Rust! + +struct Defer<F: Fn()> { + f: F +} + +impl <F: Fn()> Drop for Defer<F> { + fn drop(&mut self) { + (self.f)() + } +} + +// Only added this for Go-syntax familiarity ;-) +fn defer<F: Fn()>(f: F) -> Defer<F> { + Defer { f } +} + +fn main() { + let mut i = 1; + + // Calling it "token" ... could be something else. The lifetime of this + // controls when the action is run. + let _token = defer(move || println!("Value is: {}", i)); + + i += 1; + println!("Value is: {}", i); +} + +// Prints: +// Value is: 2 +// Value is: 1 diff --git a/fun/defer_rs/examples/undefer.rs b/fun/defer_rs/examples/undefer.rs new file mode 100644 index 000000000000..17ad8a6b5485 --- /dev/null +++ b/fun/defer_rs/examples/undefer.rs @@ -0,0 +1,40 @@ +// Go's defer in Rust, with a little twist! + +struct Defer<F: Fn()> { + f: F +} + +impl <F: Fn()> Drop for Defer<F> { + fn drop(&mut self) { + (self.f)() + } +} + +// Only added this for Go-syntax familiarity ;-) +fn defer<F: Fn()>(f: F) -> Defer<F> { + Defer { f } +} + +// Changed your mind about the defer? +// (Note: This leaks the closure! Don't actually do this!) +fn undefer<F: Fn()>(token: Defer<F>) { + use std::mem; + mem::forget(token); +} + +fn main() { + let mut i = 1; + + // Calling it "token" ... could be something else. The lifetime of this + // controls when the action is run. + let token = defer(move || println!("Value is: {}", i)); + + i += 1; + println!("Value is: {}", i); + + // Oh, now I changed my mind about the previous defer: + undefer(token); +} + +// Prints: +// Value is: 2 diff --git a/fun/dt/CMakeLists.txt b/fun/dt/CMakeLists.txt new file mode 100644 index 000000000000..85b659fea862 --- /dev/null +++ b/fun/dt/CMakeLists.txt @@ -0,0 +1,16 @@ +# -*- mode: cmake; -*- +cmake_minimum_required(VERSION 3.16) +project(dt) +add_executable(dt dt.cc) +find_package(absl REQUIRED) + +target_link_libraries(dt + absl::flags + absl::flags_parse + absl::hash + absl::time + absl::strings + farmhash +) + +install(TARGETS dt DESTINATION bin) diff --git a/fun/dt/README.md b/fun/dt/README.md new file mode 100644 index 000000000000..ee43d5606409 --- /dev/null +++ b/fun/dt/README.md @@ -0,0 +1,11 @@ +dt +== + +It's got a purpose. + +## Usage: + +``` +nix-build -E '(import (builtins.fetchGit "https://git.tazj.in/") {}).fun.dt' +./result/bin/dt --one ... --two ... +``` diff --git a/fun/dt/default.nix b/fun/dt/default.nix new file mode 100644 index 000000000000..b6efa289948b --- /dev/null +++ b/fun/dt/default.nix @@ -0,0 +1,14 @@ +{ depot, pkgs, ... }: + +let + stdenv = with pkgs; overrideCC clangStdenv clang_10; + abseil_cpp = pkgs.abseil_cpp.override { inherit stdenv; }; +in stdenv.mkDerivation { + name = "dt"; + src = ./.; + nativeBuildInputs = [ pkgs.cmake ]; + buildInputs = with pkgs; [ + abseil_cpp + farmhash + ]; +} diff --git a/fun/dt/dt.cc b/fun/dt/dt.cc new file mode 100644 index 000000000000..5c4c3da76853 --- /dev/null +++ b/fun/dt/dt.cc @@ -0,0 +1,79 @@ +#include <iostream> +#include <vector> + +#include "absl/flags/flag.h" +#include "absl/flags/parse.h" +#include "absl/hash/hash.h" +#include "absl/strings/str_cat.h" +#include "absl/time/clock.h" +#include "absl/time/time.h" +#include "absl/types/optional.h" +#include "farmhash.h" + +ABSL_FLAG(std::vector<std::string>, words, {}, "words to use"); + +struct Result { + std::string a; + int ec; + absl::optional<std::string> p; +}; + +std::string which(const std::vector<std::string>& words) { + uint64_t fp; + std::string word; + + for (const auto& w : words) { + auto nfp = util::Fingerprint64(w); + if (nfp > fp) { + fp = nfp; + word = w; + } + } + + return word; +} + +Result decide(const std::vector<std::string>& words) { + auto input = absl::FormatTime("%Y%m%d", absl::Now(), absl::UTCTimeZone()); + for (const auto& w : words) { + input += w; + } + + auto base = util::Fingerprint64(input); + Result result = { "nope" }; + + if (base % 10 == 0) { + result.a = "ca"; + } else if (base % 8 == 0) { + result.a = "c1"; + result.p = which(words); + } else if (base % 6 == 0) { + result.a = "skip"; + } else if (base % 3 == 0) { + result.a = "e1"; + result.ec = base % 10; + result.p = which(words); + } else if (base % 2 == 0) { + result.a = "ea"; + result.ec = base % 10; + } + + return result; +} + +int main(int argc, char *argv[]) { + absl::ParseCommandLine(argc, argv); + + auto words = absl::GetFlag(FLAGS_words); + if (words.size() < 2) { + std::cerr << "needs at least two!" << std::endl; + return 1; + } + + auto result = decide(words); + std::cout << result.a + << (result.p.has_value() ? absl::StrCat(" ", "(", result.p.value(), ")") + : "") + << (result.ec > 0 ? absl::StrCat(": ", result.ec) : "") + << std::endl; +} diff --git a/fun/elblog/.gitignore b/fun/elblog/.gitignore new file mode 100644 index 000000000000..c531d9867f6c --- /dev/null +++ b/fun/elblog/.gitignore @@ -0,0 +1 @@ +*.elc diff --git a/fun/elblog/README.md b/fun/elblog/README.md new file mode 100644 index 000000000000..994b1138ef8f --- /dev/null +++ b/fun/elblog/README.md @@ -0,0 +1,11 @@ +elblog +====== + +This is a simple blogging software written in Emacs Lisp. + +The idea is that it should be able to do most of the things [my actual blog][] +does at the moment. + +No documentation exists for now besides the commit messages, but it works! + +[my actual blog]: https://www.tazj.in/ diff --git a/fun/elblog/blog.css b/fun/elblog/blog.css new file mode 100644 index 000000000000..0d021f78e89b --- /dev/null +++ b/fun/elblog/blog.css @@ -0,0 +1,37 @@ +<style type="text/css"> +body { + margin: 40px auto; + max-width: 800px; + line-height: 1.6; + font-size: 18px; + color: #383838; + padding: 0 10px +} +h1, h2, h3 { + line-height: 1.2 +} +.footer { + text-align: right; +} +.lod { + text-align: center; +} +.unstyled-link { + color: inherit; + text-decoration: none; +} +.uncoloured-link { + color: inherit; +} +.date { + text-align: right; + font-style: italic; + float: right; +} +.inline { + display: inline; +} +.navigation { + text-align: center; +} +</style> diff --git a/fun/elblog/blog.el b/fun/elblog/blog.el new file mode 100644 index 000000000000..102aa3791481 --- /dev/null +++ b/fun/elblog/blog.el @@ -0,0 +1,123 @@ +;;; blog.el --- A simple org-mode & elnode blog software. +;;; -*- lexical-binding: t; -*- + +(require 'dash) +(require 'elnode) +(require 'f) +(require 'ht) + +;; Definition of customization options + +(defgroup elblog nil + "Configuration for the Emacs Lisp blog software" + :link '(url-link "https://github.com/tazjin/elblog")) + +(defcustom elblog-port 8010 + "Port to run elblog's HTTP server on" + :group 'elblog + :type 'integer) + +(defcustom elblog-host "localhost" + "Host for elblog's HTTP server to listen on" + :group 'elblog + :type 'string) + +(defcustom elblog-title "Elblog" + "Title text for this elblog instance" + :group 'elblog + :type 'string) + +(defcustom elblog-article-directory nil + "Directory in which elblog articles are stored" + :group 'elblog + :type 'string) + +(defcustom elblog-additional-routes '() + "Additional Elnode routes to register in the Elblog instance" + :group 'elblog + :type '(alist :key-type regexp :value-type function)) + +;; Declare user-configurable variables needed at runtime. + +(defvar elblog-articles (ht-create) + "A hash-table of blog articles. This is used for looking up articles from + URL fragments as well as for rendering the index.") + +;; HTML templating setup + +(defun template-preamble () + "Templates the preamble snippet with the correct blog title." + (format (f-read-text "preamble.html") elblog-title)) + +(defun configure-org-html-export () + "Configure org-mode settings for elblog's HTML templating to work correctly." + (setq org-html-postamble t) + (setq org-html-doctype "html5") + (setq org-html-head-include-scripts nil) + (setq org-html-style-default (f-read-text "blog.css")) + (setq org-html-preamble-format `(("en" ,(template-preamble)))) + (setq org-html-postamble-format `(("en" ,(f-read-text "postamble.html"))))) + +;; Article fetching & rendering functions + +(defun render-org-buffer (input-buffer &optional force) + "Renders an org-mode buffer as HTML and returns the name of the output buffer." + (letrec ((output-buffer (concat (buffer-name input-buffer) "-rendered")) + ;; Don't re-render articles unless forced. + (must-render (or force + (not (get-buffer output-buffer))))) + (if (and input-buffer must-render) + (with-current-buffer input-buffer + (org-export-to-buffer 'html output-buffer nil nil t))) + (if input-buffer output-buffer nil))) + +(defun get-buffer-string (buffer) + "Returns the contents of the specified buffer as a string." + (with-current-buffer (get-buffer buffer) + (buffer-string))) + +(defvar-local article-not-found + '(404 . "<html><body><p>Oh no, the article was not found.</p></body></html>")) + +(defvar-local text-html '("Content-Type" . "text/html")) + +(defun render-article (article) + "Renders an article, if it exists." + (letrec ((rendered (-some->> + (ht-get elblog-articles article) + (concat elblog-article-directory) + (find-file) + (render-org-buffer)))) + (if rendered `(200 . ,(get-buffer-string rendered)) + article-not-found))) + +(defun blog-post-handler (httpcon) + "This handler servers a blog post from the configured blog post directory." + (let ((response (render-article (elnode-http-mapping httpcon 1)))) + (elnode-http-start httpcon (car response) text-html) + (elnode-http-return httpcon (cdr response)))) + +;; Web server implementation + +(defvar elblog-routes + '(("^.*//\\(.*\\)" . blog-post-handler)) + "The default routes available in elblog. They can be extended by the user +by setting the elblog-additional-routes customize option.") + +(defun elblog-handler (httpcon) + (elnode-hostpath-dispatcher + httpcon + (-concat elblog-additional-routes elblog-routes))) + +(defun start-elblog () + (interactive) + (configure-org-html-export) + (elnode-start 'elblog-handler + :port elblog-port + :host elblog-host)) + +(defun stop-elblog () + (interactive) + (elnode-stop elblog-port)) + +(provide 'elblog) diff --git a/fun/elblog/postamble.html b/fun/elblog/postamble.html new file mode 100644 index 000000000000..16a26218a0c0 --- /dev/null +++ b/fun/elblog/postamble.html @@ -0,0 +1,9 @@ +<hr> +<footer><p class="footer">Served with <a class="uncoloured-link" href="https://github.com/tazjin/elblog">Emacs</a>.</p> + <p class="footer"> + <a class="uncoloured-link" href="https://twitter.com/tazjin">Twitter</a> + | + <a class="uncoloured-link" href="mailto:blog@tazj.in">Mail</a> + </p> + <p class="lod">เฒ _เฒ </p> +</footer> diff --git a/fun/elblog/preamble.html b/fun/elblog/preamble.html new file mode 100644 index 000000000000..be74b9207e72 --- /dev/null +++ b/fun/elblog/preamble.html @@ -0,0 +1,6 @@ +<header> + <h1> + <a class="unstyled-link" href="/">%s</a> + </h1> + <hr> +</header> diff --git a/fun/gemma/CODE_OF_CONDUCT.md b/fun/gemma/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..c4013ac13ebc --- /dev/null +++ b/fun/gemma/CODE_OF_CONDUCT.md @@ -0,0 +1,20 @@ +A SERMON ON ETHICS AND LOVE +=========================== + +One day Mal-2 asked the messenger spirit Saint Gulik to approach the Goddess and request Her presence for some desperate advice. Shortly afterwards the radio came on by itself, and an ethereal female Voice said **YES?** + +"O! Eris! Blessed Mother of Man! Queen of Chaos! Daughter of Discord! Concubine of Confusion! O! Exquisite Lady, I beseech You to lift a heavy burden from my heart!" + +**WHAT BOTHERS YOU, MAL? YOU DON'T SOUND WELL.** + +"I am filled with fear and tormented with terrible visions of pain. Everywhere people are hurting one another, the planet is rampant with injustices, whole societies plunder groups of their own people, mothers imprison sons, children perish while brothers war. O, woe." + +**WHAT IS THE MATTER WITH THAT, IF IT IS WHAT YOU WANT TO DO?** + +"But nobody Wants it! Everybody hates it." + +**OH. WELL, THEN *STOP*.** + +At which moment She turned herself into an aspirin commercial and left The Polyfather stranded alone with his species. + +SINISTER DEXTER HAS A BROKEN SPIROMETER. diff --git a/fun/gemma/LICENSE b/fun/gemma/LICENSE new file mode 100644 index 000000000000..94a9ed024d38 --- /dev/null +++ b/fun/gemma/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/fun/gemma/README.md b/fun/gemma/README.md new file mode 100644 index 000000000000..064742c0091f --- /dev/null +++ b/fun/gemma/README.md @@ -0,0 +1,96 @@ +# Gemma + +Gemma is a simple application to track *recurring* tasks, named after Gemma +Hartley who [wrote an article][] about task distribution issues in households. + +## Background + +(Skip this if you just want the technical bits) + +Gemma's article launched a discussion in my friend circle about what causes an +uneven distribution of household workload. I theorised that this is not so much +a gender issue, but mostly a discoverability issue. + +Usually one person in a household is aware of what needs to be done, but in many +cases the "overhead" of delegating the tasks would actually take more time than +simply doing the task. + +I theorise further that the person (or people) who do a smaller share of the +household work would often do the work if they had a convenient way to become +aware of what needs to be done. Many times the "household manager" has the +function of tracking non-obvious tasks like when bedsheets were last changed - +shouldn't it be possible to actually distribute this information somehow? + +## The Project + +This project is an initial attempt at sketching out a little application that +aids with reminding users of recurring tasks. Some basic ideas: + +* The system should be blame-free. +* There should be as little usage overhead as possible so that people actually + do use it. +* It should work mostly passively without much user interaction. + +I believe that the basic (*very* simple) idea behind Gemma solves these issues. +Unfortunately my living situation changed before I actually got to test this out +in a real-life situation involving multiple people, but feedback from other +potential test subjects would be welcome! :) + +## Overview + +Gemma is a Common Lisp application in which a list of recurring tasks is +declared, together with the *maximum interval* at which they should be completed +(in days). Example: + +```lisp +;; Bathroom tasks +(deftask bathroom/wipe-mirror 7) +(deftask bathroom/wipe-counter 7) + +;; Bedroom tasks +(deftask bedroom/change-sheets 7) +(deftask bedroom/vacuum 10) + +;; Kitchen tasks +(deftask kitchen/trash 3) +(deftask kitchen/wipe-counters 3) +(deftask kitchen/vacuum 5 "Kitchen has more crumbs and such!") + +;; Entire place +(deftask clean-windows 60) +``` + +These tasks are marked with their last completion time and tracked by Gemma. A +simple Elm-based frontend application displays the tasks sorted by their +"urgency" and features a button to mark a task as completed: + +![Gemma screenshot](http://i.imgur.com/n7FFMJH.png) + +Marking a task as completed resets its counter and moves it to the bottom of the +task list. + +In theory this *should be it*, the frontend is made available to household +members in some easily accessible place (e.g. an old phone glued to the fridge!) +and people should attempt to develop a habit of checking what needs to be done +occasionally. + +The "household manager" still exists as a role of the household because someone +is entering the tasks into the application, but if my theory about people not +actually being actively *unwilling* to do tasks is correct this could help a +lot. + +## Usage + +(*Note*: Gemma is alpha software so the below is clearly not the final goal) + +Right now using this is non-trivial, but I'll eventually make a better +distribution. Basically you need to know Common Lisp (in which case you'll know +how to get the backend running) and have `elm-reactor` installed to run the +development version of the frontend application. + +Gemma is configured via a configuration file that should be located either at +`/etc/gemma/config.lisp` or at a custom location specified via the environment +variable `GEMMA_CONFIG`. Have a look at the `config.lisp` file in the repository +root for an example. + +[wrote an article]: http://www.harpersbazaar.com/culture/features/a12063822/emotional-labor-gender-equality/ diff --git a/fun/gemma/config.lisp b/fun/gemma/config.lisp new file mode 100644 index 000000000000..54f8e5f34462 --- /dev/null +++ b/fun/gemma/config.lisp @@ -0,0 +1,21 @@ +;; Example configuration file for Gemma + +(config :port 4242 + :data-dir "/tmp/gemma/") + +(deftask bathroom/wipe-mirror 7) +(deftask bathroom/wipe-counter 7) + +;; Bedroom tasks +(deftask bedroom/change-sheets 7) +(deftask bedroom/vacuum 10) + +;; Kitchen tasks +(deftask kitchen/normal-trash 3) +(deftask kitchen/green-trash 5) +(deftask kitchen/blue-trash 5) +(deftask kitchen/wipe-counters 3) +(deftask kitchen/vacuum 5 "Kitchen has more crumbs and such!") + +;; Entire place +(deftask clean-windows 60) diff --git a/fun/gemma/default.nix b/fun/gemma/default.nix new file mode 100644 index 000000000000..55612106d2e0 --- /dev/null +++ b/fun/gemma/default.nix @@ -0,0 +1,50 @@ +{ depot, ... }: + +let + inherit (depot) elmPackages; + inherit (depot.third_party) cacert iana-etc libredirect stdenv runCommandNoCC writeText; + + frontend = stdenv.mkDerivation { + name = "gemma-frontend.html"; + src = ./frontend; + buildInputs = [ cacert iana-etc elmPackages.elm ]; + + # The individual Elm packages this requires are not packaged and I + # can't be bothered to do that now, so lets open the escape hatch: + outputHashAlgo = "sha256"; + outputHash = "000xhds5bsig3kbi7dhgbv9h7myacf34bqvw7avvz7m5mwnqlqg7"; + + phases = [ "unpackPhase" "buildPhase" ]; + buildPhase = '' + export NIX_REDIRECTS=/etc/protocols=${iana-etc}/etc/protocols \ + LD_PRELOAD=${libredirect}/lib/libredirect.so + + export SYSTEM_CERTIFICATE_PATH=${cacert}/etc/ssl/certs + + mkdir .home && export HOME="$PWD/.home" + elm-make --yes Main.elm --output $out + ''; + }; + + injectFrontend = writeText "gemma-frontend.lisp" '' + (in-package :gemma) + (setq *static-file-location* "${runCommandNoCC "frontend" {} '' + mkdir -p $out + cp ${frontend} $out/index.html + ''}/") + ''; +in depot.nix.buildLisp.program { + name = "gemma"; + + deps = with depot.third_party.lisp; [ + cl-json + cl-prevalence + hunchentoot + local-time + ]; + + srcs = [ + ./src/gemma.lisp + injectFrontend + ]; +} diff --git a/fun/gemma/frontend/Main.elm b/fun/gemma/frontend/Main.elm new file mode 100644 index 000000000000..e449908e499c --- /dev/null +++ b/fun/gemma/frontend/Main.elm @@ -0,0 +1,221 @@ +-- Copyright (C) 2016-2017 Vincent Ambo <mail@tazj.in> +-- +-- This file is part of Gemma. +-- +-- Gemma is free software: you can redistribute it and/or modify it +-- under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. + + +module Main exposing (..) + +import Html exposing (Html, text, div, span) +import Html.Attributes exposing (style) +import Json.Decode exposing (..) +import Http +import Time + + +-- Material design imports + +import Material +import Material.Card as Card +import Material.Color as Color +import Material.Grid exposing (grid, cell, size, Device(..)) +import Material.Layout as Layout +import Material.Scheme as Scheme +import Material.Options as Options +import Material.Elevation as Elevation +import Material.Button as Button + + +-- API interface to Gemma + + +type alias Task = + { name : String + , description : Maybe String + , remaining : Int + } + + +emptyStringFilter s = + if s == "" then + Nothing + else + Just s + + +decodeEmptyString : Decoder (Maybe String) +decodeEmptyString = + map emptyStringFilter string + + +decodeTask : Decoder Task +decodeTask = + map3 Task + (field "name" string) + (field "description" decodeEmptyString) + (field "remaining" int) + + +loadTasks : Cmd Msg +loadTasks = + let + request = + Http.get "/tasks" (list decodeTask) + in + Http.send NewTasks request + + +completeTask : Task -> Cmd Msg +completeTask task = + let + request = + Http.getString + (String.concat + [ "/complete?task=" + , task.name + ] + ) + in + Http.send (\_ -> LoadTasks) request + + + +-- Elm architecture implementation + + +type Msg + = None + | LoadTasks + | NewTasks (Result Http.Error (List Task)) + | Mdl (Material.Msg Msg) + | Complete Task + + +type alias Model = + { tasks : List Task + , error : Maybe String + , mdl : Material.Model + } + + +update : Msg -> Model -> ( Model, Cmd Msg ) +update msg model = + case msg of + LoadTasks -> + ( model, loadTasks ) + + Complete task -> + ( model, completeTask task ) + + NewTasks (Ok tasks) -> + ( { model | tasks = tasks, error = Nothing }, Cmd.none ) + + NewTasks (Err err) -> + ( { model | error = Just (toString err) }, Cmd.none ) + + _ -> + ( model, Cmd.none ) + + + +-- View implementation + + +white = + Color.text Color.white + + +taskColor : Task -> Color.Hue +taskColor task = + if task.remaining > 2 then + Color.Green + else if task.remaining < 0 then + Color.Red + else + Color.Yellow + + +within : Task -> String +within task = + if task.remaining < 0 then + "This task is overdue!" + else if task.remaining > 2 then + String.concat + [ "Relax, this task has " + , toString task.remaining + , " days left before it is due." + ] + else + String.concat + [ "This task should be completed within " + , toString task.remaining + , " days. Consider doing it now!" + ] + + +renderTask : Model -> Task -> Html Msg +renderTask model task = + Card.view + [ Color.background (Color.color (taskColor task) Color.S800) + , Elevation.e3 + ] + [ Card.title [] [ Card.head [ white ] [ text task.name ] ] + , Card.text [ white ] + [ text (Maybe.withDefault "" task.description) + , Html.br [] [] + , text (within task) + ] + , Card.actions + [ Card.border ] + [ Button.render Mdl + [ 0 ] + model.mdl + [ white, Button.ripple, Button.accent, Options.onClick (Complete task) ] + [ text "Completed" ] + ] + ] + + +gemmaView : Model -> Html Msg +gemmaView model = + grid [] + (List.map (\t -> cell [ size All 4 ] [ renderTask model t ]) + model.tasks + ) + + +view : Model -> Html Msg +view model = + gemmaView model |> Scheme.top + + + +-- subscriptions : Model -> Sub Msg + + +subscriptions model = + Sub.batch + [ Material.subscriptions Mdl model + , Time.every (15 * Time.second) (\_ -> LoadTasks) + ] + + +main : Program Never Model Msg +main = + let + model = + { tasks = [] + , error = Nothing + , mdl = Material.model + } + in + Html.program + { init = ( model, Cmd.batch [ loadTasks, Material.init Mdl ] ) + , view = view + , update = update + , subscriptions = subscriptions + } diff --git a/fun/gemma/frontend/elm-package.json b/fun/gemma/frontend/elm-package.json new file mode 100644 index 000000000000..2ae541ae0b95 --- /dev/null +++ b/fun/gemma/frontend/elm-package.json @@ -0,0 +1,17 @@ +{ + "version": "1.0.0", + "summary": "helpful summary of your project, less than 80 characters", + "repository": "https://github.com/user/project.git", + "license": "BSD3", + "source-directories": [ + "." + ], + "exposed-modules": [], + "dependencies": { + "elm-lang/core": "5.1.1 <= v < 6.0.0", + "elm-lang/html": "2.0.0 <= v < 3.0.0", + "elm-lang/http": "1.0.0 <= v < 2.0.0", + "debois/elm-mdl": "8.1.0 <= v < 9.0.0" + }, + "elm-version": "0.18.0 <= v < 0.19.0" +} diff --git a/fun/gemma/src/gemma.lisp b/fun/gemma/src/gemma.lisp new file mode 100644 index 000000000000..20a76caae629 --- /dev/null +++ b/fun/gemma/src/gemma.lisp @@ -0,0 +1,192 @@ +;; Copyright (C) 2016-2020 Vincent Ambo <mail@tazj.in> +;; +;; This file is part of Gemma. +;; +;; Gemma is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +(defpackage gemma + (:use :cl + :local-time + :cl-json) + (:import-from :sb-posix :getenv) + (:shadowing-import-from :sb-posix :getcwd) + (:export :start-gemma :config :main)) +(in-package :gemma) + +;; TODO: Store an average of how many days it was between task +;; completions. Some of the current numbers are just guesses +;; anyways. + +(defmacro in-case-of (x &body body) + "Evaluate BODY if X is non-nil, binding the value of X to IT." + `(let ((it ,x)) + (when it ,@body))) + +;; Set default configuration parameters +(defvar *gemma-port* 4242 + "Port on which the Gemma web server listens.") + +(defvar *gemma-acceptor* nil + "Hunchentoot acceptor for Gemma's web server.") + +(defvar *static-file-location* "frontend/" + "Folder from which to serve static assets. If built inside of Nix, + the path is injected during the build.") + +(defvar *p-tasks* nil + "All tasks registered in this Gemma instance.") + +(defun initialise-persistence (data-dir) + (setq *p-tasks* (cl-prevalence:make-prevalence-system data-dir)) + + ;; Initialise database ID counter + (or (> (length (cl-prevalence:find-all-objects *p-tasks* 'task)) 0) + (cl-prevalence:tx-create-id-counter *p-tasks*))) + +(defun config (&key port data-dir) + "Configuration function for use in the Gemma configuration file." + + (in-package :gemma) + (in-case-of port (defparameter *gemma-port* it)) + (initialise-persistence (or data-dir "data/"))) + +;; +;; Define task management system +;; + +(defclass task () + ((id :reader id + :initarg :id) + + ;; (Unique) name of the task + (name :type symbol + :initarg :name + :accessor name-of) + + ;; Maximum completion interval + (days :type integer + :initarg :days + :accessor days-of) + + ;; Optional description + (description :type string + :initarg :description + :accessor description-of) + + ;; Last completion time + (done-at :type timestamp + :initarg :done-at + :accessor last-done-at))) + +(defmacro deftask (task-name days &optional description) + (unless (get-task task-name) + `(progn (cl-prevalence:tx-create-object + *p-tasks* + 'task + (quote ((name ,task-name) + (days ,days) + (description ,(or description "")) + (done-at ,(now))))) + (cl-prevalence:snapshot *p-tasks*)))) + +(defun get-task (name) + (cl-prevalence:find-object-with-slot *p-tasks* 'task 'name name)) + +(defun list-tasks () + (cl-prevalence:find-all-objects *p-tasks* 'task)) + +(defun days-remaining (task) + "Returns the number of days remaining before the supplied TASK reaches its +maximum interval." + (let* ((expires-at (timestamp+ (last-done-at task) + (days-of task) :day)) + (secs-until-expiry (timestamp-difference expires-at (now)))) + (round (/ secs-until-expiry 60 60 24)))) + +(defun sort-tasks (tasks) + "Sorts TASKS in descending order by number of days remaining." + (sort (copy-list tasks) + (lambda (t1 t2) (< (days-remaining t1) + (days-remaining t2))))) + +(defun complete-task (name &optional at) + "Mark the task with NAME as completed, either now or AT specified time." + (cl-prevalence:tx-change-object-slots *p-tasks* 'task + (id (get-task name)) + `((done-at ,(or at (now))))) + (cl-prevalence:snapshot *p-tasks*)) + +;; +;; Define web API +;; + +(defun response-for (task) + "Create a response object to be JSON encoded for TASK." + `((:name . ,(name-of task)) + (:description . ,(description-of task)) + (:remaining . ,(days-remaining task)))) + +(defun start-gemma () + (in-package :gemma) + + ;; Load configuration + (load (pathname (or (getenv "GEMMA_CONFIG") + "/etc/gemma/config.lisp"))) + + ;; Set up web server + (setq *gemma-acceptor* (make-instance 'hunchentoot:easy-acceptor + :port *gemma-port* + :document-root *static-file-location*)) + (hunchentoot:start *gemma-acceptor*) + + ;; Task listing handler + (hunchentoot:define-easy-handler + (get-tasks :uri "/tasks") () + + (setf (hunchentoot:content-type*) "application/json") + (setf (hunchentoot:header-out "Access-Control-Allow-Origin") "*") + (encode-json-to-string + ;; Construct a frontend-friendly representation of the tasks. + (mapcar #'response-for (sort-tasks (list-tasks))))) + + ;; Task completion handler + (hunchentoot:define-easy-handler + (complete-task-handler :uri "/complete") (task) + (setf (hunchentoot:content-type*) "application/json") + (let* ((key (find-symbol (camel-case-to-lisp task) "GEMMA"))) + (format t "Marking task ~A as completed" key) + (complete-task key) + (encode-json-to-string (response-for (get-task key)))))) + +(defun main () + "This function serves as the entrypoint for ASDF-built executables. + It joins the Hunchentoot server thread to keep the process running + for as long as the server is alive." + + (start-gemma) + (sb-thread:join-thread + (find-if (lambda (th) + (string= (sb-thread:thread-name th) + (format nil "hunchentoot-listener-*:~A" *gemma-port*))) + (sb-thread:list-all-threads)))) + +;; Experimentation / testing stuff + +(defun randomise-completion-times () + "Set some random completion timestamps for all tasks" + (mapcar + (lambda (task) + (complete-task (name-of task) + (timestamp- (now) + (random 14) + :day))) + (cl-prevalence:find-all-objects *p-tasks* 'task))) + +(defun clear-all-tasks () + (mapcar (lambda (task) (cl-prevalence:tx-delete-object *p-tasks* 'task (id task))) + (cl-prevalence:find-all-objects *p-tasks* 'task))) + +;; (randomise-completion-times) diff --git a/fun/idual/README.md b/fun/idual/README.md new file mode 100644 index 000000000000..922047617f25 --- /dev/null +++ b/fun/idual/README.md @@ -0,0 +1,34 @@ +# iDual light control + +This folder contains some tooling for controlling iDual LED lights +(which use infrared controls) using a "Broadlink RM Pro" infrared +controller. + +The supported colour codes of the iDual remote are stored in +`codes.txt`. + +The point of this is to make it possible for me to automate my lights +in the morning, so that I can actually get out of bed. + +## Capturing codes + +Capturing codes is relatively easy, assuming that the broadlink device +is set up: + +```python +import broadlink +import base64 + +devices = broadlink.discover(timeout=5) +devices[0].auth() +``` + +For each code, the procedure is as follows: + +```python +devices[0].find_rf_packet() +# wait until this returns True + +devices[0].check_data() +# this will return the code +``` diff --git a/fun/idual/default.nix b/fun/idual/default.nix new file mode 100644 index 000000000000..1ac87ab47f0f --- /dev/null +++ b/fun/idual/default.nix @@ -0,0 +1,24 @@ +{ pkgs, lib, ... }: + +let + inherit (pkgs) python python3 python3Packages; + + opts = { + pname = "idualctl"; + version = "0.1"; + src = ./.; + + propagatedBuildInputs = [ + python.broadlink + ]; + }; + package = python3Packages.buildPythonPackage opts; + script = python3Packages.buildPythonApplication opts; +in { + inherit script; + python = python3.withPackages (_: [ package ]); + setAlarm = pkgs.writeShellScriptBin "set-alarm" '' + echo "setting an alarm for ''${1}" + ${pkgs.systemd}/bin/systemd-run --user --on-calendar="''${1} Europe/London" --unit=light-alarm.service + ''; +} diff --git a/fun/idual/idual/__init__.py b/fun/idual/idual/__init__.py new file mode 100644 index 000000000000..35c3bbae9039 --- /dev/null +++ b/fun/idual/idual/__init__.py @@ -0,0 +1,65 @@ +import base64 +import broadlink +import time +import sys + +commands = { + # system commands + 'on' : 'JgBIAAABK5AVERQ2FBEUERQSFBEUERQSFBEUNhQ2FDUUNhQ2FDYUNRU1FBIUERQRFBIUERQRFBIUERQ2FDYUNRQ2FDYUNhQ1FQANBQ==', + 'off' : 'JgBIAAABLJAUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNhQRFDYUERQSFBEUERQSFBEUNhQRFDYUNhQ2FDUUNhQ2FAANBQ==', + 'darker' : 'JgBIAAABLI8VERQ2FBEUERURFBEUEhQRFBEUNhQ2FDYUNRU1FDYUNhQRFBIUERQRFDYUEhQRFBEVNRQ2FDYUNhQRFDYUNhQ1FQANBQ==', + 'brighter' : 'JgBIAAABLI8VERQ2FBEUERQSFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUERQ2FBEUEhQRFBEUEhQ1FTUUEhQ1FTUUNhQ2FAANBQ==', + + # presets + 'candle' : 'JgBQAAABKZISExI4EhMSFBITEhQRFBITEhQROBI4EjgSOBE4EjgSOBI4ERQSExIUEjgRFBITEhQSExI4EjgROBIUEjcSOBI4EgAFJgABKUkSAA0FAAAAAAAAAAA=', + 'bulb' : 'JgBYAAABK5AUERQ2FBEVERQRFBEVERQRFBEVNRQ2FDYUNRU1FDYUNhQRFDYUNRURFBEUEhQRFBEUNhQRFREUNhQ1FDYUNhQ2FAAFIwABKkgVAAxOAAErRxUADQU=', + 'sun' : 'JgBQAAABLI8VERQ2FBEUERURFBEUEhQRFBEUNhQ2FDYUNRU1FTUUNhQSFDUUEhQ2FBEUERURFBEUNhQSFDUUEhQ2FDUVNRQ2FAAFJQABK0cVAA0FAAAAAAAAAAA=', + 'cold' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ1FTUUEhQRFBEUEhQRFBIUERQRFDYUNhQ2FDYUNRQ2FAAFJAABK0cVAA0FAAAAAAAAAAA=', + 'eve_dark' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUERQSFDUUEhQRFBIUNRQSFDUUNhQSFDUUNhQ2FAAFIwABLEYVAA0FAAAAAAAAAAA=', + 'eve_fade' : 'JgBIAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ1FDYUNhQRFDYUERQSFBEUEhQRFBEUNhQSEzYUNhQ2FAANBQ==', + 'reading' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNhQ1FDYUEhQ1FBIUERQRFBIUERQSFDUUEhQ1FTUUNhQ2FAAFJAABK0YVAA0FAAAAAAAAAAA=', + 'yoga' : 'JgBYAAABLI8VERQ1FREUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRURFBEUNhQRFBIUERMSExMTNxM2ExMTNxM2EzcTNxM3EwAFJQABKkgTAAxRAAErRxUADQU=', + 'morning' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FDYUERURFDUVERQRFBIUERQRFTUUNhQRFDYUNhQ2FAAFIwABK0cVAA0FAAAAAAAAAAA=', + 'colours' : 'JgBQAAABLI8VERQ2FBEUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRQSFBEUERQ2FDYUERQSFBEUNhQ1FTUUEhQRFDYUNRU1FAAFJAABKkcVAA0FAAAAAAAAAAA=', + 'random' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQSExIUNhQ1EzcTNxM3EzYTNxMTEhMTNxM2ExMTEhMSExMTNxM2ExMTEhM3EzcTNhM3EwAFJQABK0cVAA0FAAAAAAAAAAA=', + 'island' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUNRURFBEUEhQRFBEUEhQ1FREUNhQ1FDYUNhQ2FAAFIwABK0cVAA0FAAAAAAAAAAA=', + 'forest' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FTUUNhQ2FDUVNRQSFBEUNhQRFDYUERQSFBEUNhQ2FBEUNhQRFDYUNhQ1FQAFIwABK0cVAA0FAAAAAAAAAAA=', + 'ocean' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQRFREUNhQ1FTUUNhQ2FDUVNRQ2FBEUEhQ1FTUUEhQRFBEUEhQ1FTUUEhQRFDYUNRU1FAAFJAABK0cVAA0FAAAAAAAAAAA=', + 'fire' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUNRU1FBIUERQRFBIUERQ2FBEUEhQ1FTUUNhQ2FAAFIwABLEYVAA0FAAAAAAAAAAA=', + 'love' : 'JgBQAAABL5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FDYUNhQ2FDUVNRQSFDUUNhQSFBEUERQSFBEUNhQRFBIUNRQ2FDYUNhQ1FAAFJAABK0cVAA0FAAAAAAAAAAA=', + + # colour commands + 'red' : 'JgBIAAABK5AUERQ2FBEUEhQRFBEVERQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUNhQ1FREUERQSFBEUNhQRFBIUERQ2FDUVNRQ2FAANBQ==', + 'yellow' : 'JgBIAAABLI8UEhQ2FBEUERQSFBEUEhMSFBEUNhQ2FDUUNhQ2FDYUNRQ2FDYUNhQRFBIUERQRFBIUERQSExIUNhQ1FDYUNhQ2FAANBQ==', + 'green' : 'JgBIAAABK5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FDYUNhQ2FDUVNRQSFBEUERQ2FBIUERQRFBIUNRU1FDYUERQ2FDYUNhQ1FQANBQ==', + 'blue' : 'JgBIAAABK5AUERQ2FBEUEhQRFBITEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ2ExIUNhQRFDYUERQSExIUERQ2FBEUNhQSEzYUNhQ2FAANBQ==', + 'saturate' : 'JgBIAAABK5AUERQ2FBEUEhQRFBIUERQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUERQ2FDYUERQSFBEUNhQRFDYUERQSFDUUNhQ2FAANBQ==', + 'desaturate' : 'JgBIAAABLI8VERQ2FBEUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRQ2FDYUNhQ1FREUERQSFBEUERQSFBEUERQ2FDYUNhQ1FQANBQ==', +} + +def cmd(name): + return base64.b64decode(commands[name]) + +class LightController: + def __init__(self): + self.devices = broadlink.discover(timeout=10, max_devices=2) + if self.devices == []: + raise Exception('no devices found') + for device in self.devices: + device.auth() + + def send_cmd(self, name, iterations=5): + "Send a command, repeatedly for reliability" + packet = cmd(name) + for i in range(iterations): + for device in self.devices: + device.send_data(packet) + + def wakey(self): + "Turn on the lights in the morning, try repeatedly for reasons." + print('Turning on the lights. Wakey, wakey!') + for i in range(5): + self.send_cmd('random') + time.sleep(0.3) + self.send_cmd('on') + time.sleep(0.3) diff --git a/fun/idual/idualctl b/fun/idual/idualctl new file mode 100644 index 000000000000..10a85eba0af0 --- /dev/null +++ b/fun/idual/idualctl @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +import idual +import sys + +def help(): + print('Available commands:') + for cmd in idual.commands: + print('- ' + cmd) + sys.exit(0) + +def handle(ctrl, cmd): + if cmd == 'help': + help() + elif cmd == 'wakey': + ctrl.wakey() + sys.exit(0) + elif cmd == 'on': + print('Turning on the lights') + ctrl.send_cmd(cmd) + elif cmd == 'off': + print('Turning off the lights') + ctrl.send_cmd(cmd) + elif cmd in idual.commands: + print('Sending ' + cmd + '-command') + ctrl.send_cmd(cmd) + else: + print('unknown command \'' + cmd + '\'') + sys.exit(1) + +if __name__ == "__main__": + if len(sys.argv) == 1: + help() + + print('Initialising light controller') + ctrl = idual.LightController() + + for cmd in sys.argv[1:]: + handle(ctrl, cmd) diff --git a/fun/idual/setup.py b/fun/idual/setup.py new file mode 100644 index 000000000000..f10c3b86f24e --- /dev/null +++ b/fun/idual/setup.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from setuptools import setup + +setup( + name='idualctl', + version='0.1', + author='Vincent Ambo', + author_email='mail@tazj.in', + url='https://git.tazj.in/about/fun/idual', + packages=['idual'], + scripts = ['idualctl'], + install_requires=['broadlink>=0.13.2'], + include_package_data=True, +) diff --git a/fun/logo/depot-logo.png b/fun/logo/depot-logo.png new file mode 100644 index 000000000000..5d4d0b5c047c --- /dev/null +++ b/fun/logo/depot-logo.png Binary files differdiff --git a/fun/logo/depot-logo.xcf b/fun/logo/depot-logo.xcf new file mode 100644 index 000000000000..3bf6a6713182 --- /dev/null +++ b/fun/logo/depot-logo.xcf Binary files differdiff --git a/fun/quinistry/.gitignore b/fun/quinistry/.gitignore new file mode 100644 index 000000000000..622119552e47 --- /dev/null +++ b/fun/quinistry/.gitignore @@ -0,0 +1,2 @@ +.idea/ +quinistry \ No newline at end of file diff --git a/fun/quinistry/README.md b/fun/quinistry/README.md new file mode 100644 index 000000000000..de197a219ebf --- /dev/null +++ b/fun/quinistry/README.md @@ -0,0 +1,63 @@ +Quinistry +========= + +*A simple Docker registry quine.* + +## What? + +This is an example project for a from-scratch implementation of an HTTP server compatible with the [Docker Registry V2][] +protocol. + +It serves a single image called `quinistry:latest` which is a Docker image that runs quinistry itself, therefore it is a +sort of Docker registry [quine][]. + +The official documentation does not contain enough information to actually implement this protocol (which I assume is +intentional), but a bit of trial&error lead there anyways. I've added comments to parts of the code to clear up things +that may be helpful to other developers in the future. + +## Example + +``` +# Run quinistry: +vincent@urdhva ~/go/src/github.com/tazjin/quinistry (git)-[master] % ./quinistry +2017/03/16 14:11:56 Starting quinistry + +# Pull the quinistry image from itself: +vincent@urdhva ~ % docker pull localhost:8080/quinistry +Using default tag: latest +latest: Pulling from quinistry +7bf1a8b18466: Already exists +Digest: sha256:d5cd4490901ef04b4e28e4ccc03a1d25fe3461200cf4d7166aab86fcd495e22e +Status: Downloaded newer image for localhost:8080/quinistry:latest + +# Quinistry will log: +2017/03/16 14:14:03 Acknowleding V2 API: GET /v2/ +2017/03/16 14:14:03 Serving manifest: GET /v2/quinistry/manifests/latest +2017/03/16 14:14:03 Serving config: GET /v2/quinistry/blobs/sha256:fbb165c48849de16017aa398aa9bb08fd1c00eaa7c150b6c2af37312913db279 + +# Run the downloaded image: +vincent@urdhva ~ % docker run -p 8090:8080 localhost:8080/quinistry +2017/03/16 13:15:18 Starting quinistry + +# And download it again from itself: +vincent@urdhva ~ % docker pull localhost:8090/quinistry +Using default tag: latest +latest: Pulling from quinistry +7bf1a8b18466: Already exists +Digest: sha256:11141d95ddce0bac9ffa32ab1e8bc94748ed923e87762c68858dc41d11a46d3f +Status: Downloaded newer image for localhost:8090/quinistry:latest +``` + +## Building + +Quinistry creates a Docker image that only contains a statically linked `main` binary. As this package makes use of +`net/http`, Go will (by default) link against `libc` for DNS resolution and create a dynamic binary instead. + +To disable this, `build` the project with `-tags netgo`: + +``` +go build -tags netgo +``` + +[Docker Registry V2]: https://docs.docker.com/registry/spec/api/ +[quine]: https://en.wikipedia.org/wiki/Quine_(computing) \ No newline at end of file diff --git a/fun/quinistry/const.go b/fun/quinistry/const.go new file mode 100644 index 000000000000..173fa9efc390 --- /dev/null +++ b/fun/quinistry/const.go @@ -0,0 +1,12 @@ +package main + +// HTTP content types + +const ImageConfigMediaType string = "application/vnd.docker.container.image.v1+json" +const ManifestMediaType string = "application/vnd.docker.distribution.manifest.v2+json" +const LayerMediaType string = "application/vnd.docker.image.rootfs.diff.tar.gzip" + +// HTTP header names + +const ContentType string = "Content-Type" +const DigestHeader string = "Docker-Content-Digest" diff --git a/fun/quinistry/default.nix b/fun/quinistry/default.nix new file mode 100644 index 000000000000..b12c5e6f0c29 --- /dev/null +++ b/fun/quinistry/default.nix @@ -0,0 +1,11 @@ +{ depot, ... }: + +depot.nix.buildGo.program { + name = "quinistry"; + srcs = [ + ./const.go + ./image.go + ./main.go + ./types.go + ]; +} diff --git a/fun/quinistry/image.go b/fun/quinistry/image.go new file mode 100644 index 000000000000..3daeac34d6bb --- /dev/null +++ b/fun/quinistry/image.go @@ -0,0 +1,150 @@ +// The code in this file creates a Docker image layer containing the binary of the +// application itself. + +package main + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/json" + "fmt" + "io/ioutil" + "log" + "os" + "time" +) + +// This function creates a Docker-image digest (i.e. SHA256 hash with +// algorithm-specification prefix) +func Digest(b []byte) string { + hash := sha256.New() + hash.Write(b) + + return fmt.Sprintf("sha256:%x", hash.Sum(nil)) +} + +func GetImageOfCurrentExecutable() Image { + binary := getCurrentBinary() + tarArchive := createTarArchive(&map[string][]byte{ + "/main": binary, + }) + + configJson, configElem := createConfig([]string{Digest(tarArchive)}) + compressed := gzipArchive("Quinistry image", tarArchive) + manifest := createManifest(&configElem, &compressed) + manifestJson, _ := json.Marshal(manifest) + + return Image{ + Layer: compressed, + LayerDigest: Digest(compressed), + Manifest: manifestJson, + ManifestDigest: Digest(manifestJson), + Config: configJson, + ConfigDigest: Digest(configJson), + } + +} + +func getCurrentBinary() []byte { + path, _ := os.Executable() + file, _ := ioutil.ReadFile(path) + return file +} + +func createTarArchive(files *map[string][]byte) []byte { + buf := new(bytes.Buffer) + w := tar.NewWriter(buf) + + for name, file := range *files { + hdr := &tar.Header{ + Name: name, + // Everything is executable \o/ + Mode: 0755, + Size: int64(len(file)), + } + w.WriteHeader(hdr) + w.Write(file) + } + + if err := w.Close(); err != nil { + log.Fatalln(err) + os.Exit(1) + } + + return buf.Bytes() +} + +func gzipArchive(name string, archive []byte) []byte { + buf := new(bytes.Buffer) + w := gzip.NewWriter(buf) + w.Name = name + w.Write(archive) + + if err := w.Close(); err != nil { + log.Fatalln(err) + os.Exit(1) + } + + return buf.Bytes() +} + +func createConfig(layerDigests []string) (configJson []byte, elem Element) { + now := time.Now() + + imageConfig := &ImageConfig{ + Cmd: []string{"/main"}, + Env: []string{"PATH=/"}, + } + + rootFs := RootFs{ + DiffIds: layerDigests, + Type: "layers", + } + + history := []History{ + { + Created: now, + CreatedBy: "Quinistry magic", + }, + } + + config := Config{ + Created: now, + Author: "tazjin", + Architecture: "amd64", + Os: "linux", + Config: imageConfig, + RootFs: rootFs, + History: history, + } + + configJson, _ = json.Marshal(config) + + elem = Element{ + MediaType: ImageConfigMediaType, + Size: len(configJson), + Digest: Digest(configJson), + } + + return +} + +func createManifest(config *Element, layer *[]byte) Manifest { + layers := []Element{ + { + MediaType: LayerMediaType, + Size: len(*layer), + // Layers must contain the digest of the *gzipped* layer. + Digest: Digest(*layer), + }, + } + + return Manifest{ + SchemaVersion: 2, + MediaType: ManifestMediaType, + Config: *config, + Layers: layers, + } +} diff --git a/fun/quinistry/k8s/child.yaml b/fun/quinistry/k8s/child.yaml new file mode 100644 index 000000000000..aa2e318262cd --- /dev/null +++ b/fun/quinistry/k8s/child.yaml @@ -0,0 +1,27 @@ +# This is a child quinistry, running via an image served off the parent. +--- +apiVersion: extensions/v1beta1 +kind: DaemonSet +metadata: + name: quinistry-gen2 + labels: + k8s-app: quinistry + quinistry/role: child + quinistry/generation: '2' +spec: + template: + metadata: + labels: + k8s-app: quinistry + quinistry/role: child + quinistry/generation: '2' + spec: + containers: + - name: quinistry + # Bootstrap via Docker Hub (or any other registry) + image: localhost:5000/quinistry + ports: + - name: registry + containerPort: 8080 + # Incremented hostPort, + hostPort: 5001 diff --git a/fun/quinistry/k8s/parent.yaml b/fun/quinistry/k8s/parent.yaml new file mode 100644 index 000000000000..0db2fe300e1e --- /dev/null +++ b/fun/quinistry/k8s/parent.yaml @@ -0,0 +1,27 @@ +# This is a bootstrapped Quinistry DaemonSet. The initial image +# comes from Docker Hub +--- +apiVersion: extensions/v1beta1 +kind: DaemonSet +metadata: + name: quinistry + labels: + k8s-app: quinistry + quinistry/role: parent + quinistry/generation: '1' +spec: + template: + metadata: + labels: + k8s-app: quinistry + quinistry/role: parent + quinistry/generation: '1' + spec: + containers: + - name: quinistry + # Bootstrap via Docker Hub (or any other registry) + image: tazjin/quinistry + ports: + - name: registry + containerPort: 8080 + hostPort: 5000 diff --git a/fun/quinistry/main.go b/fun/quinistry/main.go new file mode 100644 index 000000000000..50b47418d1a8 --- /dev/null +++ b/fun/quinistry/main.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "log" + "net/http" +) + +func main() { + log.Println("Starting quinistry") + + image := GetImageOfCurrentExecutable() + + layerUri := fmt.Sprintf("/v2/quinistry/blobs/%s", image.LayerDigest) + configUri := fmt.Sprintf("/v2/quinistry/blobs/%s", image.ConfigDigest) + + log.Fatal(http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Acknowledge that we speak V2 + if r.RequestURI == "/v2/" { + logRequest("Acknowleding V2 API", r) + fmt.Fprintln(w) + return + } + + // Serve manifest + if r.RequestURI == "/v2/quinistry/manifests/latest" { + logRequest("Serving manifest", r) + w.Header().Set(ContentType, ManifestMediaType) + w.Header().Add(DigestHeader, image.ManifestDigest) + w.Write(image.Manifest) + return + } + + // Serve actual image layer + if r.RequestURI == layerUri { + logRequest("Serving image layer blob", r) + w.Header().Add(DigestHeader, image.LayerDigest) + w.Write(image.Layer) + return + } + + // Serve image config + if r.RequestURI == configUri { + logRequest("Serving config", r) + w.Header().Set("Content-Type", ImageConfigMediaType) + w.Header().Set(DigestHeader, image.ConfigDigest) + w.Write(image.Config) + return + } + + log.Printf("Unhandled request: %v\n", *r) + }))) +} + +func logRequest(msg string, r *http.Request) { + log.Printf("%s: %s %s\n", msg, r.Method, r.RequestURI) +} diff --git a/fun/quinistry/types.go b/fun/quinistry/types.go new file mode 100644 index 000000000000..498cbac2f2ab --- /dev/null +++ b/fun/quinistry/types.go @@ -0,0 +1,79 @@ +package main + +import "time" + +// This type represents the rootfs-key of the Docker image config. +// It specifies the digest (i.e. usually SHA256 hash) of the tar'ed, but NOT +// compressed image layers. +type RootFs struct { + // The digests of the non-compressed FS layers. + DiffIds []string `json:"diff_ids"` + + // Type should always be set to "layers" + Type string `json:"type"` +} + +// This type represents an entry in the Docker image config's history key. +// Every history element "belongs" to a filesystem layer. +type History struct { + Created time.Time `json:"created"` + CreatedBy string `json:"created_by"` +} + +// This type represents runtime-configuration for the Docker image. +// A lot of possible keys are omitted here, see: +// https://github.com/docker/docker/blob/master/image/spec/v1.2.md#image-json-description +type ImageConfig struct { + Cmd []string + Env []string +} + +// This type represents the Docker image configuration +type Config struct { + Created time.Time `json:"created"` + Author string `json:"author"` + + // Architecture should be "amd64" + Architecture string `json:"architecture"` + + // OS should be "linux" + Os string `json:"os"` + + // Configuration can be set to 'nil', in which case all options have to be + // supplied at container launch time. + Config *ImageConfig `json:"config"` + + // Filesystem layers and history elements have to be in the same order. + RootFs RootFs `json:"rootfs"` + History []History `json:"history"` +} + +// This type represents any manifest +type Element struct { + MediaType string `json:"mediaType"` + Size int `json:"size"` + Digest string `json:"digest"` +} + +// This type represents a Docker image manifest as used by the registry +// protocol V2. +type Manifest struct { + SchemaVersion int `json:"schemaVersion"` // Must be 2 + MediaType string `json:"mediaType"` // Use ManifestMediaType const + Config Element `json:"config"` + Layers []Element `json:"layers"` +} + +// A really "dumb" representation of an image, with its data blob and related +// metadata. +// Note: This is not a registry API type. +type Image struct { + Layer []byte + LayerDigest string + + Manifest []byte + ManifestDigest string + + Config []byte + ConfigDigest string +} diff --git a/fun/streamTVL/default.nix b/fun/streamTVL/default.nix new file mode 100644 index 000000000000..da7c00ce4be5 --- /dev/null +++ b/fun/streamTVL/default.nix @@ -0,0 +1,19 @@ +{ depot, ... }: + +depot.third_party.writeShellScriptBin "start-tvl-stream" '' + env LD_LIBRARY_PATH=/run/opengl-driver/lib/ ${depot.third_party.ffmpeg}/bin/ffmpeg \ + -vsync 0 \ + -hwaccel cuvid \ + -init_hw_device cuda=0 -filter_hw_device 0 \ + -f x11grab \ + -video_size 1920x1080 \ + -framerate 60 \ + -thread_queue_size 256 \ + -i :0.0+0,0 \ + -filter:v "format=nv12,hwupload,scale_npp=w=1280:h=720:interp_algo=lanczos" \ + -c:v h264_nvenc \ + -preset:v llhq \ + -rc:v cbr_ld_hq \ + -an \ + -f flv rtmp://tazj.in:1935/tvl +'' diff --git a/fun/uggc/default.nix b/fun/uggc/default.nix new file mode 100644 index 000000000000..49160071f586 --- /dev/null +++ b/fun/uggc/default.nix @@ -0,0 +1,19 @@ +{ depot, pkgs, ... }@args: + +let + inherit (pkgs) gopkgs; + uggc = depot.nix.buildGo.program { + name = "uggc"; + srcs = [ + ./main.go + ]; + deps = [ + gopkgs."github.com".pkg.browser.gopkg + ]; + }; +in uggc.overrideAttrs(old: { + buildCommand = old.buildCommand + '' + install -D ${./uggc.desktop} $out/share/applications/uggc.desktop + sed "s|@out@|$out|g" -i $out/share/applications/uggc.desktop + ''; +}) diff --git a/fun/uggc/main.go b/fun/uggc/main.go new file mode 100644 index 000000000000..94f8cf092507 --- /dev/null +++ b/fun/uggc/main.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "os" + "strings" + + "github.com/pkg/browser" +) + +func rot13(r rune) rune { + if 'a' <= r && r <= 'm' { + return r + ('n' - 'a') + } else if 'n' <= r && r <= 'z' { + return r - ('n' - 'a') + } + if 'A' <= r && r <= 'M' { + return r + ('N' - 'A') + } else if 'N' <= r && r <= 'Z' { + return r - ('N' - 'A') + } + return r +} + +func main() { + if len(os.Args) == 0 { + fmt.Println("usage: uggc [rot13-encoded URL]") + return + } + urlText := strings.Join(os.Args[1:], " ") + corrected := strings.Map(rot13, urlText) + + err := browser.OpenURL(corrected) + + if err != nil { + fmt.Println("could not launch browser:", err) + } +} diff --git a/fun/uggc/uggc.desktop b/fun/uggc/uggc.desktop new file mode 100644 index 000000000000..c4eeff7f5897 --- /dev/null +++ b/fun/uggc/uggc.desktop @@ -0,0 +1,7 @@ +[Desktop Entry] +Type=Application +Name=Rot13 URL Handler +Exec=@out@/bin/uggc +StartupNotify=false +MimeType=x-scheme-handler/uggc; +MimeType=x-scheme-handler/uggcf; diff --git a/fun/uggc/uggc.reg b/fun/uggc/uggc.reg new file mode 100644 index 000000000000..bfb8e1952f7e --- /dev/null +++ b/fun/uggc/uggc.reg @@ -0,0 +1,23 @@ +Windows Registry Editor Version 5.00 + +[HKEY_CLASSES_ROOT\uggc] +"URL Protocol"="" +@="URL:Rot13 HTTP URL Protocol" + +[HKEY_CLASSES_ROOT\uggcf] +"URL Protocol"="" +@="URL:Rot13 HTTPS URL Protocol" + +[HKEY_CLASSES_ROOT\uggc\shell] + +[HKEY_CLASSES_ROOT\uggcf\shell] + +[HKEY_CLASSES_ROOT\uggc\shell\open] + +[HKEY_CLASSES_ROOT\uggcf\shell\open] + +[HKEY_CLASSES_ROOT\uggc\shell\open\command] +@="\"C:\\Program Files\\uggc\\uggc.exe\" \"%1\"" + +[HKEY_CLASSES_ROOT\uggcf\shell\open\command] +@="\"C:\\Program Files\\uggc\\uggc.exe\" \"%1\"" diff --git a/fun/wallpapers/bio_thehost_1920.webp b/fun/wallpapers/bio_thehost_1920.webp new file mode 100644 index 000000000000..1b904c06fadf --- /dev/null +++ b/fun/wallpapers/bio_thehost_1920.webp Binary files differdiff --git a/fun/wallpapers/busride2_1920.webp b/fun/wallpapers/busride2_1920.webp new file mode 100644 index 000000000000..ad6ec446f661 --- /dev/null +++ b/fun/wallpapers/busride2_1920.webp Binary files differdiff --git a/fun/wallpapers/by_belltowers_2880.webp b/fun/wallpapers/by_belltowers_2880.webp new file mode 100644 index 000000000000..f7477f168914 --- /dev/null +++ b/fun/wallpapers/by_belltowers_2880.webp Binary files differdiff --git a/fun/wallpapers/by_crossing_2560.webp b/fun/wallpapers/by_crossing_2560.webp new file mode 100644 index 000000000000..efa263790b45 --- /dev/null +++ b/fun/wallpapers/by_crossing_2560.webp Binary files differdiff --git a/fun/wallpapers/by_gathering3_2880.webp b/fun/wallpapers/by_gathering3_2880.webp new file mode 100644 index 000000000000..e6b83bdcd430 --- /dev/null +++ b/fun/wallpapers/by_gathering3_2880.webp Binary files differdiff --git a/fun/wallpapers/by_mainservers1_1920.webp b/fun/wallpapers/by_mainservers1_1920.webp new file mode 100644 index 000000000000..f88d237e2b91 --- /dev/null +++ b/fun/wallpapers/by_mainservers1_1920.webp Binary files differdiff --git a/fun/wallpapers/by_warmachines1_2560.webp b/fun/wallpapers/by_warmachines1_2560.webp new file mode 100644 index 000000000000..848bf62bd7ed --- /dev/null +++ b/fun/wallpapers/by_warmachines1_2560.webp Binary files differdiff --git a/fun/wallpapers/by_warmachines3_1920.webp b/fun/wallpapers/by_warmachines3_1920.webp new file mode 100644 index 000000000000..6002ad695a1e --- /dev/null +++ b/fun/wallpapers/by_warmachines3_1920.webp Binary files differdiff --git a/fun/wallpapers/clever-man_2880.webp b/fun/wallpapers/clever-man_2880.webp new file mode 100644 index 000000000000..eb4d3f1bfa33 --- /dev/null +++ b/fun/wallpapers/clever-man_2880.webp Binary files differdiff --git a/fun/wallpapers/december1994_1920.webp b/fun/wallpapers/december1994_1920.webp new file mode 100644 index 000000000000..d2c4da80187c --- /dev/null +++ b/fun/wallpapers/december1994_1920.webp Binary files differdiff --git a/fun/wallpapers/flyby_1920.webp b/fun/wallpapers/flyby_1920.webp new file mode 100644 index 000000000000..8df5b1132e74 --- /dev/null +++ b/fun/wallpapers/flyby_1920.webp Binary files differdiff --git a/fun/wallpapers/gaussfraktarna_1920_badge.webp b/fun/wallpapers/gaussfraktarna_1920_badge.webp new file mode 100644 index 000000000000..3274a3a2d21d --- /dev/null +++ b/fun/wallpapers/gaussfraktarna_1920_badge.webp Binary files differdiff --git a/fun/wallpapers/kraftahq_1920.webp b/fun/wallpapers/kraftahq_1920.webp new file mode 100644 index 000000000000..62a6debf476f --- /dev/null +++ b/fun/wallpapers/kraftahq_1920.webp Binary files differdiff --git a/fun/wallpapers/peripheral2_1920.webp b/fun/wallpapers/peripheral2_1920.webp new file mode 100644 index 000000000000..e454072ac42a --- /dev/null +++ b/fun/wallpapers/peripheral2_1920.webp Binary files differdiff --git a/fun/wallpapers/ship14_1920.webp b/fun/wallpapers/ship14_1920.webp new file mode 100644 index 000000000000..502f5dac903e --- /dev/null +++ b/fun/wallpapers/ship14_1920.webp Binary files differdiff --git a/fun/wallpapers/shipyard_1920.webp b/fun/wallpapers/shipyard_1920.webp new file mode 100644 index 000000000000..3d4115305d10 --- /dev/null +++ b/fun/wallpapers/shipyard_1920.webp Binary files differdiff --git a/fun/wallpapers/specky_1920.webp b/fun/wallpapers/specky_1920.webp new file mode 100644 index 000000000000..b8246618bebc --- /dev/null +++ b/fun/wallpapers/specky_1920.webp Binary files differdiff --git a/fun/wallpapers/summerlove2_1920.webp b/fun/wallpapers/summerlove2_1920.webp new file mode 100644 index 000000000000..d64a1cb867ec --- /dev/null +++ b/fun/wallpapers/summerlove2_1920.webp Binary files differdiff --git a/fun/wallpapers/t50_1920_badge.webp b/fun/wallpapers/t50_1920_badge.webp new file mode 100644 index 000000000000..f8cb6107f30c --- /dev/null +++ b/fun/wallpapers/t50_1920_badge.webp Binary files differdiff --git a/fun/wallpapers/theflood1_1920.webp b/fun/wallpapers/theflood1_1920.webp new file mode 100644 index 000000000000..335efb057172 --- /dev/null +++ b/fun/wallpapers/theflood1_1920.webp Binary files differdiff --git a/fun/wallpapers/thelan_1920.webp b/fun/wallpapers/thelan_1920.webp new file mode 100644 index 000000000000..55e6c22ad212 --- /dev/null +++ b/fun/wallpapers/thelan_1920.webp Binary files differdiff --git a/fun/wallpapers/vadrare_1920_badge.webp b/fun/wallpapers/vadrare_1920_badge.webp new file mode 100644 index 000000000000..887c891da36c --- /dev/null +++ b/fun/wallpapers/vadrare_1920_badge.webp Binary files differdiff --git a/fun/watchblob/README.md b/fun/watchblob/README.md new file mode 100644 index 000000000000..712c96cd95d4 --- /dev/null +++ b/fun/watchblob/README.md @@ -0,0 +1,35 @@ +Watchblob - WatchGuard VPN on Linux +=================================== + +This tiny helper tool makes it possible to use WatchGuard / Firebox / <<whatever +they are actually called>> VPNs that use multi-factor authentication on Linux. + +Rather than using OpenVPN's built-in dynamic challenge/response protocol, WatchGuard +has opted for a separate implementation negotiating credentials outside of the +OpenVPN protocol, which makes it impossible to start those connections solely by +using the `openvpn` CLI and configuration files. + +What this application does has been reverse-engineered from the "WatchGuard Mobile VPN +with SSL" application on OS X. + +I've published a [blog post](https://www.tazj.in/en/1486830338) describing the process +and what is actually going on in this protocol. + +## Installation + +Make sure you have Go installed and `GOPATH` configured, then simply +`go get github.com/tazjin/watchblob/...`. + +## Usage + +Right now the usage is very simple. Make sure you have the correct OpenVPN client +config ready (this is normally supplied by the WatchGuard UI) simply run: + +``` +watchblob vpnserver.somedomain.org username p4ssw0rd +``` + +The server responds with a challenge which is displayed to the user, wait until you +receive the SMS code or whatever and enter it. `watchblob` then completes the +credential negotiation and you may proceed to log in with OpenVPN using your username +and *the OTP token* (**not** your password) as credentials. diff --git a/fun/watchblob/default.nix b/fun/watchblob/default.nix new file mode 100644 index 000000000000..dc32e4d1cefb --- /dev/null +++ b/fun/watchblob/default.nix @@ -0,0 +1,13 @@ +{ depot, ... }: + +depot.nix.buildGo.program { + name = "watchblob"; + srcs = [ + ./main.go + ./urls.go + ]; + + deps = with depot.third_party; [ + gopkgs."golang.org".x.crypto.ssh.terminal.gopkg + ]; +} diff --git a/fun/watchblob/main.go b/fun/watchblob/main.go new file mode 100644 index 000000000000..a7ab65d3d196 --- /dev/null +++ b/fun/watchblob/main.go @@ -0,0 +1,108 @@ +package main + +import ( + "bufio" + "encoding/xml" + "fmt" + "golang.org/x/crypto/ssh/terminal" + "net/http" + "os" + "strings" + "syscall" +) + +// The XML response returned by the WatchGuard server +type Resp struct { + Action string `xml:"action"` + LogonStatus int `xml:"logon_status"` + LogonId int `xml:"logon_id"` + Error string `xml:"errStr"` + Challenge string `xml:"chaStr"` +} + +func main() { + args := os.Args[1:] + + if len(args) != 1 { + fmt.Fprintln(os.Stderr, "Usage: watchblob <vpn-host>") + os.Exit(1) + } + + host := args[0] + + username, password, err := readCredentials() + if err != nil { + fmt.Fprintf(os.Stderr, "Could not read credentials: %v\n", err) + } + + fmt.Printf("Requesting challenge from %s as user %s\n", host, username) + challenge, err := triggerChallengeResponse(&host, &username, &password) + + if err != nil || challenge.LogonStatus != 4 { + fmt.Fprintln(os.Stderr, "Did not receive challenge from server") + fmt.Fprintf(os.Stderr, "Response: %v\nError: %v\n", challenge, err) + os.Exit(1) + } + + token := getToken(&challenge) + err = logon(&host, &challenge, &token) + + if err != nil { + fmt.Fprintf(os.Stderr, "Logon failed: %v\n", err) + os.Exit(1) + } + + fmt.Printf("Login succeeded, you may now (quickly) authenticate OpenVPN with %s as your password\n", token) +} + +func readCredentials() (string, string, error) { + fmt.Printf("Username: ") + reader := bufio.NewReader(os.Stdin) + username, err := reader.ReadString('\n') + + fmt.Printf("Password: ") + password, err := terminal.ReadPassword(syscall.Stdin) + fmt.Println() + + // If an error occured, I don't care about which one it is. + return strings.TrimSpace(username), strings.TrimSpace(string(password)), err +} + +func triggerChallengeResponse(host *string, username *string, password *string) (r Resp, err error) { + return request(templateUrl(host, templateChallengeTriggerUri(username, password))) +} + +func getToken(challenge *Resp) string { + fmt.Println(challenge.Challenge) + + reader := bufio.NewReader(os.Stdin) + token, _ := reader.ReadString('\n') + + return strings.TrimSpace(token) +} + +func logon(host *string, challenge *Resp, token *string) (err error) { + resp, err := request(templateUrl(host, templateResponseUri(challenge.LogonId, token))) + if err != nil { + return + } + + if resp.LogonStatus != 1 { + err = fmt.Errorf("Challenge/response authentication failed: %v", resp) + } + + return +} + +func request(url string) (r Resp, err error) { + resp, err := http.Get(url) + if err != nil { + return + } + + defer resp.Body.Close() + decoder := xml.NewDecoder(resp.Body) + + err = decoder.Decode(&r) + return +} diff --git a/fun/watchblob/main_test.go b/fun/watchblob/main_test.go new file mode 100644 index 000000000000..1af52d0cd4eb --- /dev/null +++ b/fun/watchblob/main_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "encoding/xml" + "reflect" + "testing" +) + +func TestUnmarshalChallengeRespones(t *testing.T) { + var testXml string = ` +<?xml version="1.0" encoding="UTF-8"?> +<resp> + <action>sslvpn_logon</action> + <logon_status>4</logon_status> + <auth-domain-list> + <auth-domain> + <name>RADIUS</name> + </auth-domain> + </auth-domain-list> + <logon_id>441</logon_id> + <chaStr>Enter Your 6 Digit Passcode </chaStr> +</resp>` + + var r Resp + xml.Unmarshal([]byte(testXml), &r) + + expected := Resp{ + Action: "sslvpn_logon", + LogonStatus: 4, + LogonId: 441, + Challenge: "Enter Your 6 Digit Passcode ", + } + + assertEqual(t, expected, r) +} + +func TestUnmarshalLoginError(t *testing.T) { + var testXml string = ` +<?xml version="1.0" encoding="UTF-8"?> +<resp> + <action>sslvpn_logon</action> + <logon_status>2</logon_status> + <auth-domain-list> + <auth-domain> + <name>RADIUS</name> + </auth-domain> + </auth-domain-list> + <errStr>501</errStr> +</resp>` + + var r Resp + xml.Unmarshal([]byte(testXml), &r) + + expected := Resp{ + Action: "sslvpn_logon", + LogonStatus: 2, + Error: "501", + } + + assertEqual(t, expected, r) +} + +func TestUnmarshalLoginSuccess(t *testing.T) { + var testXml string = ` +<?xml version="1.0" encoding="UTF-8"?> +<resp> + <action>sslvpn_logon</action> + <logon_status>1</logon_status> + <auth-domain-list> + <auth-domain> + <name>RADIUS</name> + </auth-domain> + </auth-domain-list> +</resp> +` + var r Resp + xml.Unmarshal([]byte(testXml), &r) + + expected := Resp{ + Action: "sslvpn_logon", + LogonStatus: 1, + } + + assertEqual(t, expected, r) +} + +func assertEqual(t *testing.T, expected interface{}, result interface{}) { + if !reflect.DeepEqual(expected, result) { + t.Errorf( + "Unmarshaled values did not match.\nExpected: %v\nResult: %v\n", + expected, result, + ) + + t.Fail() + } +} diff --git a/fun/watchblob/urls.go b/fun/watchblob/urls.go new file mode 100644 index 000000000000..37f65e0faef4 --- /dev/null +++ b/fun/watchblob/urls.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "net/url" + "strconv" +) + +const urlFormat string = "https://%s%s" +const uriFormat = "/?%s" + +func templateChallengeTriggerUri(username *string, password *string) string { + v := url.Values{} + v.Set("action", "sslvpn_logon") + v.Set("style", "fw_logon_progress.xsl") + v.Set("fw_logon_type", "logon") + v.Set("fw_domain", "Firebox-DB") + v.Set("fw_username", *username) + v.Set("fw_password", *password) + + return fmt.Sprintf(uriFormat, v.Encode()) +} + +func templateResponseUri(logonId int, token *string) string { + v := url.Values{} + v.Set("action", "sslvpn_logon") + v.Set("style", "fw_logon_progress.xsl") + v.Set("fw_logon_type", "response") + v.Set("response", *token) + v.Set("fw_logon_id", strconv.Itoa(logonId)) + + return fmt.Sprintf(uriFormat, v.Encode()) +} + +func templateUrl(baseUrl *string, uri string) string { + return fmt.Sprintf(urlFormat, *baseUrl, uri) +} diff --git a/fun/wcl/default.nix b/fun/wcl/default.nix new file mode 100644 index 000000000000..e4d9804c807c --- /dev/null +++ b/fun/wcl/default.nix @@ -0,0 +1,14 @@ +{ depot, ... }: + +depot.nix.buildLisp.program { + name = "wc"; + + srcs = [ + ./wc.lisp + ]; + + deps = with depot.third_party.lisp; [ + unix-opts + iterate + ]; +} diff --git a/fun/wcl/wc.lisp b/fun/wcl/wc.lisp new file mode 100644 index 000000000000..83c7e8c4f1cc --- /dev/null +++ b/fun/wcl/wc.lisp @@ -0,0 +1,34 @@ +(defpackage wc + (:use #:cl #:iterate) + (:export :main)) +(in-package :wc) +(declaim (optimize (speed 3) (safety 0))) + +(defun main () + (let ((filename (cadr (opts:argv))) + (space (char-code #\Space)) + (newline (char-code #\Newline))) + (with-open-file (file-stream filename :element-type '(unsigned-byte 8)) + (iter + (for byte in-stream file-stream using #'read-byte) + (for previous-byte previous byte) + (for is-newline = (eql newline byte)) + + ;; Count each byte + (sum 1 into bytes) + + ;; Count every newline + (counting is-newline into newlines) + + ;; Count every "word", unless the preceding character already + ;; was a space or we are at the beginning of the file. + (when (or (eql space previous-byte) + (eql newline previous-byte) + (not previous-byte)) + (next-iteration)) + + (counting (or is-newline (eql space byte)) + into words) + + (declare (fixnum bytes newlines words)) + (finally (format t " ~A ~A ~A ~A~%" newlines words bytes filename)))))) |