├── .gitignore
├── ActivityPubBotDotNet.sln
├── Client
└── KristoffferStrube.ActivityPubBotDotNet.Client
│ ├── App.razor
│ ├── KristoffferStrube.ActivityPubBotDotNet.Client.csproj
│ ├── MainLayout.razor
│ ├── Pages
│ └── Index.razor
│ ├── Program.cs
│ ├── Properties
│ └── launchSettings.json
│ ├── _Imports.razor
│ └── wwwroot
│ ├── css
│ └── app.css
│ └── index.html
├── LICENSE
├── README.md
└── Server
└── KristofferStrube.ActivityPubBotDotNet.Server
├── .db
└── Here the DB will be generated.txt
├── ActivityPubDbContext.cs
├── KristofferStrube.ActivityPubBotDotNet.Server.csproj
├── Migrations
├── 20221206235626_InitialCreate.Designer.cs
├── 20221206235626_InitialCreate.cs
└── ActivityPubDbContextModelSnapshot.cs
├── Program.cs
├── Properties
└── launchSettings.json
├── Services
├── ActivityPubService.cs
├── IOutboxService.cs
└── RSSFeedOutboxService.cs
├── Users
├── FollowRelation.cs
├── UserInfo.cs
└── UsersApi.cs
├── WebFinger
├── ResourceLink.cs
├── WebFingerApi.cs
└── WebFingerResource.cs
├── appsettings.Development.json
└── appsettings.json
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/ActivityPubBotDotNet.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.0.31903.59
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KristofferStrube.ActivityPubBotDotNet.Server", "Server\KristofferStrube.ActivityPubBotDotNet.Server\KristofferStrube.ActivityPubBotDotNet.Server.csproj", "{A6C9FFC5-5BA4-43CF-8E10-C8A9BB35F1FF}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KristoffferStrube.ActivityPubBotDotNet.Client", "Client\KristoffferStrube.ActivityPubBotDotNet.Client\KristoffferStrube.ActivityPubBotDotNet.Client.csproj", "{ECB1B4AC-00DB-4560-AA99-F6A81E28E93C}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {A6C9FFC5-5BA4-43CF-8E10-C8A9BB35F1FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {A6C9FFC5-5BA4-43CF-8E10-C8A9BB35F1FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {A6C9FFC5-5BA4-43CF-8E10-C8A9BB35F1FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {A6C9FFC5-5BA4-43CF-8E10-C8A9BB35F1FF}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {ECB1B4AC-00DB-4560-AA99-F6A81E28E93C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {ECB1B4AC-00DB-4560-AA99-F6A81E28E93C}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {ECB1B4AC-00DB-4560-AA99-F6A81E28E93C}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {ECB1B4AC-00DB-4560-AA99-F6A81E28E93C}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {85F35453-A54C-4436-A503-74D84D76BB54}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/App.razor:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Not found
8 |
9 | Sorry, there's nothing at this address.
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/KristoffferStrube.ActivityPubBotDotNet.Client.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net7.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/MainLayout.razor:
--------------------------------------------------------------------------------
1 | @inherits LayoutComponentBase
2 |
3 |
4 | @Body
5 |
6 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/Pages/Index.razor:
--------------------------------------------------------------------------------
1 | @page "/"
2 |
3 |
Hello, world!
4 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Components.Web;
2 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
3 | using KristoffferStrube.ActivityPubBotDotNet.Client;
4 |
5 | var builder = WebAssemblyHostBuilder.CreateDefault(args);
6 | builder.RootComponents.Add("#app");
7 | builder.RootComponents.Add("head::after");
8 |
9 | builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
10 |
11 | await builder.Build().RunAsync();
12 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "iisSettings": {
3 | "iisExpress": {
4 | "applicationUrl": "http://localhost:54128",
5 | "sslPort": 44337
6 | }
7 | },
8 | "profiles": {
9 | "http": {
10 | "commandName": "Project",
11 | "dotnetRunMessages": true,
12 | "launchBrowser": true,
13 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
14 | "applicationUrl": "http://localhost:5175",
15 | "environmentVariables": {
16 | "ASPNETCORE_ENVIRONMENT": "Development"
17 | }
18 | },
19 | "https": {
20 | "commandName": "Project",
21 | "dotnetRunMessages": true,
22 | "launchBrowser": true,
23 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
24 | "applicationUrl": "https://localhost:7055;http://localhost:5175",
25 | "environmentVariables": {
26 | "ASPNETCORE_ENVIRONMENT": "Development"
27 | }
28 | },
29 | "IIS Express": {
30 | "commandName": "IISExpress",
31 | "launchBrowser": true,
32 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
33 | "environmentVariables": {
34 | "ASPNETCORE_ENVIRONMENT": "Development"
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/_Imports.razor:
--------------------------------------------------------------------------------
1 | @using System.Net.Http
2 | @using System.Net.Http.Json
3 | @using Microsoft.AspNetCore.Components.Routing
4 | @using Microsoft.AspNetCore.Components.Web
5 | @using Microsoft.AspNetCore.Components.WebAssembly.Http
6 | @using Microsoft.JSInterop
7 | @using KristoffferStrube.ActivityPubBotDotNet.Client
8 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/wwwroot/css/app.css:
--------------------------------------------------------------------------------
1 | h1:focus {
2 | outline: none;
3 | }
4 |
5 | #blazor-error-ui {
6 | background: lightyellow;
7 | bottom: 0;
8 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
9 | display: none;
10 | left: 0;
11 | padding: 0.6rem 1.25rem 0.7rem 1.25rem;
12 | position: fixed;
13 | width: 100%;
14 | z-index: 1000;
15 | }
16 |
17 | #blazor-error-ui .dismiss {
18 | cursor: pointer;
19 | position: absolute;
20 | right: 0.75rem;
21 | top: 0.5rem;
22 | }
23 |
24 | .blazor-error-boundary {
25 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121;
26 | padding: 1rem 1rem 1rem 3.7rem;
27 | color: white;
28 | }
29 |
30 | .blazor-error-boundary::after {
31 | content: "An error has occurred."
32 | }
33 |
--------------------------------------------------------------------------------
/Client/KristoffferStrube.ActivityPubBotDotNet.Client/wwwroot/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | KristoffferStrube.ActivityPubBotDotNet.Client
7 |
8 |
9 |
10 |
12 |
13 |
14 |
15 | Loading...
16 |
17 |
18 | An unhandled error has occurred.
19 |
Reload
20 |
🗙
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Kristoffer Strube
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](/LICENSE)
2 | [](https://github.com/KristofferStrube/ActivityPubBotDotNet/issues)
3 | [](https://github.com/KristofferStrube/ActivityPubBotDotNet/network/members)
4 | [](https://github.com/KristofferStrube/ActivityPubBotDotNet/stargazers)
5 |
6 | # Introduction
7 | An implementation of a [ActivityPub](https://www.w3.org/TR/activitypub/) bot that can communicate with Mastodon servers.
8 |
9 | Try to say *"AcitivityPub Bot Dot Net"* fast three times.
10 |
11 | It is build using Minimal API and EF Core with SQLite. It uses the [KristofferStrube.ActivityStreams](https://www.nuget.org/packages/KristofferStrube.ActivityStreams) NuGet package for strongly typed classes for parsing the payload of endpoints and to send messages to other servers.
12 |
13 | You can see it in action at [https://kristoffer-strube.dk/API/ActivityPub/Users/bot](https://kristoffer-strube.dk/API/ActivityPub/Users/bot) where the bot serves my blog posts from [kristoffer-strube.dk](https://kristoffer-strube.dk) in its [Outbox](https://www.w3.org/TR/activitypub/#outbox) using the `RSSFeedOutboxService`.
14 |
15 | It is build with inspiration from David Fowler's project [TodoApi](https://github.com/davidfowl/TodoApi).
16 |
17 | # Local Development
18 | ## Setup Database
19 | Setup the dotnet tool *dotnet-ef*.
20 | ```bash
21 | dotnet tool install dotnet-ef -g
22 | ```
23 | Create the database by running the following script from the `src/KristofferStrube.ActivityPubBotDotNet.Server/` folder.
24 | ```bash
25 | dotnet ef database update
26 | ```
27 | ## Adding SSH Keys
28 | For the server project you need to add two configuration keys that will contain a RSA key value pair.
29 | These can either be supplied through [User Secrets](https://blog.elmah.io/asp-net-core-not-that-secret-user-secrets-explained/) or by setting the appropriate values in `appsettings.Development.json`. The Keys are:
30 | - `PEM:Public`
31 | - `PEM:Private`
32 | ## Running the Server
33 | Go to the `src/KristofferStrube.ActivityPubBotDotNet.Server/` folder and run.
34 | ```bash
35 | dotnet run
36 | ```
37 |
38 | # Goals
39 | ## Server Interaction Goals
40 | - [x] [Accept](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-accept) [Follow](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-follow) activities sent to [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person).
41 | - [x] Remove subscription when someone [Undo](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-undo) a [Follow](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-follow) activity.
42 | - [x] Persist [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person) information in EF Core.
43 | - [ ] Validate message [signing](https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/).
44 | - [x] Dynamic information of [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person).
45 | - [x] Dynamic WebFinger endpoint.
46 | - [x] Serve [Articles](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-article) of [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person) from RSS feed.
47 | - [x] Serve [Notes](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-note) of [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person) from administrative tool.
48 | - [ ] Send [Create](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-create) Activity message when a new Article is created.
49 | - [ ] Send [Delete](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-delete) Activity message when [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person) information changes.
50 | ## Administration Goals
51 | - [ ] Be able to authenticate the admin somehow.
52 | - [ ] Be able to update a [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person) information.
53 | - [ ] Be able to create new [Notes](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-note)
54 | - [ ] Be able to delete a [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person).
55 | ## Client Goals
56 | - [ ] Show [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person) information if someone hits the API and doesn't request valid `content-type`.
57 | - [ ] Show [Person](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person)'s [Articles](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-article) below Profile information.
58 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/.db/Here the DB will be generated.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KristofferStrube/ActivityPubBotDotNet/ea17ded6a40a0dfe160ebb68a2261dd325e6662c/Server/KristofferStrube.ActivityPubBotDotNet.Server/.db/Here the DB will be generated.txt
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/ActivityPubDbContext.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore;
2 |
3 | namespace KristofferStrube.ActivityPubBotDotNet.Server;
4 |
5 | public class ActivityPubDbContext : DbContext
6 | {
7 | public ActivityPubDbContext(DbContextOptions options) : base(options) { }
8 |
9 | public DbSet Users => Set();
10 | public DbSet FollowRelations => Set();
11 |
12 | protected override void OnModelCreating(ModelBuilder builder)
13 | {
14 | builder.Entity()
15 | .HasKey(u => u.Id);
16 |
17 | builder.Entity()
18 | .HasKey(f => new { f.FollowerId, f.FollowedId });
19 |
20 | builder.Entity()
21 | .HasOne(f => f.Follower)
22 | .WithMany(u => u.Followers)
23 | .HasForeignKey(f => f.FollowerId);
24 |
25 | builder.Entity()
26 | .HasOne(f => f.Followed)
27 | .WithMany(u => u.Following)
28 | .HasForeignKey(f => f.FollowedId);
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/KristofferStrube.ActivityPubBotDotNet.Server.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net7.0
5 | enable
6 | enable
7 | c22923ae-b25a-4923-95cd-a2c1eb3bcc8e
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Migrations/20221206235626_InitialCreate.Designer.cs:
--------------------------------------------------------------------------------
1 | //
2 | using KristofferStrube.ActivityPubBotDotNet.Server;
3 | using Microsoft.EntityFrameworkCore;
4 | using Microsoft.EntityFrameworkCore.Infrastructure;
5 | using Microsoft.EntityFrameworkCore.Migrations;
6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
7 |
8 | #nullable disable
9 |
10 | namespace KristofferStrube.ActivityPubBotDotNet.Server.Migrations
11 | {
12 | [DbContext(typeof(ActivityPubDbContext))]
13 | [Migration("20221206235626_InitialCreate")]
14 | partial class InitialCreate
15 | {
16 | ///
17 | protected override void BuildTargetModel(ModelBuilder modelBuilder)
18 | {
19 | #pragma warning disable 612, 618
20 | modelBuilder.HasAnnotation("ProductVersion", "7.0.0");
21 |
22 | modelBuilder.Entity("KristofferStrube.ActivityPubBotDotNet.Server.FollowRelation", b =>
23 | {
24 | b.Property("FollowerId")
25 | .HasColumnType("TEXT");
26 |
27 | b.Property("FollowedId")
28 | .HasColumnType("TEXT");
29 |
30 | b.HasKey("FollowerId", "FollowedId");
31 |
32 | b.HasIndex("FollowedId");
33 |
34 | b.ToTable("FollowRelations");
35 | });
36 |
37 | modelBuilder.Entity("KristofferStrube.ActivityPubBotDotNet.Server.UserInfo", b =>
38 | {
39 | b.Property("Id")
40 | .HasColumnType("TEXT");
41 |
42 | b.Property("Name")
43 | .IsRequired()
44 | .HasColumnType("TEXT");
45 |
46 | b.HasKey("Id");
47 |
48 | b.ToTable("Users");
49 | });
50 |
51 | modelBuilder.Entity("KristofferStrube.ActivityPubBotDotNet.Server.FollowRelation", b =>
52 | {
53 | b.HasOne("KristofferStrube.ActivityPubBotDotNet.Server.UserInfo", "Followed")
54 | .WithMany("Following")
55 | .HasForeignKey("FollowedId")
56 | .OnDelete(DeleteBehavior.Cascade)
57 | .IsRequired();
58 |
59 | b.HasOne("KristofferStrube.ActivityPubBotDotNet.Server.UserInfo", "Follower")
60 | .WithMany("Followers")
61 | .HasForeignKey("FollowerId")
62 | .OnDelete(DeleteBehavior.Cascade)
63 | .IsRequired();
64 |
65 | b.Navigation("Followed");
66 |
67 | b.Navigation("Follower");
68 | });
69 |
70 | modelBuilder.Entity("KristofferStrube.ActivityPubBotDotNet.Server.UserInfo", b =>
71 | {
72 | b.Navigation("Followers");
73 |
74 | b.Navigation("Following");
75 | });
76 | #pragma warning restore 612, 618
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Migrations/20221206235626_InitialCreate.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore.Migrations;
2 |
3 | #nullable disable
4 |
5 | namespace KristofferStrube.ActivityPubBotDotNet.Server.Migrations
6 | {
7 | ///
8 | public partial class InitialCreate : Migration
9 | {
10 | ///
11 | protected override void Up(MigrationBuilder migrationBuilder)
12 | {
13 | migrationBuilder.CreateTable(
14 | name: "Users",
15 | columns: table => new
16 | {
17 | Id = table.Column(type: "TEXT", nullable: false),
18 | Name = table.Column(type: "TEXT", nullable: false)
19 | },
20 | constraints: table =>
21 | {
22 | table.PrimaryKey("PK_Users", x => x.Id);
23 | });
24 |
25 | migrationBuilder.CreateTable(
26 | name: "FollowRelations",
27 | columns: table => new
28 | {
29 | FollowerId = table.Column(type: "TEXT", nullable: false),
30 | FollowedId = table.Column(type: "TEXT", nullable: false)
31 | },
32 | constraints: table =>
33 | {
34 | table.PrimaryKey("PK_FollowRelations", x => new { x.FollowerId, x.FollowedId });
35 | table.ForeignKey(
36 | name: "FK_FollowRelations_Users_FollowedId",
37 | column: x => x.FollowedId,
38 | principalTable: "Users",
39 | principalColumn: "Id",
40 | onDelete: ReferentialAction.Cascade);
41 | table.ForeignKey(
42 | name: "FK_FollowRelations_Users_FollowerId",
43 | column: x => x.FollowerId,
44 | principalTable: "Users",
45 | principalColumn: "Id",
46 | onDelete: ReferentialAction.Cascade);
47 | });
48 |
49 | migrationBuilder.CreateIndex(
50 | name: "IX_FollowRelations_FollowedId",
51 | table: "FollowRelations",
52 | column: "FollowedId");
53 | }
54 |
55 | ///
56 | protected override void Down(MigrationBuilder migrationBuilder)
57 | {
58 | migrationBuilder.DropTable(
59 | name: "FollowRelations");
60 |
61 | migrationBuilder.DropTable(
62 | name: "Users");
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Migrations/ActivityPubDbContextModelSnapshot.cs:
--------------------------------------------------------------------------------
1 | //
2 | using KristofferStrube.ActivityPubBotDotNet.Server;
3 | using Microsoft.EntityFrameworkCore;
4 | using Microsoft.EntityFrameworkCore.Infrastructure;
5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
6 |
7 | #nullable disable
8 |
9 | namespace KristofferStrube.ActivityPubBotDotNet.Server.Migrations
10 | {
11 | [DbContext(typeof(ActivityPubDbContext))]
12 | partial class ActivityPubDbContextModelSnapshot : ModelSnapshot
13 | {
14 | protected override void BuildModel(ModelBuilder modelBuilder)
15 | {
16 | #pragma warning disable 612, 618
17 | modelBuilder.HasAnnotation("ProductVersion", "7.0.0");
18 |
19 | modelBuilder.Entity("KristofferStrube.ActivityPubBotDotNet.Server.FollowRelation", b =>
20 | {
21 | b.Property("FollowerId")
22 | .HasColumnType("TEXT");
23 |
24 | b.Property("FollowedId")
25 | .HasColumnType("TEXT");
26 |
27 | b.HasKey("FollowerId", "FollowedId");
28 |
29 | b.HasIndex("FollowedId");
30 |
31 | b.ToTable("FollowRelations");
32 | });
33 |
34 | modelBuilder.Entity("KristofferStrube.ActivityPubBotDotNet.Server.UserInfo", b =>
35 | {
36 | b.Property("Id")
37 | .HasColumnType("TEXT");
38 |
39 | b.Property("Name")
40 | .IsRequired()
41 | .HasColumnType("TEXT");
42 |
43 | b.HasKey("Id");
44 |
45 | b.ToTable("Users");
46 | });
47 |
48 | modelBuilder.Entity("KristofferStrube.ActivityPubBotDotNet.Server.FollowRelation", b =>
49 | {
50 | b.HasOne("KristofferStrube.ActivityPubBotDotNet.Server.UserInfo", "Followed")
51 | .WithMany("Following")
52 | .HasForeignKey("FollowedId")
53 | .OnDelete(DeleteBehavior.Cascade)
54 | .IsRequired();
55 |
56 | b.HasOne("KristofferStrube.ActivityPubBotDotNet.Server.UserInfo", "Follower")
57 | .WithMany("Followers")
58 | .HasForeignKey("FollowerId")
59 | .OnDelete(DeleteBehavior.Cascade)
60 | .IsRequired();
61 |
62 | b.Navigation("Followed");
63 |
64 | b.Navigation("Follower");
65 | });
66 |
67 | modelBuilder.Entity("KristofferStrube.ActivityPubBotDotNet.Server.UserInfo", b =>
68 | {
69 | b.Navigation("Followers");
70 |
71 | b.Navigation("Following");
72 | });
73 | #pragma warning restore 612, 618
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Program.cs:
--------------------------------------------------------------------------------
1 | using KristofferStrube.ActivityPubBotDotNet.Server;
2 |
3 | WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
4 |
5 | // Add services to the container.
6 | // Add Swagger
7 | builder.Services.AddEndpointsApiExplorer();
8 | builder.Services.AddSwaggerGen();
9 |
10 | // Add ActivityPubService
11 | builder.Services.AddHttpClient();
12 | builder.Services.AddScoped();
13 | builder.Services.AddScoped(_ => new RSSFeedOutboxService("https://kristoffer-strube.dk/RSS.xml", "bot", builder.Configuration));
14 |
15 | // Configure the database
16 | string connectionString = builder.Configuration.GetConnectionString("Todos") ?? "Data Source=.db/Todos.db";
17 | builder.Services.AddSqlite(connectionString);
18 |
19 | WebApplication app = builder.Build();
20 |
21 | // Configure the HTTP request pipeline.
22 | if (app.Environment.IsDevelopment())
23 | {
24 | app.UseSwagger();
25 | app.UseSwaggerUI();
26 | app.Map("/", () => Results.Redirect("/swagger"));
27 | }
28 |
29 | app.UseHttpsRedirection();
30 |
31 | app.MapUsers();
32 | app.MapWebFingers();
33 |
34 | ActivityPubDbContext dbContext = app.Services.CreateScope().ServiceProvider.GetRequiredService();
35 | if (!dbContext.Users.Any(u => u.Name == "Bot"))
36 | {
37 | dbContext.Add(new UserInfo("Bot", $"{app.Configuration["HostUrls:Server"]}/Users/bot"));
38 | dbContext.SaveChanges();
39 | }
40 |
41 | app.Run();
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:50721",
8 | "sslPort": 44346
9 | }
10 | },
11 | "profiles": {
12 | "http": {
13 | "commandName": "Project",
14 | "dotnetRunMessages": true,
15 | "launchBrowser": true,
16 | "launchUrl": "swagger",
17 | "applicationUrl": "http://localhost:5030",
18 | "environmentVariables": {
19 | "ASPNETCORE_ENVIRONMENT": "Development"
20 | }
21 | },
22 | "https": {
23 | "commandName": "Project",
24 | "dotnetRunMessages": true,
25 | "launchBrowser": true,
26 | "launchUrl": "swagger",
27 | "applicationUrl": "https://localhost:7296;http://localhost:5030",
28 | "environmentVariables": {
29 | "ASPNETCORE_ENVIRONMENT": "Development"
30 | }
31 | },
32 | "IIS Express": {
33 | "commandName": "IISExpress",
34 | "launchBrowser": true,
35 | "launchUrl": "swagger",
36 | "environmentVariables": {
37 | "ASPNETCORE_ENVIRONMENT": "Development"
38 | }
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Services/ActivityPubService.cs:
--------------------------------------------------------------------------------
1 | using KristofferStrube.ActivityStreams;
2 | using System.Globalization;
3 | using System.Net.Http.Headers;
4 | using System.Security.Cryptography;
5 | using System.Text;
6 | using static System.Text.Json.JsonSerializer;
7 |
8 | namespace KristofferStrube.ActivityPubBotDotNet.Server;
9 |
10 | public class ActivityPubService
11 | {
12 | private readonly HttpClient httpClient;
13 | private readonly IConfiguration configuration;
14 |
15 | public ActivityPubService(HttpClient httpClient, IConfiguration configuration)
16 | {
17 | this.httpClient = httpClient;
18 | this.configuration = configuration;
19 | httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/activity+json"));
20 | }
21 |
22 | public async Task PostAsync(IObjectOrLink objectOrLink, Uri requestUri)
23 | {
24 | string serializedBody = Serialize(objectOrLink);
25 |
26 | HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri)
27 | {
28 | Content = new StringContent(serializedBody, mediaType: new MediaTypeHeaderValue("application/activity+json"))
29 | };
30 |
31 | // Specify the 'x-ms-date' header as the current UTC timestamp according to the RFC1123 standard
32 | string date = DateTimeOffset.UtcNow.ToString("r", CultureInfo.InvariantCulture);
33 | // Compute a content hash for the 'x-ms-content-sha256' header.
34 | string contentHash = $"SHA-256={ComputeContentHash(serializedBody)}";
35 |
36 | // Prepare a string to sign.
37 | string stringToSign = $"date: {date}\ndigest: {contentHash}";
38 | // Compute the signature.
39 | string signature = ComputeSignature(stringToSign);
40 | // Concatenate the string, which will be used in the authorization header.
41 | string authorizationHeader = $"keyId=\"https://kristoffer-strube.dk/API/ActivityPub/Users/bot#main-key\",headers=\"date digest\",signature=\"{signature}\"";
42 |
43 | // Add a Date header.
44 | request.Headers.Add("Date", date);
45 | // Add a Digest header.
46 | request.Headers.Add("Digest", contentHash);
47 | // Add a Signature header.
48 | request.Headers.Add("Signature", authorizationHeader);
49 | // ActivityStreams requires this.
50 | request.Headers.Accept.Add(new("application/ld+json"));
51 |
52 | return await httpClient.SendAsync(request);
53 | }
54 |
55 | public async Task GetInboxUriAsync(IObjectOrLink person)
56 | {
57 | if (person is ILink { Href: Uri href })
58 | {
59 | HttpResponseMessage response = await httpClient.GetAsync(href);
60 | if (!response.IsSuccessStatusCode)
61 | {
62 | return null;
63 | }
64 | IObjectOrLink? obj = await response.Content.ReadFromJsonAsync();
65 | if (obj is Person { Inbox.Href: Uri inboxHref })
66 | {
67 | return inboxHref;
68 | }
69 | }
70 | else if (person is Actor actorObject)
71 | {
72 | return actorObject.Inbox?.Href;
73 | }
74 | return null;
75 | }
76 |
77 | public string? GetPersonId(IObjectOrLink? person)
78 | {
79 | if (person is ILink { Href: Uri href })
80 | {
81 | return href.ToString();
82 | }
83 | else if (person is Person)
84 | {
85 | return person.Id;
86 | }
87 | return null;
88 | }
89 |
90 | private string ComputeContentHash(string content)
91 | {
92 | using SHA256 sha256 = SHA256.Create();
93 | byte[] hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(content));
94 | return Convert.ToBase64String(hashedBytes);
95 | }
96 |
97 | private string ComputeSignature(string stringToSign)
98 | {
99 | string privateKey = configuration["PEM:Private"];
100 |
101 | RSA rsa = RSA.Create();
102 | rsa.ImportFromPem(privateKey.ToCharArray());
103 | byte[] bytes = Encoding.ASCII.GetBytes(stringToSign);
104 | byte[] hash = rsa.SignData(bytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
105 | return Convert.ToBase64String(hash);
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Services/IOutboxService.cs:
--------------------------------------------------------------------------------
1 | using KristofferStrube.ActivityStreams;
2 |
3 | namespace KristofferStrube.ActivityPubBotDotNet.Server;
4 |
5 | public interface IOutboxService
6 | {
7 | bool HasOutboxFor(string userId);
8 | IEnumerable GetOutboxItems(string userId);
9 | }
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Services/RSSFeedOutboxService.cs:
--------------------------------------------------------------------------------
1 | using KristofferStrube.ActivityStreams;
2 | using KristofferStrube.ActivityStreams.JsonLD;
3 | using System.ServiceModel.Syndication;
4 | using System.Xml;
5 |
6 | namespace KristofferStrube.ActivityPubBotDotNet.Server;
7 |
8 | public class RSSFeedOutboxService : IOutboxService
9 | {
10 | private readonly string rssFeedUrl;
11 | private readonly string userId;
12 | private readonly IConfiguration configuration;
13 |
14 | public RSSFeedOutboxService(string rssFeedUrl, string userId, IConfiguration configuration)
15 | {
16 | this.rssFeedUrl = rssFeedUrl;
17 | this.userId = userId;
18 | this.configuration = configuration;
19 | }
20 |
21 | public bool HasOutboxFor(string userId) => this.userId == userId;
22 |
23 | public IEnumerable GetOutboxItems(string userId)
24 | {
25 | XmlReader reader = XmlReader.Create(rssFeedUrl);
26 | SyndicationFeed feed = SyndicationFeed.Load(reader);
27 | reader.Close();
28 | return feed.Items.Select(item => new Create()
29 | {
30 | Id = $"{configuration["HostUrls:Server"]}/Users/{userId}/outbox/{item.Id}/activity",
31 | To = new List { new() { Href = new("https://www.w3.org/ns/activitystreams#Public") } },
32 | Object = new List
33 | {
34 | new Article()
35 | {
36 | Id = $"{configuration["HostUrls:Server"]}/Users/{userId}/outbox/{item.Id}",
37 | Content = new List() {
38 | $"""
39 | {item.Title.Text}
40 | {item.Summary.Text}
41 | {(item.Content is TextSyndicationContent { } content ? content.Text : string.Empty)}
42 | """
43 | },
44 | Published = item.PublishDate.DateTime,
45 | To = new List { new() { Href = new("https://www.w3.org/ns/activitystreams#Public") } },
46 | AttributedTo = new List() { new Link() { Href = new($"{configuration["HostUrls:Server"]}/Users/{userId}") } }
47 | }
48 | }
49 | });
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Users/FollowRelation.cs:
--------------------------------------------------------------------------------
1 | namespace KristofferStrube.ActivityPubBotDotNet.Server;
2 |
3 | public record FollowRelation(string FollowerId, string FollowedId)
4 | {
5 | public UserInfo Follower { get; set; }
6 |
7 | public UserInfo Followed { get; set; }
8 | }
9 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Users/UserInfo.cs:
--------------------------------------------------------------------------------
1 | namespace KristofferStrube.ActivityPubBotDotNet.Server;
2 |
3 | public record UserInfo(string Name, string Id)
4 | {
5 | public List Followers { get; set; }
6 | public List Following { get; set; }
7 | }
8 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/Users/UsersApi.cs:
--------------------------------------------------------------------------------
1 | using KristofferStrube.ActivityStreams;
2 | using KristofferStrube.ActivityStreams.JsonLD;
3 | using Microsoft.AspNetCore.Http.HttpResults;
4 | using Microsoft.AspNetCore.Mvc;
5 | using static System.Text.Json.JsonSerializer;
6 |
7 | namespace KristofferStrube.ActivityPubBotDotNet.Server;
8 |
9 | public static class UsersApi
10 | {
11 | public static RouteGroupBuilder MapUsers(this IEndpointRouteBuilder routes)
12 | {
13 | RouteGroupBuilder group = routes.MapGroup("/users");
14 | group.WithTags("Users");
15 |
16 | group.MapGet("/{userId}", Index);
17 | group.MapPost("/{userId}/inbox", Inbox);
18 | group.MapGet("/{userId}/outbox", Outbox);
19 | group.MapGet("/{userId}/followers", Followers);
20 | group.MapGet("/{userId}/following", Following);
21 |
22 | return group;
23 | }
24 |
25 | public static Results, Ok> Index(string userId, IConfiguration configuration, ActivityPubDbContext dbContext)
26 | {
27 | UserInfo? user = dbContext.Users.Find($"{configuration["HostUrls:Server"]}/Users/{userId}");
28 | if (user is null)
29 | {
30 | return TypedResults.BadRequest("User could not be found.");
31 | }
32 |
33 | return TypedResults.Ok((IObject)new Person()
34 | {
35 | Id = $"{configuration["HostUrls:Server"]}/Users/{userId}",
36 | PreferredUsername = user.Name,
37 | Inbox = new Link() { Href = new Uri($"{configuration["HostUrls:Server"]}/Users/{userId}/inbox") },
38 | Outbox = new Link() { Href = new Uri($"{configuration["HostUrls:Server"]}/Users/{userId}/outbox") },
39 | Followers = new Link() { Href = new Uri($"{configuration["HostUrls:Server"]}/Users/{userId}/followers") },
40 | Following = new Link() { Href = new Uri($"{configuration["HostUrls:Server"]}/Users/{userId}/following") },
41 | Published = new DateTime(2022, 11, 27),
42 | Icon = new List {
43 | new() {
44 | Url = new Link[] { new() { Href = new("https://kristoffer-strube.dk/bot.png") } },
45 | MediaType = "image/png",
46 | }
47 | },
48 | Image = new List {
49 | new() {
50 | Url = new Link[] { new() { Href = new("https://kristoffer-strube.dk/bot_header.PNG") } },
51 | MediaType = "image/png",
52 | }
53 | },
54 | Summary = new string[] { "This is a ActivityPub bot written in .NET." },
55 | ExtensionData = new()
56 | {
57 | { "manuallyApprovesFollowers", SerializeToElement(true) },
58 | { "discoverable", SerializeToElement(true) },
59 | {
60 | "publicKey",
61 | SerializeToElement(new
62 | {
63 | id = $"{configuration["HostUrls:Server"]}/Users/{userId}#main-key",
64 | owner = $"{configuration["HostUrls:Server"]}/Users/{userId}",
65 | publicKeyPem = configuration["PEM:Public"]
66 | })
67 | }
68 | }
69 | });
70 | }
71 |
72 | public static async Task, Accepted>> Inbox(string userId, [FromBody] IObject obj, IConfiguration configuration, ActivityPubDbContext dbContext, ActivityPubService activityPub)
73 | {
74 | UserInfo? user = dbContext.Users.Find($"{configuration["HostUrls:Server"]}/Users/{userId}");
75 | if (user is null)
76 | {
77 | return TypedResults.BadRequest("User could not be found.");
78 | }
79 |
80 | switch (obj)
81 | {
82 | case Follow follow:
83 | if (follow.Actor is null)
84 | {
85 | return TypedResults.BadRequest("Follow request had no actor.");
86 | }
87 | if (activityPub.GetPersonId(follow.Object?.First()) is not string objectPersonId)
88 | {
89 | return TypedResults.BadRequest("The Object was not a Link or did not have a id.");
90 | }
91 | if (objectPersonId != $"{configuration["HostUrls:Server"]}/Users/{userId}")
92 | {
93 | return TypedResults.BadRequest("The Object Id did not match the address of this inbox.");
94 | }
95 | Uri? inbox = await activityPub.GetInboxUriAsync(follow.Actor.First());
96 | if (inbox is null)
97 | {
98 | return TypedResults.BadRequest("The User had no inbox specified.");
99 | }
100 |
101 | Accept accept = new Accept()
102 | {
103 | Actor = new List() { new() { Href = new($"{configuration["HostUrls:Server"]}/Users/{userId}") } },
104 | Id = $"{configuration["HostUrls:Server"]}/Activity/{Guid.NewGuid()}",
105 | Object = new List() { follow }
106 | };
107 | HttpResponseMessage response = await activityPub.PostAsync(accept, inbox);
108 |
109 | if (!response.IsSuccessStatusCode)
110 | {
111 | return TypedResults.BadRequest("Could not send Accept message.");
112 | }
113 | if (activityPub.GetPersonId(follow.Actor.First()) is not string followerId)
114 | {
115 | return TypedResults.BadRequest("The Actor was not a Link or did not have a id.");
116 | }
117 |
118 | if (dbContext.FollowRelations.Find(followerId, userId) is not null)
119 | {
120 | return TypedResults.Accepted("Accepted as the Actor already followed the Object.");
121 | }
122 | UserInfo dbUser = dbContext.Users.Find($"{configuration["HostUrls:Server"]}/Users/{userId}")!;
123 | UserInfo? dbFollower = dbContext.Users.Find(followerId);
124 | if (dbFollower is null)
125 | {
126 | dbFollower = new("Some Follower", followerId);
127 | dbContext.Add(dbFollower);
128 | }
129 | dbContext.Add(new FollowRelation(dbFollower.Id, dbUser.Id));
130 | dbContext.SaveChanges();
131 |
132 | return TypedResults.Accepted("Accepted");
133 | case Undo undo:
134 | switch (undo.Object?.First())
135 | {
136 | case Follow follow:
137 | if (activityPub.GetPersonId(follow.Actor?.First()) is not string actorId || follow.Object?.First() is not ILink { Href: Uri objectUri })
138 | {
139 | return TypedResults.BadRequest($"Could not Undo Follow either because the actor was not a Link or did not have an id or because the Object was not a Link.");
140 | }
141 | FollowRelation? followRelation = dbContext.FollowRelations.Find(actorId, objectUri.ToString());
142 | if (followRelation is null)
143 | {
144 | return TypedResults.BadRequest($"Could not Undo Follow because the Actor was not following the Object.");
145 | }
146 | dbContext.FollowRelations.Remove(followRelation);
147 | dbContext.SaveChanges();
148 | return TypedResults.Accepted("Accepted");
149 | default:
150 | return TypedResults.BadRequest(Serialize(undo.Object));
151 | }
152 | default:
153 | return TypedResults.BadRequest("The Object type was not supported.");
154 | }
155 | }
156 |
157 | public static Results, Ok> Outbox(string userId, IConfiguration configuration, ActivityPubDbContext dbContext, IOutboxService outboxService)
158 | {
159 | UserInfo? user = dbContext.Users.Find($"{configuration["HostUrls:Server"]}/Users/{userId}");
160 | if (user is null)
161 | {
162 | return TypedResults.BadRequest("User could not be found.");
163 | }
164 |
165 | if (!outboxService.HasOutboxFor(userId))
166 | {
167 | return TypedResults.BadRequest("Did not have data for outbox of User.");
168 | }
169 |
170 | var outBoxItems = outboxService.GetOutboxItems(userId).ToList();
171 |
172 | IObjectOrLink collection = new OrderedCollection()
173 | {
174 | Id = $"{configuration["HostUrls:Server"]}/Users/{userId}/outbox",
175 | Items = outBoxItems,
176 | TotalItems = (uint)outBoxItems.Count()
177 | };
178 |
179 | return TypedResults.Ok(collection);
180 | }
181 |
182 | public static Results, Ok> Followers(string userId, IConfiguration configuration, ActivityPubDbContext dbContext)
183 | {
184 | UserInfo? user = dbContext.Users.Find($"{configuration["HostUrls:Server"]}/Users/{userId}");
185 | if (user is null)
186 | {
187 | return TypedResults.BadRequest("User could not be found.");
188 | }
189 |
190 | var relations = dbContext.FollowRelations.Where(f => f.FollowedId == $"{configuration["HostUrls:Server"]}/Users/{userId}").ToList();
191 |
192 | IObjectOrLink collection = new Collection()
193 | {
194 | Id = $"{configuration["HostUrls:Server"]}/Users/{userId}/followers",
195 | Items = relations.Select(f => new Link() { Href = new(f.FollowerId) }).ToList(),
196 | TotalItems = (uint)relations.Count()
197 | };
198 | return TypedResults.Ok(collection);
199 | }
200 |
201 | public static Results, Ok> Following(string userId, IConfiguration configuration, ActivityPubDbContext dbContext)
202 | {
203 | UserInfo? user = dbContext.Users.Find($"{configuration["HostUrls:Server"]}/Users/{userId}");
204 | if (user is null)
205 | {
206 | return TypedResults.BadRequest("User could not be found.");
207 | }
208 |
209 | var relations = dbContext.FollowRelations.Where(f => f.FollowerId == $"{configuration["HostUrls:Server"]}/Users/{userId}").ToList();
210 |
211 | IObjectOrLink collection = new Collection()
212 | {
213 | Id = $"{configuration["HostUrls:Server"]}/Users/{userId}/following",
214 | Items = relations.Select(f => new Link() { Href = new(f.FollowedId) }).ToList(),
215 | TotalItems = (uint)relations.Count()
216 | };
217 | return TypedResults.Ok(collection);
218 | }
219 | }
220 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/WebFinger/ResourceLink.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace KristofferStrube.ActivityPubBotDotNet.Server.WebFinger;
4 |
5 | public class ResourceLink
6 | {
7 | [JsonPropertyName("rel")]
8 | public string Rel { get; set; }
9 |
10 | [JsonPropertyName("type")]
11 | public string Type { get; set; }
12 |
13 | [JsonPropertyName("href")]
14 | public Uri Href { get; set; }
15 |
16 | public ResourceLink(string rel, string type, Uri href)
17 | {
18 | Rel = rel;
19 | Type = type;
20 | Href = href;
21 | }
22 | }
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/WebFinger/WebFingerApi.cs:
--------------------------------------------------------------------------------
1 | using KristofferStrube.ActivityPubBotDotNet.Server.WebFinger;
2 | using KristofferStrube.ActivityStreams;
3 | using KristofferStrube.ActivityStreams.JsonLD;
4 | using Microsoft.AspNetCore.Http.HttpResults;
5 | using Microsoft.AspNetCore.Mvc;
6 | using static System.Text.Json.JsonSerializer;
7 |
8 | namespace KristofferStrube.ActivityPubBotDotNet.Server;
9 |
10 | public static class WebFingerApi
11 | {
12 | public static RouteGroupBuilder MapWebFingers(this IEndpointRouteBuilder routes)
13 | {
14 | RouteGroupBuilder group = routes.MapGroup("/webfinger");
15 | group.WithTags("WebFinger");
16 |
17 | group.MapGet("/", Index);
18 |
19 | return group;
20 | }
21 |
22 | public static Results, Ok> Index(string resource, IConfiguration configuration, ActivityPubDbContext dbContext)
23 | {
24 | if (!resource.Contains(':'))
25 | {
26 | return TypedResults.BadRequest("Malformed resource querystring missing ':'.");
27 | }
28 | if (!resource.Split(':')[1].Contains('@'))
29 | {
30 | return TypedResults.BadRequest("Malformed resource querystring missing '@'.");
31 | }
32 |
33 | string userId = resource.Split(":")[1].Split("@")[0];
34 |
35 | UserInfo? user = dbContext.Users.Find($"{configuration["HostUrls:Server"]}/Users/{userId}");
36 | if (user is null)
37 | {
38 | return TypedResults.BadRequest("User could not be found.");
39 | }
40 |
41 | return TypedResults.Ok(new WebFingerResource(resource)
42 | {
43 | Links = new() { new ResourceLink("self", "application/activity+json", new($"{configuration["HostUrls:Server"]}/Users/{userId}")) }
44 | });
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/WebFinger/WebFingerResource.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace KristofferStrube.ActivityPubBotDotNet.Server.WebFinger;
4 |
5 | public class WebFingerResource
6 | {
7 | [JsonPropertyName("subject")]
8 | public string Subject { get; set; }
9 |
10 | [JsonPropertyName("links")]
11 | public List Links { get; set; } = new();
12 |
13 | public WebFingerResource(string subject)
14 | {
15 | Subject = subject;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "HostUrls": {
3 | "Server": "https://localhost:7296",
4 | "Client": "https://localhost:7055"
5 | },
6 | "PEM": {
7 | "Public": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n",
8 | "Private": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----\n"
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Server/KristofferStrube.ActivityPubBotDotNet.Server/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "HostUrls": {
3 | "Server": "",
4 | "Client": ""
5 | }
6 | }
7 |
--------------------------------------------------------------------------------