├── .github ├── CODEOWNERS ├── dependabot.yml └── workflows │ ├── codeql.yml │ ├── dependency-review.yml │ ├── dotnet-release.yml │ └── dotnet.yml ├── .gitignore ├── .idea ├── .gitignore ├── .idea.mastodon-bookmark-sync │ └── .idea │ │ ├── .gitignore │ │ ├── codeStyles │ │ ├── Project.xml │ │ └── codeStyleConfig.xml │ │ ├── indexLayout.xml │ │ ├── inspectionProfiles │ │ └── Project_Default.xml │ │ ├── riderPublish.xml │ │ └── vcs.xml ├── dictionaries │ └── mjorgensen.xml ├── inspectionProfiles │ └── Project_Default.xml ├── mastodon-bookmark-sync.iml ├── modules.xml └── vcs.xml ├── .run └── BookmarkSync.CLI.run.xml ├── LICENSE ├── README.md ├── mastodon-bookmark-sync.sln ├── mastodon-bookmark-sync.sln.DotSettings ├── src ├── BookmarkSync.CLI │ ├── BookmarkSync.CLI.csproj │ ├── Program.cs │ ├── config.Example.yaml │ └── config.yaml ├── BookmarkSync.Core │ ├── BookmarkSync.Core.csproj │ ├── Configuration │ │ └── ConfigManager.cs │ ├── Entities │ │ ├── Account.cs │ │ ├── Bookmark.cs │ │ └── Config │ │ │ ├── App.cs │ │ │ ├── Bookmarking.cs │ │ │ ├── ConfigurationBase.cs │ │ │ └── Instance.cs │ ├── Extensions │ │ ├── ListExtensions.cs │ │ └── StringExtensions.cs │ ├── GlobalUsings.cs │ ├── Interfaces │ │ └── IBookmarkingService.cs │ ├── Json │ │ └── SnakeCaseContractResolver.cs │ ├── Meta.cs │ └── Utilities │ │ ├── HtmlUtilities.cs │ │ └── UriUtilities.cs └── BookmarkSync.Infrastructure │ ├── BookmarkSync.Infrastructure.csproj │ ├── GlobalUsings.cs │ └── Services │ ├── Bookmarking │ ├── BookmarkSyncService.cs │ ├── BookmarkingService.cs │ ├── Briefkasten │ │ └── BriefkastenBookmarkingService.cs │ ├── LinkAce │ │ ├── LinkAceBookmarkingService.cs │ │ └── LinkAceEntites.cs │ ├── Linkding │ │ └── LinkdingBookmarkingService.cs │ └── Pinboard │ │ └── PinboardBookmarkingService.cs │ └── Mastodon │ └── MastodonService.cs └── tests ├── BookmarkSync.Core.Tests ├── BookmarkSync.Core.Tests.csproj ├── Configuration │ └── ConfigManagerTests.cs ├── Entities │ ├── AccountTests.cs │ ├── BookmarkTests.cs │ └── Config │ │ ├── AppTests.cs │ │ ├── BookmarkingTests.cs │ │ └── InstanceTests.cs ├── Extensions │ ├── ListExtensionsTests.cs │ └── StringExtensionsTests.cs ├── GlobalUsings.cs ├── Helpers │ └── TestHelpers.cs ├── SnakeCaseContractResolverTests.cs └── Utilities │ ├── HtmlUtilitiesTests.cs │ └── UriUtilitiesTests.cs └── BookmarkSync.Infrastructure.Tests ├── BookmarkSync.Infrastructure.Tests.csproj ├── GlobalUsings.cs └── Services ├── BookmarkingServiceTests.cs ├── Briefkasten └── BriefkastenBookmarkingServiceTests.cs ├── LinkAce └── LinkAceBookmarkingServiceTests.cs ├── Linkding └── LinkdingBookmarkingServiceTests.cs ├── Mastodon └── MastodonServiceTests.cs └── Pinboard └── PinboardBookmarkingServiceTests.cs /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @prplecake 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "nuget" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | ignore: 13 | - dependency-name: "CiT.Common" 14 | - package-ecosystem: "github-actions" # See documentation for possible values 15 | directory: "/" # Location of package manifests 16 | schedule: 17 | interval: "weekly" 18 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ "master" ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ "master" ] 20 | schedule: 21 | - cron: '38 13 * * 1' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | packages: read 32 | 33 | strategy: 34 | fail-fast: false 35 | matrix: 36 | language: [ 'csharp' ] 37 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 38 | # Use only 'java' to analyze code written in Java, Kotlin or both 39 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both 40 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 41 | 42 | steps: 43 | - name: Checkout repository 44 | uses: actions/checkout@v4 45 | with: 46 | fetch-depth: 0 47 | 48 | # Initializes the CodeQL tools for scanning. 49 | - name: Initialize CodeQL 50 | uses: github/codeql-action/init@v3 51 | with: 52 | languages: ${{ matrix.language }} 53 | # If you wish to specify custom queries, you can do so here or in a config file. 54 | # By default, queries listed here will override any specified in a config file. 55 | # Prefix the list here with "+" to use these queries and those in the config file. 56 | 57 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 58 | # queries: security-extended,security-and-quality 59 | 60 | 61 | # ℹ️ Command-line programs to run using the OS shell. 62 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 63 | 64 | # If the Autobuild fails above, remove it and uncomment the following three lines. 65 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 66 | 67 | - name: Build 68 | run: | 69 | dotnet nuget add source --username prplecake --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/CompostInTraining/index.json" 70 | dotnet build 71 | 72 | 73 | - name: Perform CodeQL Analysis 74 | uses: github/codeql-action/analyze@v3 75 | with: 76 | category: "/language:${{matrix.language}}" 77 | -------------------------------------------------------------------------------- /.github/workflows/dependency-review.yml: -------------------------------------------------------------------------------- 1 | # Dependency Review Action 2 | # 3 | # This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. 4 | # 5 | # Source repository: https://github.com/actions/dependency-review-action 6 | # Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement 7 | name: 'Dependency Review' 8 | on: [pull_request] 9 | 10 | permissions: 11 | contents: read 12 | 13 | jobs: 14 | dependency-review: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: 'Checkout Repository' 18 | uses: actions/checkout@v4 19 | - name: 'Dependency Review' 20 | uses: actions/dependency-review-action@v4 21 | -------------------------------------------------------------------------------- /.github/workflows/dotnet-release.yml: -------------------------------------------------------------------------------- 1 | name: .NET Release 2 | 3 | on: 4 | release: 5 | types: [ published ] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | with: 14 | fetch-depth: 0 15 | - uses: actions/cache@v4 16 | with: 17 | path: ~/.nuget/packages 18 | key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }} 19 | restore-keys: | 20 | ${{ runner.os }}-nuget- 21 | - name: Setup .NET 22 | uses: actions/setup-dotnet@v4 23 | with: 24 | dotnet-version: 8.0.x 25 | - name: Restore dependencies 26 | run: | 27 | dotnet nuget add source --username prplecake --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/CompostInTraining/index.json" 28 | dotnet restore 29 | - name: Build 30 | run: dotnet build --no-restore 31 | - name: Test 32 | run: dotnet test --no-build --verbosity normal --logger "trx" --results-directory "./TestResults" /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:Exclude="[BookmarkSync.*.Tests?]*" 33 | - uses: dorny/test-reporter@v2 34 | if: always() 35 | with: 36 | name: .NET Test Results 37 | path: TestResults/*.trx 38 | reporter: dotnet-trx 39 | - name: Upload coverage reports to Codecov 40 | uses: codecov/codecov-action@v5 41 | env: 42 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 43 | - run: dotnet run --project src/BookmarkSync.CLI/BookmarkSync.CLI.csproj -- version 44 | 45 | 46 | publish: 47 | env: 48 | ZipFile: mastodon-bookmark-sync-${{ github.ref_name }}.zip 49 | strategy: 50 | matrix: 51 | rid: [ 52 | linux-x64, linux-arm64, 53 | win-x64, osx-x64, 54 | ] 55 | runs-on: ubuntu-latest 56 | name: publish-${{matrix.rid}} 57 | needs: build 58 | steps: 59 | - uses: actions/checkout@v4 60 | with: 61 | fetch-depth: 0 62 | - uses: actions/cache@v4 63 | with: 64 | path: ~/.nuget/packages 65 | key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }} 66 | restore-keys: | 67 | ${{ runner.os }}-nuget- 68 | - name: Setup .NET 69 | uses: actions/setup-dotnet@v4 70 | with: 71 | dotnet-version: 8.0.x 72 | - name: Add NuGet source 73 | run: dotnet nuget add source --username prplecake --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/CompostInTraining/index.json" 74 | - name: Publish CLI (${{matrix.rid}}) 75 | run: | 76 | dotnet publish src/BookmarkSync.CLI/BookmarkSync.CLI.csproj -c Release -r ${{matrix.rid}} --self-contained -p:PublishSingleFile=true -p:PublishReadyToRun=true 77 | zip -j mastodon-bookmark-sync-${{ github.ref_name }}-${{matrix.rid}}.zip src/BookmarkSync.CLI/bin/Release/net8.0/${{matrix.rid}}/publish/* README.md LICENSE 78 | - name: Release 79 | uses: softprops/action-gh-release@v2 80 | if: startsWith(github.ref, 'refs/tags/') 81 | with: 82 | files: mastodon-bookmark-sync-*.zip 83 | -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: .NET 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | permissions: 10 | checks: write 11 | packages: read 12 | 13 | concurrency: 14 | group: ${{ github.workflow }}-${{ github.ref }} 15 | cancel-in-progress: true 16 | 17 | jobs: 18 | build: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v4 22 | with: 23 | fetch-depth: 0 24 | - uses: actions/cache@v4 25 | with: 26 | path: ~/.nuget/packages 27 | key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }} 28 | restore-keys: | 29 | ${{ runner.os }}-nuget- 30 | - name: Setup .NET 31 | uses: actions/setup-dotnet@v4 32 | with: 33 | dotnet-version: 8.0.x 34 | - name: Restore dependencies 35 | run: | 36 | dotnet nuget add source --username prplecake --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/CompostInTraining/index.json" 37 | dotnet restore 38 | - name: Build 39 | run: dotnet build --no-restore 40 | - name: Test 41 | run: dotnet test --no-build --verbosity normal --logger "trx" --results-directory "./TestResults" /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:Exclude="[BookmarkSync.*.Tests?]*" 42 | - uses: dorny/test-reporter@v2 43 | if: always() 44 | with: 45 | name: .NET Test Results 46 | path: TestResults/*.trx 47 | reporter: dotnet-trx 48 | - name: Upload coverage reports to Codecov 49 | uses: codecov/codecov-action@v5 50 | env: 51 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 52 | - run: dotnet run --project src/BookmarkSync.CLI/BookmarkSync.CLI.csproj -- version 53 | -------------------------------------------------------------------------------- /.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/main/VisualStudio.gitignore 5 | 6 | # Secrets 7 | appsettings.*.json 8 | config.*.yaml 9 | !appsettings.Example.json 10 | !config.Example.yaml 11 | 12 | # User-specific files 13 | *.rsuser 14 | *.suo 15 | *.user 16 | *.userosscache 17 | *.sln.docstates 18 | 19 | # User-specific files (MonoDevelop/Xamarin Studio) 20 | *.userprefs 21 | 22 | # Mono auto generated files 23 | mono_crash.* 24 | 25 | # Build results 26 | [Dd]ebug/ 27 | [Dd]ebugPublic/ 28 | [Rr]elease/ 29 | [Rr]eleases/ 30 | x64/ 31 | x86/ 32 | [Ww][Ii][Nn]32/ 33 | [Aa][Rr][Mm]/ 34 | [Aa][Rr][Mm]64/ 35 | bld/ 36 | [Bb]in/ 37 | [Oo]bj/ 38 | [Ll]og/ 39 | [Ll]ogs/ 40 | 41 | # Visual Studio 2015/2017 cache/options directory 42 | .vs/ 43 | # Uncomment if you have tasks that create the project's static files in wwwroot 44 | #wwwroot/ 45 | 46 | # Visual Studio 2017 auto generated files 47 | Generated\ Files/ 48 | 49 | # MSTest test Results 50 | [Tt]est[Rr]esult*/ 51 | [Bb]uild[Ll]og.* 52 | 53 | # NUnit 54 | *.VisualState.xml 55 | TestResult.xml 56 | nunit-*.xml 57 | 58 | # Build Results of an ATL Project 59 | [Dd]ebugPS/ 60 | [Rr]eleasePS/ 61 | dlldata.c 62 | 63 | # Benchmark Results 64 | BenchmarkDotNet.Artifacts/ 65 | 66 | # .NET Core 67 | project.lock.json 68 | project.fragment.lock.json 69 | artifacts/ 70 | 71 | # ASP.NET Scaffolding 72 | ScaffoldingReadMe.txt 73 | 74 | # StyleCop 75 | StyleCopReport.xml 76 | 77 | # Files built by Visual Studio 78 | *_i.c 79 | *_p.c 80 | *_h.h 81 | *.ilk 82 | *.meta 83 | *.obj 84 | *.iobj 85 | *.pch 86 | *.pdb 87 | *.ipdb 88 | *.pgc 89 | *.pgd 90 | *.rsp 91 | *.sbr 92 | *.tlb 93 | *.tli 94 | *.tlh 95 | *.tmp 96 | *.tmp_proj 97 | *_wpftmp.csproj 98 | *.log 99 | *.tlog 100 | *.vspscc 101 | *.vssscc 102 | .builds 103 | *.pidb 104 | *.svclog 105 | *.scc 106 | 107 | # Chutzpah Test files 108 | _Chutzpah* 109 | 110 | # Visual C++ cache files 111 | ipch/ 112 | *.aps 113 | *.ncb 114 | *.opendb 115 | *.opensdf 116 | *.sdf 117 | *.cachefile 118 | *.VC.db 119 | *.VC.VC.opendb 120 | 121 | # Visual Studio profiler 122 | *.psess 123 | *.vsp 124 | *.vspx 125 | *.sap 126 | 127 | # Visual Studio Trace Files 128 | *.e2e 129 | 130 | # TFS 2012 Local Workspace 131 | $tf/ 132 | 133 | # Guidance Automation Toolkit 134 | *.gpState 135 | 136 | # ReSharper is a .NET coding add-in 137 | _ReSharper*/ 138 | *.[Rr]e[Ss]harper 139 | *.DotSettings.user 140 | 141 | # TeamCity is a build add-in 142 | _TeamCity* 143 | 144 | # DotCover is a Code Coverage Tool 145 | *.dotCover 146 | 147 | # AxoCover is a Code Coverage Tool 148 | .axoCover/* 149 | !.axoCover/settings.json 150 | 151 | # Coverlet is a free, cross platform Code Coverage Tool 152 | coverage*.json 153 | coverage*.xml 154 | coverage*.info 155 | 156 | # Visual Studio code coverage results 157 | *.coverage 158 | *.coveragexml 159 | 160 | # NCrunch 161 | _NCrunch_* 162 | .*crunch*.local.xml 163 | nCrunchTemp_* 164 | 165 | # MightyMoose 166 | *.mm.* 167 | AutoTest.Net/ 168 | 169 | # Web workbench (sass) 170 | .sass-cache/ 171 | 172 | # Installshield output folder 173 | [Ee]xpress/ 174 | 175 | # DocProject is a documentation generator add-in 176 | DocProject/buildhelp/ 177 | DocProject/Help/*.HxT 178 | DocProject/Help/*.HxC 179 | DocProject/Help/*.hhc 180 | DocProject/Help/*.hhk 181 | DocProject/Help/*.hhp 182 | DocProject/Help/Html2 183 | DocProject/Help/html 184 | 185 | # Click-Once directory 186 | publish/ 187 | 188 | # Publish Web Output 189 | *.[Pp]ublish.xml 190 | *.azurePubxml 191 | # Note: Comment the next line if you want to checkin your web deploy settings, 192 | # but database connection strings (with potential passwords) will be unencrypted 193 | *.pubxml 194 | *.publishproj 195 | 196 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 197 | # checkin your Azure Web App publish settings, but sensitive information contained 198 | # in these scripts will be unencrypted 199 | PublishScripts/ 200 | 201 | # NuGet Packages 202 | *.nupkg 203 | # NuGet Symbol Packages 204 | *.snupkg 205 | # The packages folder can be ignored because of Package Restore 206 | **/[Pp]ackages/* 207 | # except build/, which is used as an MSBuild target. 208 | !**/[Pp]ackages/build/ 209 | # Uncomment if necessary however generally it will be regenerated when needed 210 | #!**/[Pp]ackages/repositories.config 211 | # NuGet v3's project.json files produces more ignorable files 212 | *.nuget.props 213 | *.nuget.targets 214 | 215 | # Microsoft Azure Build Output 216 | csx/ 217 | *.build.csdef 218 | 219 | # Microsoft Azure Emulator 220 | ecf/ 221 | rcf/ 222 | 223 | # Windows Store app package directories and files 224 | AppPackages/ 225 | BundleArtifacts/ 226 | Package.StoreAssociation.xml 227 | _pkginfo.txt 228 | *.appx 229 | *.appxbundle 230 | *.appxupload 231 | 232 | # Visual Studio cache files 233 | # files ending in .cache can be ignored 234 | *.[Cc]ache 235 | # but keep track of directories ending in .cache 236 | !?*.[Cc]ache/ 237 | 238 | # Others 239 | ClientBin/ 240 | ~$* 241 | *~ 242 | *.dbmdl 243 | *.dbproj.schemaview 244 | *.jfm 245 | *.pfx 246 | *.publishsettings 247 | orleans.codegen.cs 248 | 249 | # Including strong name files can present a security risk 250 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 251 | #*.snk 252 | 253 | # Since there are multiple workflows, uncomment next line to ignore bower_components 254 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 255 | #bower_components/ 256 | 257 | # RIA/Silverlight projects 258 | Generated_Code/ 259 | 260 | # Backup & report files from converting an old project file 261 | # to a newer Visual Studio version. Backup files are not needed, 262 | # because we have git ;-) 263 | _UpgradeReport_Files/ 264 | Backup*/ 265 | UpgradeLog*.XML 266 | UpgradeLog*.htm 267 | ServiceFabricBackup/ 268 | *.rptproj.bak 269 | 270 | # SQL Server files 271 | *.mdf 272 | *.ldf 273 | *.ndf 274 | 275 | # Business Intelligence projects 276 | *.rdl.data 277 | *.bim.layout 278 | *.bim_*.settings 279 | *.rptproj.rsuser 280 | *- [Bb]ackup.rdl 281 | *- [Bb]ackup ([0-9]).rdl 282 | *- [Bb]ackup ([0-9][0-9]).rdl 283 | 284 | # Microsoft Fakes 285 | FakesAssemblies/ 286 | 287 | # GhostDoc plugin setting file 288 | *.GhostDoc.xml 289 | 290 | # Node.js Tools for Visual Studio 291 | .ntvs_analysis.dat 292 | node_modules/ 293 | 294 | # Visual Studio 6 build log 295 | *.plg 296 | 297 | # Visual Studio 6 workspace options file 298 | *.opt 299 | 300 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 301 | *.vbw 302 | 303 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 304 | *.vbp 305 | 306 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 307 | *.dsw 308 | *.dsp 309 | 310 | # Visual Studio 6 technical files 311 | *.ncb 312 | *.aps 313 | 314 | # Visual Studio LightSwitch build output 315 | **/*.HTMLClient/GeneratedArtifacts 316 | **/*.DesktopClient/GeneratedArtifacts 317 | **/*.DesktopClient/ModelManifest.xml 318 | **/*.Server/GeneratedArtifacts 319 | **/*.Server/ModelManifest.xml 320 | _Pvt_Extensions 321 | 322 | # Paket dependency manager 323 | .paket/paket.exe 324 | paket-files/ 325 | 326 | # FAKE - F# Make 327 | .fake/ 328 | 329 | # CodeRush personal settings 330 | .cr/personal 331 | 332 | # Python Tools for Visual Studio (PTVS) 333 | __pycache__/ 334 | *.pyc 335 | 336 | # Cake - Uncomment if you are using it 337 | # tools/** 338 | # !tools/packages.config 339 | 340 | # Tabs Studio 341 | *.tss 342 | 343 | # Telerik's JustMock configuration file 344 | *.jmconfig 345 | 346 | # BizTalk build output 347 | *.btp.cs 348 | *.btm.cs 349 | *.odx.cs 350 | *.xsd.cs 351 | 352 | # OpenCover UI analysis results 353 | OpenCover/ 354 | 355 | # Azure Stream Analytics local run output 356 | ASALocalRun/ 357 | 358 | # MSBuild Binary and Structured Log 359 | *.binlog 360 | 361 | # NVidia Nsight GPU debugger configuration file 362 | *.nvuser 363 | 364 | # MFractors (Xamarin productivity tool) working folder 365 | .mfractor/ 366 | 367 | # Local History for Visual Studio 368 | .localhistory/ 369 | 370 | # Visual Studio History (VSHistory) files 371 | .vshistory/ 372 | 373 | # BeatPulse healthcheck temp database 374 | healthchecksdb 375 | 376 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 377 | MigrationBackup/ 378 | 379 | # Ionide (cross platform F# VS Code tools) working folder 380 | .ionide/ 381 | 382 | # Fody - auto-generated XML schema 383 | FodyWeavers.xsd 384 | 385 | # VS Code files for those working on multiple tools 386 | .vscode/* 387 | !.vscode/settings.json 388 | !.vscode/tasks.json 389 | !.vscode/launch.json 390 | !.vscode/extensions.json 391 | *.code-workspace 392 | 393 | # Local History for Visual Studio Code 394 | .history/ 395 | 396 | # Windows Installer files from build outputs 397 | *.cab 398 | *.msi 399 | *.msix 400 | *.msm 401 | *.msp 402 | 403 | # JetBrains Rider 404 | *.sln.iml -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/.idea.mastodon-bookmark-sync/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Rider ignored files 5 | /modules.xml 6 | /contentModel.xml 7 | /projectSettingsUpdater.xml 8 | /.idea.mastodon-bookmark-sync.iml 9 | # Editor-based HTTP Client requests 10 | /httpRequests/ 11 | # Datasource local storage ignored files 12 | /dataSources/ 13 | /dataSources.local.xml 14 | -------------------------------------------------------------------------------- /.idea/.idea.mastodon-bookmark-sync/.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 22 | -------------------------------------------------------------------------------- /.idea/.idea.mastodon-bookmark-sync/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/.idea.mastodon-bookmark-sync/.idea/indexLayout.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/.idea.mastodon-bookmark-sync/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 36 | -------------------------------------------------------------------------------- /.idea/.idea.mastodon-bookmark-sync/.idea/riderPublish.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/.idea.mastodon-bookmark-sync/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/dictionaries/mjorgensen.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | bluemonday 5 | fediverse 6 | pinboard 7 | unbookmark 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/mastodon-bookmark-sync.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.run/BookmarkSync.CLI.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public 64 | License. 65 | 66 | "Copyright" also means copyright-like laws that apply to other kinds 67 | of works, such as semiconductor masks. 68 | 69 | "The Program" refers to any copyrightable work licensed under this 70 | License. Each licensee is addressed as "you". "Licensees" and 71 | "recipients" may be individuals or organizations. 72 | 73 | To "modify" a work means to copy from or adapt all or part of the work 74 | in a fashion requiring copyright permission, other than the making of an 75 | exact copy. The resulting work is called a "modified version" of the 76 | earlier work or a work "based on" the earlier work. 77 | 78 | A "covered work" means either the unmodified Program or a work based 79 | on the Program. 80 | 81 | To "propagate" a work means to do anything with it that, without 82 | permission, would make you directly or secondarily liable for 83 | infringement under applicable copyright law, except executing it on a 84 | computer or modifying a private copy. Propagation includes copying, 85 | distribution (with or without modification), making available to the 86 | public, and in some countries other activities as well. 87 | 88 | To "convey" a work means any kind of propagation that enables other 89 | parties to make or receive copies. Mere interaction with a user through 90 | a computer network, with no transfer of a copy, is not conveying. 91 | 92 | An interactive user interface displays "Appropriate Legal Notices" 93 | to the extent that it includes a convenient and prominently visible 94 | feature that (1) displays an appropriate copyright notice, and (2) 95 | tells the user that there is no warranty for the work (except to the 96 | extent that warranties are provided), that licensees may convey the 97 | work under this License, and how to view a copy of this License. If 98 | the interface presents a list of user commands or options, such as a 99 | menu, a prominent item in the list meets this criterion. 100 | 101 | 1. Source Code. 102 | 103 | The "source code" for a work means the preferred form of the work 104 | for making modifications to it. "Object code" means any non-source 105 | form of a work. 106 | 107 | A "Standard Interface" means an interface that either is an official 108 | standard defined by a recognized standards body, or, in the case of 109 | interfaces specified for a particular programming language, one that 110 | is widely used among developers working in that language. 111 | 112 | The "System Libraries" of an executable work include anything, other 113 | than the work as a whole, that (a) is included in the normal form of 114 | packaging a Major Component, but which is not part of that Major 115 | Component, and (b) serves only to enable use of the work with that 116 | Major Component, or to implement a Standard Interface for which an 117 | implementation is available to the public in source code form. A 118 | "Major Component", in this context, means a major essential component 119 | (kernel, window system, and so on) of the specific operating system 120 | (if any) on which the executable work runs, or a compiler used to 121 | produce the work, or an object code interpreter used to run it. 122 | 123 | The "Corresponding Source" for a work in object code form means all 124 | the source code needed to generate, install, and (for an executable 125 | work) run the object code and to modify the work, including scripts to 126 | control those activities. However, it does not include the work's 127 | System Libraries, or general-purpose tools or generally available free 128 | programs which are used unmodified in performing those activities but 129 | which are not part of the work. For example, Corresponding Source 130 | includes interface definition files associated with source files for 131 | the work, and the source code for shared libraries and dynamically 132 | linked subprograms that the work is specifically designed to require, 133 | such as by intimate data communication or control flow between those 134 | subprograms and other parts of the work. 135 | 136 | The Corresponding Source need not include anything that users 137 | can regenerate automatically from other parts of the Corresponding 138 | Source. 139 | 140 | The Corresponding Source for a work in source code form is that 141 | same work. 142 | 143 | 2. Basic Permissions. 144 | 145 | All rights granted under this License are granted for the term of 146 | copyright on the Program, and are irrevocable provided the stated 147 | conditions are met. This License explicitly affirms your unlimited 148 | permission to run the unmodified Program. The output from running a 149 | covered work is covered by this License only if the output, given its 150 | content, constitutes a covered work. This License acknowledges your 151 | rights of fair use or other equivalent, as provided by copyright law. 152 | 153 | You may make, run and propagate covered works that you do not 154 | convey, without conditions so long as your license otherwise remains 155 | in force. You may convey covered works to others for the sole purpose 156 | of having them make modifications exclusively for you, or provide you 157 | with facilities for running those works, provided that you comply with 158 | the terms of this License in conveying all material for which you do 159 | not control copyright. Those thus making or running the covered works 160 | for you must do so exclusively on your behalf, under your direction 161 | and control, on terms that prohibit them from making any copies of 162 | your copyrighted material outside their relationship with you. 163 | 164 | Conveying under any other circumstances is permitted solely under 165 | the conditions stated below. Sublicensing is not allowed; section 10 166 | makes it unnecessary. 167 | 168 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 169 | 170 | No covered work shall be deemed part of an effective technological 171 | measure under any applicable law fulfilling obligations under article 172 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 173 | similar laws prohibiting or restricting circumvention of such 174 | measures. 175 | 176 | When you convey a covered work, you waive any legal power to forbid 177 | circumvention of technological measures to the extent such circumvention 178 | is effected by exercising rights under this License with respect to 179 | the covered work, and you disclaim any intention to limit operation or 180 | modification of the work as a means of enforcing, against the work's 181 | users, your or third parties' legal rights to forbid circumvention of 182 | technological measures. 183 | 184 | 4. Conveying Verbatim Copies. 185 | 186 | You may convey verbatim copies of the Program's source code as you 187 | receive it, in any medium, provided that you conspicuously and 188 | appropriately publish on each copy an appropriate copyright notice; 189 | keep intact all notices stating that this License and any 190 | non-permissive terms added in accord with section 7 apply to the code; 191 | keep intact all notices of the absence of any warranty; and give all 192 | recipients a copy of this License along with the Program. 193 | 194 | You may charge any price or no price for each copy that you convey, 195 | and you may offer support or warranty protection for a fee. 196 | 197 | 5. Conveying Modified Source Versions. 198 | 199 | You may convey a work based on the Program, or the modifications to 200 | produce it from the Program, in the form of source code under the 201 | terms of section 4, provided that you also meet all of these conditions: 202 | 203 | a) The work must carry prominent notices stating that you modified 204 | it, and giving a relevant date. 205 | 206 | b) The work must carry prominent notices stating that it is 207 | released under this License and any conditions added under section 208 | 7. This requirement modifies the requirement in section 4 to 209 | "keep intact all notices". 210 | 211 | c) You must license the entire work, as a whole, under this 212 | License to anyone who comes into possession of a copy. This 213 | License will therefore apply, along with any applicable section 7 214 | additional terms, to the whole of the work, and all its parts, 215 | regardless of how they are packaged. This License gives no 216 | permission to license the work in any other way, but it does not 217 | invalidate such permission if you have separately received it. 218 | 219 | d) If the work has interactive user interfaces, each must display 220 | Appropriate Legal Notices; however, if the Program has interactive 221 | interfaces that do not display Appropriate Legal Notices, your 222 | work need not make them do so. 223 | 224 | A compilation of a covered work with other separate and independent 225 | works, which are not by their nature extensions of the covered work, 226 | and which are not combined with it such as to form a larger program, 227 | in or on a volume of a storage or distribution medium, is called an 228 | "aggregate" if the compilation and its resulting copyright are not 229 | used to limit the access or legal rights of the compilation's users 230 | beyond what the individual works permit. Inclusion of a covered work 231 | in an aggregate does not cause this License to apply to the other 232 | parts of the aggregate. 233 | 234 | 6. Conveying Non-Source Forms. 235 | 236 | You may convey a covered work in object code form under the terms 237 | of sections 4 and 5, provided that you also convey the 238 | machine-readable Corresponding Source under the terms of this License, 239 | in one of these ways: 240 | 241 | a) Convey the object code in, or embodied in, a physical product 242 | (including a physical distribution medium), accompanied by the 243 | Corresponding Source fixed on a durable physical medium 244 | customarily used for software interchange. 245 | 246 | b) Convey the object code in, or embodied in, a physical product 247 | (including a physical distribution medium), accompanied by a 248 | written offer, valid for at least three years and valid for as 249 | long as you offer spare parts or customer support for that product 250 | model, to give anyone who possesses the object code either (1) a 251 | copy of the Corresponding Source for all the software in the 252 | product that is covered by this License, on a durable physical 253 | medium customarily used for software interchange, for a price no 254 | more than your reasonable cost of physically performing this 255 | conveying of source, or (2) access to copy the 256 | Corresponding Source from a network server at no charge. 257 | 258 | c) Convey individual copies of the object code with a copy of the 259 | written offer to provide the Corresponding Source. This 260 | alternative is allowed only occasionally and noncommercially, and 261 | only if you received the object code with such an offer, in accord 262 | with subsection 6b. 263 | 264 | d) Convey the object code by offering access from a designated 265 | place (gratis or for a charge), and offer equivalent access to the 266 | Corresponding Source in the same way through the same place at no 267 | further charge. You need not require recipients to copy the 268 | Corresponding Source along with the object code. If the place to 269 | copy the object code is a network server, the Corresponding Source 270 | may be on a different server (operated by you or a third party) 271 | that supports equivalent copying facilities, provided you maintain 272 | clear directions next to the object code saying where to find the 273 | Corresponding Source. Regardless of what server hosts the 274 | Corresponding Source, you remain obligated to ensure that it is 275 | available for as long as needed to satisfy these requirements. 276 | 277 | e) Convey the object code using peer-to-peer transmission, provided 278 | you inform other peers where the object code and Corresponding 279 | Source of the work are being offered to the general public at no 280 | charge under subsection 6d. 281 | 282 | A separable portion of the object code, whose source code is excluded 283 | from the Corresponding Source as a System Library, need not be 284 | included in conveying the object code work. 285 | 286 | A "User Product" is either (1) a "consumer product", which means any 287 | tangible personal property which is normally used for personal, family, 288 | or household purposes, or (2) anything designed or sold for 289 | incorporation into a dwelling. In determining whether a product is a 290 | consumer product, doubtful cases shall be resolved in favor of coverage. 291 | For a particular product received by a particular user, "normally used" 292 | refers to a typical or common use of that class of product, regardless 293 | of the status of the particular user or of the way in which the 294 | particular user actually uses, or expects or is expected to use, the 295 | product. A product is a consumer product regardless of whether the 296 | product has substantial commercial, industrial or non-consumer uses, 297 | unless such uses represent the only significant mode of use of the 298 | product. 299 | 300 | "Installation Information" for a User Product means any methods, 301 | procedures, authorization keys, or other information required to install 302 | and execute modified versions of a covered work in that User Product 303 | from a modified version of its Corresponding Source. The information 304 | must suffice to ensure that the continued functioning of the modified 305 | object code is in no case prevented or interfered with solely because 306 | modification has been made. 307 | 308 | If you convey an object code work under this section in, or with, or 309 | specifically for use in, a User Product, and the conveying occurs as 310 | part of a transaction in which the right of possession and use of the 311 | User Product is transferred to the recipient in perpetuity or for a 312 | fixed term (regardless of how the transaction is characterized), the 313 | Corresponding Source conveyed under this section must be accompanied 314 | by the Installation Information. But this requirement does not apply 315 | if neither you nor any third party retains the ability to install 316 | modified object code on the User Product (for example, the work has 317 | been installed in ROM). 318 | 319 | The requirement to provide Installation Information does not include a 320 | requirement to continue to provide support service, warranty, or updates 321 | for a work that has been modified or installed by the recipient, or for 322 | the User Product in which it has been modified or installed. Access to 323 | a network may be denied when the modification itself materially and 324 | adversely affects the operation of the network or violates the rules and 325 | protocols for communication across the network. 326 | 327 | Corresponding Source conveyed, and Installation Information provided, 328 | in accord with this section must be in a format that is publicly 329 | documented (and with an implementation available to the public in 330 | source code form), and must require no special password or key for 331 | unpacking, reading or copying. 332 | 333 | 7. Additional Terms. 334 | 335 | "Additional permissions" are terms that supplement the terms of this 336 | License by making exceptions from one or more of its conditions. 337 | Additional permissions that are applicable to the entire Program shall 338 | be treated as though they were included in this License, to the extent 339 | that they are valid under applicable law. If additional permissions 340 | apply only to part of the Program, that part may be used separately 341 | under those permissions, but the entire Program remains governed by 342 | this License without regard to the additional permissions. 343 | 344 | When you convey a copy of a covered work, you may at your option 345 | remove any additional permissions from that copy, or from any part of 346 | it. (Additional permissions may be written to require their own 347 | removal in certain cases when you modify the work.) You may place 348 | additional permissions on material, added by you to a covered work, 349 | for which you have or can give appropriate copyright permission. 350 | 351 | Notwithstanding any other provision of this License, for material you 352 | add to a covered work, you may (if authorized by the copyright holders 353 | of that material) supplement the terms of this License with terms: 354 | 355 | a) Disclaiming warranty or limiting liability differently from the 356 | terms of sections 15 and 16 of this License; or 357 | 358 | b) Requiring preservation of specified reasonable legal notices or 359 | author attributions in that material or in the Appropriate Legal 360 | Notices displayed by works containing it; or 361 | 362 | c) Prohibiting misrepresentation of the origin of that material, or 363 | requiring that modified versions of such material be marked in 364 | reasonable ways as different from the original version; or 365 | 366 | d) Limiting the use for publicity purposes of names of licensors or 367 | authors of the material; or 368 | 369 | e) Declining to grant rights under trademark law for use of some 370 | trade names, trademarks, or service marks; or 371 | 372 | f) Requiring indemnification of licensors and authors of that 373 | material by anyone who conveys the material (or modified versions of 374 | it) with contractual assumptions of liability to the recipient, for 375 | any liability that these contractual assumptions directly impose on 376 | those licensors and authors. 377 | 378 | All other non-permissive additional terms are considered "further 379 | restrictions" within the meaning of section 10. If the Program as you 380 | received it, or any part of it, contains a notice stating that it is 381 | governed by this License along with a term that is a further 382 | restriction, you may remove that term. If a license document contains 383 | a further restriction but permits relicensing or conveying under this 384 | License, you may add to a covered work material governed by the terms 385 | of that license document, provided that the further restriction does 386 | not survive such relicensing or conveying. 387 | 388 | If you add terms to a covered work in accord with this section, you 389 | must place, in the relevant source files, a statement of the 390 | additional terms that apply to those files, or a notice indicating 391 | where to find the applicable terms. 392 | 393 | Additional terms, permissive or non-permissive, may be stated in the 394 | form of a separately written license, or stated as exceptions; 395 | the above requirements apply either way. 396 | 397 | 8. Termination. 398 | 399 | You may not propagate or modify a covered work except as expressly 400 | provided under this License. Any attempt otherwise to propagate or 401 | modify it is void, and will automatically terminate your rights under 402 | this License (including any patent licenses granted under the third 403 | paragraph of section 11). 404 | 405 | However, if you cease all violation of this License, then your 406 | license from a particular copyright holder is reinstated (a) 407 | provisionally, unless and until the copyright holder explicitly and 408 | finally terminates your license, and (b) permanently, if the copyright 409 | holder fails to notify you of the violation by some reasonable means 410 | prior to 60 days after the cessation. 411 | 412 | Moreover, your license from a particular copyright holder is 413 | reinstated permanently if the copyright holder notifies you of the 414 | violation by some reasonable means, this is the first time you have 415 | received notice of violation of this License (for any work) from that 416 | copyright holder, and you cure the violation prior to 30 days after 417 | your receipt of the notice. 418 | 419 | Termination of your rights under this section does not terminate the 420 | licenses of parties who have received copies or rights from you under 421 | this License. If your rights have been terminated and not permanently 422 | reinstated, you do not qualify to receive new licenses for the same 423 | material under section 10. 424 | 425 | 9. Acceptance Not Required for Having Copies. 426 | 427 | You are not required to accept this License in order to receive or 428 | run a copy of the Program. Ancillary propagation of a covered work 429 | occurring solely as a consequence of using peer-to-peer transmission 430 | to receive a copy likewise does not require acceptance. However, 431 | nothing other than this License grants you permission to propagate or 432 | modify any covered work. These actions infringe copyright if you do 433 | not accept this License. Therefore, by modifying or propagating a 434 | covered work, you indicate your acceptance of this License to do so. 435 | 436 | 10. Automatic Licensing of Downstream Recipients. 437 | 438 | Each time you convey a covered work, the recipient automatically 439 | receives a license from the original licensors, to run, modify and 440 | propagate that work, subject to this License. You are not responsible 441 | for enforcing compliance by third parties with this License. 442 | 443 | An "entity transaction" is a transaction transferring control of an 444 | organization, or substantially all assets of one, or subdividing an 445 | organization, or merging organizations. If propagation of a covered 446 | work results from an entity transaction, each party to that 447 | transaction who receives a copy of the work also receives whatever 448 | licenses to the work the party's predecessor in interest had or could 449 | give under the previous paragraph, plus a right to possession of the 450 | Corresponding Source of the work from the predecessor in interest, if 451 | the predecessor has it or can get it with reasonable efforts. 452 | 453 | You may not impose any further restrictions on the exercise of the 454 | rights granted or affirmed under this License. For example, you may 455 | not impose a license fee, royalty, or other charge for exercise of 456 | rights granted under this License, and you may not initiate litigation 457 | (including a cross-claim or counterclaim in a lawsuit) alleging that 458 | any patent claim is infringed by making, using, selling, offering for 459 | sale, or importing the Program or any portion of it. 460 | 461 | 11. Patents. 462 | 463 | A "contributor" is a copyright holder who authorizes use under this 464 | License of the Program or a work on which the Program is based. The 465 | work thus licensed is called the contributor's "contributor version". 466 | 467 | A contributor's "essential patent claims" are all patent claims 468 | owned or controlled by the contributor, whether already acquired or 469 | hereafter acquired, that would be infringed by some manner, permitted 470 | by this License, of making, using, or selling its contributor version, 471 | but do not include claims that would be infringed only as a 472 | consequence of further modification of the contributor version. For 473 | purposes of this definition, "control" includes the right to grant 474 | patent sublicenses in a manner consistent with the requirements of 475 | this License. 476 | 477 | Each contributor grants you a non-exclusive, worldwide, royalty-free 478 | patent license under the contributor's essential patent claims, to 479 | make, use, sell, offer for sale, import and otherwise run, modify and 480 | propagate the contents of its contributor version. 481 | 482 | In the following three paragraphs, a "patent license" is any express 483 | agreement or commitment, however denominated, not to enforce a patent 484 | (such as an express permission to practice a patent or covenant not to 485 | sue for patent infringement). To "grant" such a patent license to a 486 | party means to make such an agreement or commitment not to enforce a 487 | patent against the party. 488 | 489 | If you convey a covered work, knowingly relying on a patent license, 490 | and the Corresponding Source of the work is not available for anyone 491 | to copy, free of charge and under the terms of this License, through a 492 | publicly available network server or other readily accessible means, 493 | then you must either (1) cause the Corresponding Source to be so 494 | available, or (2) arrange to deprive yourself of the benefit of the 495 | patent license for this particular work, or (3) arrange, in a manner 496 | consistent with the requirements of this License, to extend the patent 497 | license to downstream recipients. "Knowingly relying" means you have 498 | actual knowledge that, but for the patent license, your conveying the 499 | covered work in a country, or your recipient's use of the covered work 500 | in a country, would infringe one or more identifiable patents in that 501 | country that you have reason to believe are valid. 502 | 503 | If, pursuant to or in connection with a single transaction or 504 | arrangement, you convey, or propagate by procuring conveyance of, a 505 | covered work, and grant a patent license to some of the parties 506 | receiving the covered work authorizing them to use, propagate, modify 507 | or convey a specific copy of the covered work, then the patent license 508 | you grant is automatically extended to all recipients of the covered 509 | work and works based on it. 510 | 511 | A patent license is "discriminatory" if it does not include within 512 | the scope of its coverage, prohibits the exercise of, or is 513 | conditioned on the non-exercise of one or more of the rights that are 514 | specifically granted under this License. You may not convey a covered 515 | work if you are a party to an arrangement with a third party that is 516 | in the business of distributing software, under which you make payment 517 | to the third party based on the extent of your activity of conveying 518 | the work, and under which the third party grants, to any of the 519 | parties who would receive the covered work from you, a discriminatory 520 | patent license (a) in connection with copies of the covered work 521 | conveyed by you (or copies made from those copies), or (b) primarily 522 | for and in connection with specific products or compilations that 523 | contain the covered work, unless you entered into that arrangement, 524 | or that patent license was granted, prior to 28 March 2007. 525 | 526 | Nothing in this License shall be construed as excluding or limiting 527 | any implied license or other defenses to infringement that may 528 | otherwise be available to you under applicable patent law. 529 | 530 | 12. No Surrender of Others' Freedom. 531 | 532 | If conditions are imposed on you (whether by court order, agreement or 533 | otherwise) that contradict the conditions of this License, they do not 534 | excuse you from the conditions of this License. If you cannot convey a 535 | covered work so as to satisfy simultaneously your obligations under this 536 | License and any other pertinent obligations, then as a consequence you 537 | may not convey it at all. For example, if you agree to terms that 538 | obligate you to collect a royalty for further conveying from those to 539 | whom you convey the Program, the only way you could satisfy both those 540 | terms and this License would be to refrain entirely from conveying the 541 | Program. 542 | 543 | 13. Remote Network Interaction; Use with the GNU General Public License. 544 | 545 | Notwithstanding any other provision of this License, if you modify the 546 | Program, your modified version must prominently offer all users 547 | interacting with it remotely through a computer network (if your version 548 | supports such interaction) an opportunity to receive the Corresponding 549 | Source of your version by providing access to the Corresponding Source 550 | from a network server at no charge, through some standard or customary 551 | means of facilitating copying of software. This Corresponding Source 552 | shall include the Corresponding Source for any work covered by version 3 553 | of the GNU General Public License that is incorporated pursuant to the 554 | following paragraph. 555 | 556 | Notwithstanding any other provision of this License, you have 557 | permission to link or combine any covered work with a work licensed 558 | under version 3 of the GNU General Public License into a single 559 | combined work, and to convey the resulting work. The terms of this 560 | License will continue to apply to the part which is the covered work, 561 | but the work with which it is combined will remain governed by version 562 | 3 of the GNU General Public License. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions 567 | of the GNU Affero General Public License from time to time. Such new 568 | versions will be similar in spirit to the present version, but may 569 | differ in detail to address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU Affero 573 | General Public License "or any later version" applies to it, you have 574 | the option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU Affero General Public License, you may choose any version ever 578 | published by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU Affero General Public License can be used, that 582 | proxy's public statement of acceptance of a version permanently 583 | authorizes you to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 595 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT 596 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 597 | PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE 598 | OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU 599 | ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR 605 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 606 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES 607 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT 608 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES 609 | SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE 610 | WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN 611 | ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Dotnet](https://github.com/prplecake/mastodon-bookmark-sync/actions/workflows/dotnet.yml/badge.svg)](https://github.com/prplecake/mastodon-bookmark-sync/actions/workflows/dotnet.yml) 2 | [![Dotnet Release](https://github.com/prplecake/mastodon-bookmark-sync/actions/workflows/dotnet-release.yml/badge.svg)](https://github.com/prplecake/mastodon-bookmark-sync/actions/workflows/dotnet-release.yml) 3 | [![codecov](https://codecov.io/gh/prplecake/mastodon-bookmark-sync/graph/badge.svg?token=GBz8QvtznT)](https://codecov.io/gh/prplecake/mastodon-bookmark-sync) 4 | [![GitHub release (latest SemVer including pre-releases)](https://img.shields.io/github/v/release/prplecake/mastodon-bookmark-sync?include_prereleases)](https://github.com/prplecake/mastodon-bookmark-sync/releases/latest) 5 | 6 | # mastodon-bookmark-sync 7 | 8 | mastodon-bookmark-sync is a command-line utility to synchronize Mastodon 9 | bookmarks with LinkAce or other bookmarking services. 10 | 11 | mastodon-bookmark-sync supports multiple Mastodon accounts. 12 | 13 | **Supported bookmarking services:** 14 | 15 | - [Briefkasten] 16 | - [LinkAce] 17 | - [linkding] 18 | - [Pinboard] 19 | 20 | [Briefkasten]:https://github.com/ndom91/briefkasten 21 | [LinkAce]:https://linkace.org/ 22 | [linkding]:https://github.com/sissbruecker/linkding 23 | [Pinboard]:https://pinboard.in/ 24 | 25 | ## getting started 26 | 27 | You probably just want to grab an executable from the [Releases][releases] page. 28 | 29 | [releases]:https://github.com/prplecake/mastodon-bookmark-sync/releases 30 | 31 | Before you can start using mastodon-bookmark-sync, you'll need to configure 32 | it. An example configuration can be found [here][config-blob]. You can also 33 | just copy the example: 34 | 35 | ```shell 36 | cp appsettings.Example.json appsettings.Production.json 37 | vim appsettings.Production.json # don't forget to edit it! 38 | ``` 39 | 40 | You'll need an access token from your Mastodon server. 41 | i.e. `your.instance/settings/applications` 42 | 43 | And you'll need an API token for your bookmarking service of choice. 44 | 45 | See the wiki for [configuration examples][config-examples]. 46 | 47 | [config-examples]:https://github.com/prplecake/mastodon-bookmark-sync/wiki/Configuration-Examples 48 | 49 | Once you've got it configured, just run it. You might want to add it to your 50 | crontab, or your other favorite task scheduler: 51 | 52 | ```text 53 | 0 */6 * * * cd /path/to/mastodon-bookmark-sync; ./mastodon-bookmark-sync 54 | ``` 55 | 56 | [config-blob]:https://github.com/prplecake/mastodon-bookmark-sync/blob/master/BookmarkSync.CLI/appsettings.Example.json 57 | 58 | ## questions 59 | 60 | * [Help! I can't run this on my Mac.](https://github.com/prplecake/mastodon-bookmark-sync/wiki/Questions#help-i-cant-run-this-on-my-mac) 61 | -------------------------------------------------------------------------------- /mastodon-bookmark-sync.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B696875F-E32C-4227-920E-4AFD03B7A5FC}" 4 | ProjectSection(SolutionItems) = preProject 5 | README.md = README.md 6 | .gitignore = .gitignore 7 | .github\workflows\dotnet.yml = .github\workflows\dotnet.yml 8 | .github\workflows\dotnet-release.yml = .github\workflows\dotnet-release.yml 9 | .github\dependabot.yml = .github\dependabot.yml 10 | EndProjectSection 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5EDB0DD2-A23F-410E-9355-B1521E273FF3}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{737ABEA3-2510-4E53-9B5A-A258BE2AF721}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BookmarkSync.CLI", "src\BookmarkSync.CLI\BookmarkSync.CLI.csproj", "{E69D1FC7-D3C7-481F-B12F-E3C907014EE0}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BookmarkSync.Core.Tests", "tests\BookmarkSync.Core.Tests\BookmarkSync.Core.Tests.csproj", "{18CE5B2E-8DED-4B09-87D8-9DB28CA5C16D}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BookmarkSync.Infrastructure.Tests", "tests\BookmarkSync.Infrastructure.Tests\BookmarkSync.Infrastructure.Tests.csproj", "{97E7C240-93D5-4FCA-AEB8-5A2EA6B42062}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BookmarkSync.Core", "src\BookmarkSync.Core\BookmarkSync.Core.csproj", "{857B7598-D226-40F7-807E-D11553DC1FED}" 23 | EndProject 24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BookmarkSync.Infrastructure", "src\BookmarkSync.Infrastructure\BookmarkSync.Infrastructure.csproj", "{C328709A-9063-438D-85B8-909CF14329F0}" 25 | EndProject 26 | Global 27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 28 | Debug|Any CPU = Debug|Any CPU 29 | Release|Any CPU = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 32 | {E69D1FC7-D3C7-481F-B12F-E3C907014EE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {E69D1FC7-D3C7-481F-B12F-E3C907014EE0}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {E69D1FC7-D3C7-481F-B12F-E3C907014EE0}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {E69D1FC7-D3C7-481F-B12F-E3C907014EE0}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {18CE5B2E-8DED-4B09-87D8-9DB28CA5C16D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {18CE5B2E-8DED-4B09-87D8-9DB28CA5C16D}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {18CE5B2E-8DED-4B09-87D8-9DB28CA5C16D}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {18CE5B2E-8DED-4B09-87D8-9DB28CA5C16D}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {97E7C240-93D5-4FCA-AEB8-5A2EA6B42062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {97E7C240-93D5-4FCA-AEB8-5A2EA6B42062}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {97E7C240-93D5-4FCA-AEB8-5A2EA6B42062}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {97E7C240-93D5-4FCA-AEB8-5A2EA6B42062}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {857B7598-D226-40F7-807E-D11553DC1FED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {857B7598-D226-40F7-807E-D11553DC1FED}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {857B7598-D226-40F7-807E-D11553DC1FED}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {857B7598-D226-40F7-807E-D11553DC1FED}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {C328709A-9063-438D-85B8-909CF14329F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {C328709A-9063-438D-85B8-909CF14329F0}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {C328709A-9063-438D-85B8-909CF14329F0}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {C328709A-9063-438D-85B8-909CF14329F0}.Release|Any CPU.Build.0 = Release|Any CPU 52 | EndGlobalSection 53 | GlobalSection(NestedProjects) = preSolution 54 | {E69D1FC7-D3C7-481F-B12F-E3C907014EE0} = {5EDB0DD2-A23F-410E-9355-B1521E273FF3} 55 | {18CE5B2E-8DED-4B09-87D8-9DB28CA5C16D} = {737ABEA3-2510-4E53-9B5A-A258BE2AF721} 56 | {97E7C240-93D5-4FCA-AEB8-5A2EA6B42062} = {737ABEA3-2510-4E53-9B5A-A258BE2AF721} 57 | {857B7598-D226-40F7-807E-D11553DC1FED} = {5EDB0DD2-A23F-410E-9355-B1521E273FF3} 58 | {C328709A-9063-438D-85B8-909CF14329F0} = {5EDB0DD2-A23F-410E-9355-B1521E273FF3} 59 | EndGlobalSection 60 | EndGlobal 61 | -------------------------------------------------------------------------------- /mastodon-bookmark-sync.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True 3 | True 4 | True 5 | True 6 | True 7 | True 8 | -------------------------------------------------------------------------------- /src/BookmarkSync.CLI/BookmarkSync.CLI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | mastodon-bookmark-sync 9 | 2.0.0-alpha 10 | 11 | 12 | 13 | none 14 | 15 | 16 | 17 | 18 | 19 | all 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | Always 39 | 40 | 41 | Always 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/BookmarkSync.CLI/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using BookmarkSync.Core; 3 | using BookmarkSync.Core.Configuration; 4 | using BookmarkSync.Infrastructure.Services.Bookmarking; 5 | using BookmarkSync.Infrastructure.Services.Mastodon; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.Hosting; 9 | using Serilog; 10 | 11 | namespace BookmarkSync.CLI; 12 | 13 | [ExcludeFromCodeCoverage] 14 | public static class Program 15 | { 16 | private static IConfiguration? _configuration; 17 | public static int Main(string[] args) 18 | { 19 | if (args.Contains("version")) 20 | { 21 | Console.WriteLine("{0} {1}", Meta.Name, Meta.Version); 22 | return 0; 23 | } 24 | _configuration = SetupConfiguration(args); 25 | IConfigManager configManager = new ConfigManager(_configuration); 26 | 27 | Log.Logger = new LoggerConfiguration() 28 | .ReadFrom.Configuration(_configuration) 29 | .Enrich.FromLogContext() 30 | .CreateLogger(); 31 | 32 | try 33 | { 34 | Log.Information("Starting host"); 35 | Log.Information("{Name} {Version}", Meta.Name, Meta.Version); 36 | BuildHost(configManager).Run(); 37 | return 0; 38 | } 39 | catch (Exception ex) 40 | { 41 | Log.Fatal(ex, "Host terminated unexpectedly"); 42 | return 1; 43 | } 44 | finally 45 | { 46 | Log.Information("Stopping host"); 47 | // configManager.SaveToFile(); 48 | Log.CloseAndFlush(); 49 | } 50 | } 51 | private static IHost BuildHost(IConfigManager configManager) => 52 | new HostBuilder() 53 | .ConfigureServices(services => 54 | { 55 | services.AddSingleton(configManager); 56 | services.AddHostedService(); 57 | services.AddHttpClient(); 58 | }) 59 | .UseSerilog() 60 | .Build(); 61 | private static IConfiguration SetupConfiguration(string[] args) => new ConfigurationBuilder() 62 | .AddYamlFile("config.yaml", false, true) 63 | .AddYamlFile($"config.{Environment.GetEnvironmentVariable("MBS_ENVIRONMENT") ?? "Production"}.yaml", false, true) 64 | .AddCommandLine(args) 65 | .Build(); 66 | } 67 | -------------------------------------------------------------------------------- /src/BookmarkSync.CLI/config.Example.yaml: -------------------------------------------------------------------------------- 1 | Instances: 2 | - Uri: https://compostintraining.club 3 | AccessToken: 4 | DeleteBookmarks: true 5 | App: 6 | Bookmarking: 7 | Service: "LinkAce" 8 | ApiToken: 9 | LinkAceUri: 10 | IgnoredAccounts: 11 | - one 12 | - two -------------------------------------------------------------------------------- /src/BookmarkSync.CLI/config.yaml: -------------------------------------------------------------------------------- 1 | Serilog: 2 | Using: 3 | - Serilog.Sinks.Console 4 | MinimumLevel: 5 | Default: Information 6 | Override: 7 | Microsoft: Warning 8 | System: Error 9 | WriteTo: 10 | - Name: Console 11 | Args: 12 | theme: "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console" 13 | outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}" 14 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/BookmarkSync.Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | none 11 | 12 | 13 | 14 | 15 | 16 | all 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Configuration/ConfigManager.cs: -------------------------------------------------------------------------------- 1 | using System.Configuration; 2 | using BookmarkSync.Core.Entities.Config; 3 | using BookmarkSync.Core.Extensions; 4 | using Microsoft.Extensions.Configuration; 5 | 6 | namespace BookmarkSync.Core.Configuration; 7 | 8 | public interface IConfigManager 9 | { 10 | App App { get; } 11 | List? Instances { get; } 12 | string GetConfigValue(string key); 13 | void SaveToFile(); 14 | } 15 | public class ConfigManager : IConfigManager 16 | { 17 | private static readonly ILogger _logger = Log.ForContext(); 18 | public ConfigManager( 19 | IConfiguration configuration) 20 | { 21 | Configuration = configuration; 22 | App = Configuration.GetSection("App").Get() ?? throw new InvalidOperationException(); 23 | Instances = Configuration.GetSection("Instances").Get>(); 24 | 25 | if (App.IgnoredAccounts is not null) CleanUpIgnoredAccounts(); 26 | 27 | if (!App.IsValid()) 28 | { 29 | _logger.Error("App configuration is invalid"); 30 | throw new InvalidConfigurationException(); 31 | } 32 | } 33 | private IConfiguration Configuration { get; } 34 | public List? Instances { get; } 35 | public App App { get; } 36 | public string GetConfigValue(string key) 37 | { 38 | _logger.Debug("Running {Method} for key: {Key}", "GetConfigValue", key); 39 | string? value = Configuration[key]; 40 | if (string.IsNullOrWhiteSpace(value)) 41 | { 42 | throw new ConfigurationErrorsException( 43 | $"An invalid key was provided: key: {key}"); 44 | } 45 | return value; 46 | } 47 | public void SaveToFile() 48 | { 49 | Console.WriteLine(Directory.GetCurrentDirectory()); 50 | throw new NotImplementedException(); 51 | } 52 | private void CleanUpIgnoredAccounts() 53 | { 54 | App.IgnoredAccounts = (from account in App.IgnoredAccounts select account.RemoveLeadingAt()).ToList(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Entities/Account.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace BookmarkSync.Core.Entities; 4 | 5 | public class Account 6 | { 7 | [JsonProperty("acct")] public string? Name { get; set; } 8 | public Account(string name) 9 | { 10 | Name = name; 11 | } 12 | public Account() { } 13 | /// 14 | public override string ToString() => Name ?? GetType().Name; 15 | } 16 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Entities/Bookmark.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Utilities; 2 | 3 | namespace BookmarkSync.Core.Entities; 4 | 5 | public class Bookmark 6 | { 7 | public Account? Account { get; set; } 8 | private string? _content; 9 | public string? Content 10 | { 11 | get => _content != null ? HtmlUtilities.ConvertToPlainText(_content) : ""; 12 | set => _content = value; 13 | } 14 | public string? Id { get; set; } 15 | public string? Uri { get; set; } 16 | public string? Visibility { get; set; } 17 | public string[] DefaultTags => 18 | new[] { $"via:@{Account}", "via:mastodon-bookmark-sync"}; 19 | } 20 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Entities/Config/App.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Entities.Config; 2 | 3 | public class App : ConfigurationBase 4 | { 5 | [ConfigRequired] public Bookmarking Bookmarking { get; set; } = null!; 6 | public List? IgnoredAccounts { get; set; } 7 | public DateTime LastSynced { get; set; } 8 | } 9 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Entities/Config/Bookmarking.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Entities.Config; 2 | 3 | public class Bookmarking : ConfigurationBase 4 | { 5 | public string? ApiToken { get; set; } 6 | public string? Service { get; set; } 7 | public string? ApiVersion { get; set; } 8 | } 9 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Entities/Config/ConfigurationBase.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Entities.Config; 2 | 3 | public class ConfigurationBase 4 | { 5 | public bool IsValid() => !this.IsAnyNullOrEmpty(); 6 | } 7 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Entities/Config/Instance.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Entities.Config; 2 | 3 | public class Instance : ConfigurationBase 4 | { 5 | public string? AccessToken { get; set; } 6 | public bool DeleteBookmarks { get; set; } 7 | public string? Uri { get; init; } 8 | /// 9 | public override string ToString() => Uri ?? GetType().Name; 10 | } 11 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Extensions/ListExtensions.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Entities; 2 | 3 | namespace BookmarkSync.Core.Extensions; 4 | 5 | public static class ListExtensions 6 | { 7 | public static List? RemoveAllFromIgnoredAccounts( 8 | this List? bookmarks, 9 | List? ignoredAccounts) 10 | { 11 | if (bookmarks is null) return bookmarks; 12 | if (ignoredAccounts is null) return bookmarks; 13 | bookmarks.RemoveAll(b => ignoredAccounts.Contains(b.Account!.Name!)); 14 | return bookmarks; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Extensions/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Extensions; 2 | 3 | public static class StringExtensions 4 | { 5 | public static bool HasLeadingAt(this string str) 6 | => str.StartsWith("@"); 7 | public static string RemoveLeadingAt(this string str) 8 | => str.HasLeadingAt() ? str[1..] : str; 9 | public static string ToSnakeCase(this string str) 10 | => string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x : x.ToString())).ToLower(); 11 | } 12 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | // Global using directives 2 | 3 | global using CiT.Common.Attributes; 4 | global using CiT.Common.Exceptions; 5 | global using CiT.Common.Validations; 6 | global using Serilog; -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Interfaces/IBookmarkingService.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Entities; 2 | 3 | namespace BookmarkSync.Core.Interfaces; 4 | 5 | public interface IBookmarkingService 6 | { 7 | /// 8 | /// Saves a bookmark to the bookmarking service. 9 | /// 10 | /// A service's bookmark implementation. 11 | public Task Save(Bookmark bookmark); 12 | } 13 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Json/SnakeCaseContractResolver.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Extensions; 2 | using Newtonsoft.Json.Serialization; 3 | 4 | namespace BookmarkSync.Core.Json; 5 | 6 | public class SnakeCaseContractResolver : DefaultContractResolver 7 | { 8 | public static readonly SnakeCaseContractResolver Instance = new(); 9 | override protected string ResolvePropertyName(string propertyName) 10 | { 11 | return propertyName.ToSnakeCase(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Meta.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http.Headers; 2 | using System.Reflection; 3 | 4 | namespace BookmarkSync.Core; 5 | 6 | public static class Meta 7 | { 8 | private static readonly Assembly? Assembly = Assembly.GetEntryAssembly(); 9 | private static readonly Type? GitVersionInformationType = Assembly?.GetType("GitVersionInformation"); 10 | public const string Name = "mastodon-bookmark-sync"; 11 | public static readonly string 12 | Version = GitVersionInformationType?.GetField("MajorMinorPatch")?.GetValue(null)?.ToString() ?? "2.0"; 13 | public static readonly ProductInfoHeaderValue UserAgent = new(Name, Version); 14 | } 15 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Utilities/HtmlUtilities.cs: -------------------------------------------------------------------------------- 1 | using HtmlAgilityPack; 2 | 3 | namespace BookmarkSync.Core.Utilities; 4 | 5 | public static class HtmlUtilities 6 | { 7 | public static string ConvertToPlainText(string html) 8 | { 9 | var doc = new HtmlDocument(); 10 | doc.LoadHtml(html); 11 | 12 | var sw = new StringWriter(); 13 | ConvertTo(doc.DocumentNode, sw); 14 | 15 | sw.Flush(); 16 | return sw.ToString(); 17 | } 18 | private static void ConvertTo(HtmlNode node, TextWriter outText) 19 | { 20 | switch (node.NodeType) 21 | { 22 | case HtmlNodeType.Comment: 23 | // don't output comments 24 | break; 25 | case HtmlNodeType.Document: 26 | ConvertContentTo(node, outText); 27 | break; 28 | 29 | case HtmlNodeType.Text: 30 | // script and style must not be output 31 | string parentName = node.ParentNode.Name; 32 | if (parentName is "script" or "style") 33 | break; 34 | 35 | // get text 36 | string html = ((HtmlTextNode)node).Text; 37 | 38 | // is it a special closing node output as text? 39 | if (HtmlNode.IsOverlappedClosingElement(html)) 40 | break; 41 | 42 | // check the text is meaningful and not a bunch of whitespace 43 | if (html.Trim().Length > 0) 44 | { 45 | outText.Write(HtmlEntity.DeEntitize(html)); 46 | } 47 | break; 48 | 49 | case HtmlNodeType.Element: 50 | switch (node.Name) 51 | { 52 | case "p": 53 | // treat paragraphs as crlf 54 | outText.Write("\r\n"); 55 | break; 56 | case "br": 57 | outText.Write("\r\n"); 58 | break; 59 | } 60 | 61 | if (node.HasChildNodes) 62 | { 63 | ConvertContentTo(node, outText); 64 | } 65 | break; 66 | } 67 | } 68 | private static void ConvertContentTo(HtmlNode node, TextWriter outText) 69 | { 70 | foreach (var subNode in node.ChildNodes) 71 | { 72 | ConvertTo(subNode, outText); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/BookmarkSync.Core/Utilities/UriUtilities.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | 3 | namespace BookmarkSync.Core.Utilities; 4 | 5 | public static class UriUtilities 6 | { 7 | private static readonly ILogger _logger = Log.ForContext(typeof(UriUtilities)); 8 | /// 9 | /// Returns a URI without a (/https?/) protocol. 10 | /// 11 | /// The URI to process. 12 | /// A URI without a protocol or trailing slash. 13 | public static string RemoveProto(this string uri) 14 | { 15 | _logger.Debug("Running {Method} for {Uri}", "RemoveProto", uri); 16 | // https://stackoverflow.com/questions/10306690/what-is-a-regular-expression-which-will-match-a-valid-domain-name-without-a-subd/26987741#26987741 17 | const string pattern = 18 | @"(?:https?:\/\/)?((((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?([a-z0-9][a-z0-9\-]{0,60}|[a-z0-9-]{1,30}\.[a-z]{2,}))"; 19 | var m = Regex.Match(uri, pattern, RegexOptions.IgnoreCase); 20 | if (m.Success) return m.Groups[1].Value; 21 | _logger.Error("Could not process {Uri}", uri); 22 | throw new ArgumentException(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/BookmarkSync.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | none 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | // Global using directives 2 | 3 | global using BookmarkSync.Core.Configuration; 4 | global using BookmarkSync.Core.Entities; 5 | global using BookmarkSync.Core.Interfaces; 6 | global using Serilog; -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/Services/Bookmarking/BookmarkSyncService.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using BookmarkSync.Core.Entities.Config; 3 | using BookmarkSync.Core.Extensions; 4 | using BookmarkSync.Infrastructure.Services.Mastodon; 5 | using Microsoft.Extensions.Hosting; 6 | 7 | namespace BookmarkSync.Infrastructure.Services.Bookmarking; 8 | 9 | [ExcludeFromCodeCoverage] 10 | public class BookmarkSyncService : IHostedService 11 | { 12 | private static readonly ILogger _logger = Log.ForContext(); 13 | private readonly IBookmarkingService _bookmarkingService; 14 | private readonly IHostApplicationLifetime _host; 15 | private readonly List _ignoredAccounts; 16 | private readonly List? _instances; 17 | private readonly MastodonService _mastodonService; 18 | public BookmarkSyncService(IHostApplicationLifetime host, IConfigManager configManager, HttpClient client, MastodonService mastodonService) 19 | { 20 | _bookmarkingService = BookmarkingService.GetBookmarkingService(configManager, client); 21 | _host = host; 22 | _instances = configManager.Instances; 23 | _ignoredAccounts = configManager.App.IgnoredAccounts; 24 | _mastodonService = mastodonService; 25 | } 26 | /// 27 | public async Task StartAsync(CancellationToken stoppingToken) 28 | { 29 | if (_instances == null || _instances.Count == 0) 30 | { 31 | _logger.Warning("No instances configured"); 32 | return; 33 | } 34 | foreach (var instance in _instances) 35 | { 36 | _logger.Information("Processing {Instance}", instance); 37 | _logger.Debug("Setting up Mastodon API client"); 38 | _mastodonService.SetInstance(instance); 39 | // Get bookmarks from mastodon account 40 | List? bookmarks = null; 41 | try 42 | { 43 | bookmarks = (await _mastodonService.GetBookmarks())? 44 | .Where(b => b.Visibility is not ("private" or "direct")) 45 | .ToList(); 46 | } 47 | catch (HttpRequestException ex) 48 | { 49 | _logger.Error(ex, "Failed to retrieve bookmarks from {Instance}", instance); 50 | } 51 | 52 | if (bookmarks == null || bookmarks.Count == 0) 53 | { 54 | _logger.Information("No bookmarks received"); 55 | continue; 56 | } 57 | 58 | // Remove any bookmarks from accounts in the IgnoredAccounts list 59 | bookmarks.RemoveAllFromIgnoredAccounts(_ignoredAccounts); 60 | 61 | foreach (var bookmark in bookmarks) 62 | { 63 | // Save bookmarks to bookmarking service 64 | HttpResponseMessage result; 65 | try 66 | { 67 | result = await _bookmarkingService.Save(bookmark); 68 | } 69 | catch (Exception ex) 70 | { 71 | _logger.Error(ex, "Failed to save bookmark"); 72 | continue; 73 | } 74 | 75 | if (instance.DeleteBookmarks && result.IsSuccessStatusCode) 76 | { 77 | _logger.Information("Deleting bookmark"); 78 | await _mastodonService.DeleteBookmark(bookmark); 79 | } 80 | } 81 | } 82 | 83 | // Finish task 84 | _host.StopApplication(); 85 | } 86 | /// 87 | public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; 88 | } 89 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/Services/Bookmarking/BookmarkingService.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http.Headers; 2 | using System.Net.Mime; 3 | using BookmarkSync.Core; 4 | using BookmarkSync.Infrastructure.Services.Bookmarking.Briefkasten; 5 | using BookmarkSync.Infrastructure.Services.Bookmarking.LinkAce; 6 | using BookmarkSync.Infrastructure.Services.Bookmarking.Linkding; 7 | using BookmarkSync.Infrastructure.Services.Bookmarking.Pinboard; 8 | 9 | namespace BookmarkSync.Infrastructure.Services.Bookmarking; 10 | 11 | public abstract class BookmarkingService 12 | { 13 | /// 14 | /// The HttpClient object. 15 | /// 16 | protected static HttpClient Client = new(); 17 | protected BookmarkingService(HttpClient client) 18 | { 19 | // Setup HttpClient 20 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json)); 21 | client.DefaultRequestHeaders.UserAgent.Add(Meta.UserAgent); 22 | Client = client; 23 | } 24 | /// 25 | /// The API auth token.. 26 | /// 27 | protected string ApiToken { get; init; } = null!; 28 | /// 29 | /// The Api URL. 30 | /// 31 | protected string ApiUri { get; init; } = null!; 32 | public static IBookmarkingService GetBookmarkingService(IConfigManager configManager, HttpClient client) 33 | { 34 | return configManager.App.Bookmarking.Service switch 35 | { 36 | "Briefkasten" => new BriefkastenBookmarkingService(configManager, client), 37 | "LinkAce" => new LinkAceBookmarkingService(configManager, client), 38 | "Pinboard" => new PinboardBookmarkingService(configManager, client), 39 | "linkding" => new LinkdingBookmarkingService(configManager, client), 40 | _ => throw new InvalidOperationException("Bookmark service either not provided or unknown") 41 | }; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/Services/Bookmarking/Briefkasten/BriefkastenBookmarkingService.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Mime; 2 | using System.Text; 3 | using Newtonsoft.Json; 4 | 5 | namespace BookmarkSync.Infrastructure.Services.Bookmarking.Briefkasten; 6 | 7 | public class BriefkastenBookmarkingService : BookmarkingService, IBookmarkingService 8 | { 9 | private static readonly ILogger _logger = Log.ForContext(); 10 | public BriefkastenBookmarkingService(IConfigManager configManager, HttpClient client) : base(client) 11 | { 12 | ApiToken = configManager.App.Bookmarking.ApiToken ?? throw new InvalidOperationException("Missing API token"); 13 | string briefkastenUri = configManager.GetConfigValue("App:Bookmarking:BriefkastenUri") ?? 14 | throw new InvalidOperationException("Missing Briefkasten Uri"); 15 | ApiUri = $"{briefkastenUri}/api/bookmarks"; 16 | } 17 | /// 18 | public async Task Save(Bookmark bookmark) 19 | { 20 | // Prep payload 21 | Dictionary payload = new() 22 | { 23 | { 24 | "url", bookmark.Uri 25 | }, 26 | { 27 | "title", bookmark.Content 28 | }, 29 | { 30 | "tags", bookmark.DefaultTags 31 | }, 32 | { 33 | "userId", ApiToken 34 | } 35 | }; 36 | var stringContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, 37 | MediaTypeNames.Application.Json); 38 | var response = await Client.PostAsync(ApiUri, stringContent); 39 | response.EnsureSuccessStatusCode(); 40 | _logger.Debug("Response status: {StatusCode}", response.StatusCode); 41 | return response; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/Services/Bookmarking/LinkAce/LinkAceBookmarkingService.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http.Headers; 2 | using System.Net.Mime; 3 | using System.Text; 4 | using System.Web; 5 | using BookmarkSync.Core.Json; 6 | using Newtonsoft.Json; 7 | 8 | namespace BookmarkSync.Infrastructure.Services.Bookmarking.LinkAce; 9 | 10 | public class LinkAceBookmarkingService : BookmarkingService, IBookmarkingService 11 | { 12 | private static readonly ILogger _logger = Log.ForContext(); 13 | private readonly string _linkAceUri; 14 | public LinkAceBookmarkingService(IConfigManager configManager, HttpClient client) : base(client) 15 | { 16 | ApiToken = configManager.App.Bookmarking.ApiToken ?? throw new InvalidOperationException("Missing API token"); 17 | _linkAceUri = configManager.GetConfigValue("App:Bookmarking:LinkAceUri") ?? 18 | throw new InvalidOperationException("Missing LinkAce Uri"); 19 | string version = configManager.App.Bookmarking.ApiVersion ?? "v2"; 20 | ApiUri = $"{_linkAceUri}/api/{version}/links"; 21 | Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ApiToken); 22 | } 23 | /// 24 | public async Task Save(Bookmark bookmark) 25 | { 26 | // Prep payload 27 | Dictionary payload = new() 28 | { 29 | { 30 | "url", bookmark.Uri 31 | }, 32 | { 33 | "title", bookmark.Content 34 | }, 35 | { 36 | "tags", bookmark.DefaultTags 37 | }, 38 | { 39 | "is_private", true 40 | }, 41 | { 42 | "check_disabled", true 43 | } 44 | }; 45 | var stringContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, 46 | MediaTypeNames.Application.Json); 47 | 48 | // Check for existing bookmarks with the same URL. 49 | var uriBuilder = new UriBuilder($"{_linkAceUri}/api/v1/search/links"); 50 | var query = HttpUtility.ParseQueryString(string.Empty); 51 | query["query"] = bookmark.Uri; 52 | uriBuilder.Query = query.ToString(); 53 | var linksResponse = await Client.GetAsync(uriBuilder.ToString()); 54 | linksResponse.EnsureSuccessStatusCode(); 55 | string responseContent = await linksResponse.Content.ReadAsStringAsync(); 56 | var responseObj = JsonConvert.DeserializeObject(responseContent, 57 | new JsonSerializerSettings 58 | { 59 | ContractResolver = SnakeCaseContractResolver.Instance 60 | }); 61 | 62 | HttpResponseMessage? response; 63 | var existingLink = responseObj?.Data?.Where(b => b.Url == bookmark.Uri).FirstOrDefault(); 64 | if (existingLink != null) 65 | { 66 | // Bookmark exists in LinkAce, try to update. 67 | _logger.Information("Bookmark {Uri} exists in LinkAce, updating...", bookmark.Uri); 68 | response = await Client.PatchAsync($"{ApiUri}/{existingLink.Id}", stringContent); 69 | response.EnsureSuccessStatusCode(); 70 | _logger.Debug("Response status: {StatusCode}", response.StatusCode); 71 | return response; 72 | } 73 | 74 | response = await Client.PostAsync(ApiUri, stringContent); 75 | response.EnsureSuccessStatusCode(); 76 | _logger.Debug("Response status: {StatusCode}", response.StatusCode); 77 | return response; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/Services/Bookmarking/LinkAce/LinkAceEntites.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Infrastructure.Services.Bookmarking.LinkAce; 2 | 3 | public class LinkAceApiSearchResponse 4 | { 5 | public int CurrentPage { get; set; } 6 | public List? Data { get; set; } 7 | public string? FirstPageUrl { get; set; } 8 | public int? From { get; set; } 9 | public int LastPage { get; set; } 10 | public string? LastPageUrl { get; set; } 11 | public string? NextPageUrl { get; set; } 12 | public string Path { get; set; } 13 | public string PerPage { get; set; } 14 | public string? PreviousPageUrl { get; set; } 15 | public int? To { get; set; } 16 | public int Total { get; set; } 17 | } 18 | public class LinkAceBookmark 19 | { 20 | public bool CheckDisabled { get; set; } 21 | public DateTime CreatedAt { get; set; } 22 | public DateTime? DeletedAt { get; set; } 23 | public string? Description { get; set; } 24 | public string Icon { get; set; } 25 | public int Id { get; set; } 26 | public bool IsPrivate { get; set; } 27 | public int Status { get; set; } 28 | public string Title { get; set; } 29 | public DateTime UpdatedAt { get; set; } 30 | public string Url { get; set; } 31 | public int UserId { get; set; } 32 | } 33 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/Services/Bookmarking/Linkding/LinkdingBookmarkingService.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http.Headers; 2 | using System.Net.Mime; 3 | using System.Text; 4 | using Newtonsoft.Json; 5 | 6 | namespace BookmarkSync.Infrastructure.Services.Bookmarking.Linkding; 7 | 8 | public class LinkdingBookmarkingService : BookmarkingService, IBookmarkingService 9 | { 10 | private static readonly ILogger _logger = Log.ForContext(); 11 | public LinkdingBookmarkingService(IConfigManager configManager, HttpClient client) : base(client) 12 | { 13 | ApiToken = configManager.App.Bookmarking.ApiToken ?? throw new InvalidOperationException("Missing API token"); 14 | string linkdingUri = configManager.GetConfigValue("App:Bookmarking:LinkdingUri") ?? 15 | throw new InvalidOperationException("Missing linkding Uri"); 16 | ApiUri = $"{linkdingUri}/api/bookmarks/"; 17 | Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", ApiToken); 18 | } 19 | /// 20 | public async Task Save(Bookmark bookmark) 21 | { 22 | // Prep payload 23 | Dictionary payload = new() 24 | { 25 | { 26 | "url", bookmark.Uri 27 | }, 28 | { 29 | "title", bookmark.Content 30 | }, 31 | { 32 | "tag_names", bookmark.DefaultTags 33 | }, 34 | { 35 | "unread", false 36 | }, 37 | { 38 | "shared", false 39 | } 40 | }; 41 | var stringContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, 42 | MediaTypeNames.Application.Json); 43 | var response = await Client.PostAsync(ApiUri, stringContent); 44 | response.EnsureSuccessStatusCode(); 45 | _logger.Debug("Response status: {StatusCode}", response.StatusCode); 46 | return response; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/Services/Bookmarking/Pinboard/PinboardBookmarkingService.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | 3 | namespace BookmarkSync.Infrastructure.Services.Bookmarking.Pinboard; 4 | 5 | public class PinboardBookmarkingService : BookmarkingService, IBookmarkingService 6 | { 7 | private const int PinboardDescriptionMaxLength = 255; 8 | private static readonly ILogger _logger = Log.ForContext(); 9 | public PinboardBookmarkingService(IConfigManager configManager, HttpClient client) : base(client) 10 | { 11 | ApiToken = configManager.App.Bookmarking.ApiToken ?? throw new InvalidOperationException(); 12 | ApiUri = "https://api.pinboard.in/v1/posts/add"; 13 | } 14 | /// 15 | public async Task Save(Bookmark bookmark) 16 | { 17 | // Prep bookmark 18 | string? extended = null; 19 | if (bookmark.Content!.Length >= PinboardDescriptionMaxLength) 20 | { 21 | string? trimmedDescription = bookmark.Content[..PinboardDescriptionMaxLength]; 22 | extended = bookmark.Content; 23 | bookmark.Content = trimmedDescription; 24 | } 25 | 26 | var builder = new UriBuilder(ApiUri); 27 | var query = HttpUtility.ParseQueryString(string.Empty); 28 | query["auth_token"] = ApiToken; 29 | query["description"] = bookmark.Content; 30 | query["url"] = bookmark.Uri; 31 | query["shared"] = "no"; 32 | if (!string.IsNullOrEmpty(extended)) 33 | { 34 | query["extended"] = extended; 35 | } 36 | query["tags"] = string.Join(" ", bookmark.DefaultTags); 37 | builder.Query = query.ToString(); 38 | var requestUri = builder.ToString(); 39 | _logger.Debug("Request URI: {RequestUri}", requestUri); 40 | 41 | var response = await Client.GetAsync(requestUri); 42 | response.EnsureSuccessStatusCode(); 43 | _logger.Debug("Response status: {StatusCode}", response.StatusCode); 44 | return response; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/BookmarkSync.Infrastructure/Services/Mastodon/MastodonService.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Http.Headers; 3 | using System.Net.Mime; 4 | using BookmarkSync.Core; 5 | using BookmarkSync.Core.Entities.Config; 6 | using Newtonsoft.Json; 7 | 8 | namespace BookmarkSync.Infrastructure.Services.Mastodon; 9 | 10 | public class MastodonService 11 | { 12 | private static readonly ILogger _logger = Log.ForContext(); 13 | private readonly HttpClient _client; 14 | private Instance _instance; 15 | public MastodonService(HttpClient client) 16 | { 17 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json)); 18 | client.DefaultRequestHeaders.UserAgent.Add(Meta.UserAgent); 19 | _client = client; 20 | } 21 | public void SetInstance(Instance instance) 22 | { 23 | _instance = instance; 24 | _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _instance.AccessToken); 25 | } 26 | public async Task DeleteBookmark(Bookmark bookmark) 27 | { 28 | _logger.Debug("Running {Method}", "DeleteBookmark"); 29 | var requestUri = $"{_instance.Uri}/api/v1/statuses/{bookmark.Id}/unbookmark"; 30 | var response = await _client.PostAsync(requestUri, null); 31 | if (response.IsSuccessStatusCode) 32 | { 33 | _logger.Information("Bookmark {BookmarkId} deleted successfully", bookmark.Id); 34 | } 35 | else 36 | { 37 | switch (response.StatusCode) 38 | { 39 | case HttpStatusCode.Forbidden: 40 | _logger.Warning( 41 | "Couldn't delete bookmark due to 403 Forbidden error." + 42 | " Does the access token have write:bookmarks permissions?"); 43 | break; 44 | default: 45 | _logger.Warning( 46 | "Couldn't delete bookmark. Status code: {StatusCode}\r\nResponse: {@Response}", 47 | response.StatusCode, 48 | response.Content); 49 | break; 50 | } 51 | } 52 | } 53 | public async Task?> GetBookmarks() 54 | { 55 | _logger.Debug("Running {Method}", "GetBookmarks"); 56 | var requestUri = $"{_instance.Uri}/api/v1/bookmarks"; 57 | var response = await _client.GetAsync(requestUri); 58 | response.EnsureSuccessStatusCode(); 59 | string responseContent = await response.Content.ReadAsStringAsync(); 60 | var obj = JsonConvert.DeserializeObject>(responseContent); 61 | 62 | return obj; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/BookmarkSync.Core.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | all 22 | runtime; build; native; contentfiles; analyzers; buildtransitive 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Configuration/ConfigManagerTests.cs: -------------------------------------------------------------------------------- 1 | using System.Configuration; 2 | using System.Text; 3 | using BookmarkSync.Core.Configuration; 4 | using BookmarkSync.Core.Extensions; 5 | using CiT.Common.Exceptions; 6 | using Microsoft.Extensions.Configuration; 7 | 8 | namespace BookmarkSync.Core.Tests.Configuration; 9 | 10 | [TestClass] 11 | public class ConfigManagerTests 12 | { 13 | [TestInitialize] 14 | public void Init() 15 | { 16 | var yamlString = @" 17 | App: 18 | Bookmarking: 19 | Service: Pinboard 20 | Instances: 21 | - Uri: https://compostintraining.club 22 | "; 23 | _config = new ConfigurationBuilder() 24 | .AddYamlStream(new MemoryStream(Encoding.UTF8.GetBytes(yamlString))) 25 | .Build(); 26 | 27 | _configManager = new ConfigManager(_config); 28 | } 29 | private IConfigManager? _configManager; 30 | private IConfiguration? _config; 31 | [TestMethod] 32 | public void ConfigManager_HasProperties() 33 | { 34 | // Assert 35 | Assert.AreEqual(2, _configManager?.PropertyCount()); 36 | Assert.IsTrue(_configManager?.HasProperty("Instances")); 37 | Assert.IsTrue(_configManager?.HasProperty("App")); 38 | 39 | Assert.IsTrue(_configManager?.HasMethod("GetConfigValue")); 40 | } 41 | [TestMethod] 42 | [ExpectedException(typeof(ConfigurationErrorsException))] 43 | public void GetConfigValue_InvalidKey() 44 | { 45 | // Arrange 46 | var expected = "Pinner"; 47 | 48 | // Act 49 | string? actual = _configManager?.GetConfigValue("Apps:Bookmarking:Service"); 50 | 51 | // Assert - Exception 52 | } 53 | [TestMethod] 54 | public void GetConfigValue_Success() 55 | { 56 | // Arrange 57 | var expected = "Pinboard"; 58 | 59 | // Act 60 | string? actual = _configManager?.GetConfigValue("App:Bookmarking:Service"); 61 | 62 | // Assert 63 | Assert.AreEqual(expected, actual); 64 | } 65 | [TestMethod] 66 | public void TestConfigManagerWithIgnoredAccountsConfigured() 67 | { 68 | var yamlString = @" 69 | App: 70 | Bookmarking: 71 | Service: LinkAce 72 | IgnoredAccounts: 73 | - ""@prplecake@social.example.com"" 74 | - flipper@social.example.com 75 | Instances: 76 | - Uri: https://compostintraining.club 77 | "; 78 | var config = new ConfigurationBuilder() 79 | .AddYamlStream(new MemoryStream(Encoding.UTF8.GetBytes(yamlString))) 80 | .Build(); 81 | 82 | var configManager = new ConfigManager(config); 83 | 84 | // Assert 85 | Assert.IsNotNull(configManager.App.IgnoredAccounts); 86 | foreach (string? account in configManager.App.IgnoredAccounts) 87 | { 88 | Assert.IsFalse(account.HasLeadingAt()); 89 | } 90 | } 91 | [TestMethod] 92 | [ExpectedException(typeof(InvalidConfigurationException))] 93 | public void Test_ConfigManager_With_Invalid_Config() 94 | { 95 | var yamlString = @" 96 | App: 97 | IgnoredAccounts: 98 | - ""@prplecake@social.example.com"" 99 | - flipper@social.example.com 100 | Instances: 101 | - Uri: https://compostintraining.club 102 | "; 103 | var config = new ConfigurationBuilder() 104 | .AddYamlStream(new MemoryStream(Encoding.UTF8.GetBytes(yamlString))) 105 | .Build(); 106 | 107 | var configManager = new ConfigManager(config); 108 | 109 | // Assert - Exception: InvalidConfigurationException 110 | } 111 | [TestMethod] 112 | [ExpectedException(typeof(NotImplementedException))] 113 | public void ConfigManager_SaveToFile_Throws_NotImplementedException() 114 | { 115 | // Act 116 | _configManager?.SaveToFile(); 117 | 118 | // Assert - Exception: NotImplementedException 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Entities/AccountTests.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Tests.Entities; 2 | 3 | [TestClass] 4 | public class AccountTests 5 | { 6 | [TestMethod] 7 | public void Account_HasProperties() 8 | { 9 | // Arrange 10 | Account obj = new(); 11 | 12 | // Assert 13 | Assert.AreEqual(1, obj.PropertyCount()); 14 | Assert.IsTrue(obj.HasProperty("Name")); 15 | } 16 | [TestMethod] 17 | public void Account_ToString_Is_Name() 18 | { 19 | // Arrange 20 | Account obj = new() 21 | { 22 | Name = "@prplecake@compostintraining.club" 23 | }; 24 | 25 | // Assert 26 | Assert.AreEqual(obj.ToString(), obj.Name); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Entities/BookmarkTests.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Tests.Entities; 2 | 3 | [TestClass] 4 | public class BookmarkTests 5 | { 6 | [TestMethod] 7 | public void Bookmark_HasProperties() 8 | { 9 | // Arrange 10 | Bookmark obj = new(); 11 | 12 | // Assert 13 | Assert.AreEqual(6, obj.PropertyCount()); 14 | Assert.IsTrue(obj.HasProperty("Account")); 15 | Assert.IsTrue(obj.HasProperty("Content")); 16 | Assert.IsTrue(obj.HasProperty("Id")); 17 | Assert.IsTrue(obj.HasProperty("Uri")); 18 | Assert.IsTrue(obj.HasProperty("Visibility")); 19 | Assert.IsTrue(obj.HasProperty("DefaultTags")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Entities/Config/AppTests.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Tests.Entities.Config; 2 | 3 | [TestClass] 4 | public class AppTests 5 | { 6 | [TestMethod] 7 | public void App_HasProperties() 8 | { 9 | // Arrange 10 | App obj = new(); 11 | 12 | // Assert 13 | Assert.AreEqual(3, obj.PropertyCount()); 14 | Assert.IsTrue(obj.HasProperty("Bookmarking")); 15 | Assert.IsTrue(obj.HasProperty("IgnoredAccounts")); 16 | Assert.IsTrue(obj.HasProperty("LastSynced")); 17 | 18 | Assert.IsTrue(obj.HasMethod("IsValid")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Entities/Config/BookmarkingTests.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Tests.Entities.Config; 2 | 3 | [TestClass] 4 | public class BookmarkingTests 5 | { 6 | [TestMethod] 7 | public void Bookmarking_HasProperties() 8 | { 9 | // Arrange 10 | Bookmarking obj = new(); 11 | 12 | // Assert 13 | Assert.AreEqual(3, obj.PropertyCount()); 14 | Assert.IsTrue(obj.HasProperty("ApiToken")); 15 | Assert.IsTrue(obj.HasProperty("Service")); 16 | Assert.IsTrue(obj.HasProperty("ApiVersion")); 17 | 18 | Assert.IsTrue(obj.HasMethod("IsValid")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Entities/Config/InstanceTests.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Core.Tests.Entities.Config; 2 | 3 | [TestClass] 4 | public class InstanceTests 5 | { 6 | [TestMethod] 7 | public void Instance_HasProperties() 8 | { 9 | // Arrange 10 | Instance obj = new(); 11 | 12 | // Assert 13 | Assert.AreEqual(3, obj.PropertyCount()); 14 | Assert.IsTrue(obj.HasProperty("AccessToken")); 15 | Assert.IsTrue(obj.HasProperty("DeleteBookmarks")); 16 | Assert.IsTrue(obj.HasProperty("Uri")); 17 | 18 | Assert.IsTrue(obj.HasMethod("IsValid")); 19 | } 20 | [TestMethod] 21 | public void Instance_ToString_Is_Uri() 22 | { 23 | // Arrange 24 | Instance obj = new() 25 | { 26 | Uri = "https://compostintraining.club" 27 | }; 28 | 29 | // Assert 30 | Assert.AreEqual(obj.ToString(), obj.Uri); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Extensions/ListExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Extensions; 2 | 3 | namespace BookmarkSync.Core.Tests.Extensions; 4 | 5 | [TestClass] 6 | public class ListExtensionsTests 7 | { 8 | [TestMethod] 9 | public void RemoveAllFromIgnoredAccounts_Empty_IgnoredAccounts_Returns_Unchanged_Bookmarks_List() 10 | { 11 | // Arrange 12 | var bookmarks = new List() { NewBookmark(), NewBookmark(), NewBookmark()}; 13 | 14 | // Act 15 | var result = bookmarks.RemoveAllFromIgnoredAccounts(new List()); 16 | 17 | // Assert 18 | CollectionAssert.AreEqual(bookmarks, result); 19 | } 20 | [TestMethod] 21 | public void RemoveAllFromIgnoredAccounts_Removes_Expected() 22 | { 23 | // Arrange 24 | var bookmarks = new List() { NewBookmark(), NewBookmark(), NewBookmark()}; 25 | bookmarks.AddRange(new[] { NewBookmark("@remove@example.com"), NewBookmark("remove@example.com") }); 26 | 27 | Assert.AreEqual(5, bookmarks.Count); 28 | 29 | // Act 30 | var result = bookmarks.RemoveAllFromIgnoredAccounts(new List() { "@remove@example.com" }); 31 | 32 | // Assert 33 | CollectionAssert.AreEqual(bookmarks, result); 34 | } 35 | [TestMethod] 36 | public void RemoveAllFromIgnoredAccounts_Null_Bookmarks_List_Returns_Same() 37 | { 38 | // Arrange 39 | List? bookmarks = null; 40 | 41 | // Act 42 | var result = bookmarks.RemoveAllFromIgnoredAccounts(new List()); 43 | 44 | // Assert 45 | Assert.IsNull(result); 46 | } 47 | private Bookmark NewBookmark(string? account = null) 48 | { 49 | return new Bookmark 50 | { Account = new Account(account ?? "@test@example.com"), 51 | Content = "Good post", 52 | Id = TestHelpers.RandomString(16) }; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Extensions/StringExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Extensions; 2 | 3 | namespace BookmarkSync.Core.Tests.Extensions; 4 | 5 | [TestClass] 6 | public class StringExtensionsTests 7 | { 8 | [DataTestMethod] 9 | [DataRow("@prplecake", true)] 10 | [DataRow("flipper", false)] 11 | public void HasLeadingAt_Success(string input, bool expected) 12 | { 13 | // Act 14 | bool actual = input.HasLeadingAt(); 15 | 16 | // Assert 17 | Assert.AreEqual(expected, actual); 18 | } 19 | [DataTestMethod] 20 | [DataRow("@prplecake@compostintraining.club", "prplecake@compostintraining.club")] 21 | [DataRow("flipper@compostintraining.club", "flipper@compostintraining.club")] 22 | public void RemoveLeadingAt_Success(string input, string expected) 23 | { 24 | // Act 25 | string actual = input.RemoveLeadingAt(); 26 | 27 | // Assert 28 | Assert.AreEqual(expected, actual); 29 | } 30 | [DataTestMethod] 31 | [DataRow("Example", "example")] 32 | [DataRow("TestCase", "test_case")] 33 | [DataRow("Example2", "example2")] 34 | public void ToSnakeCase_Success(string input, string expected) 35 | { 36 | // Act 37 | string actual = input.ToSnakeCase(); 38 | 39 | // Assert 40 | Assert.AreEqual(expected, actual); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | // Global using directives 2 | 3 | global using BookmarkSync.Core.Entities; 4 | global using BookmarkSync.Core.Entities.Config; 5 | global using BookmarkSync.Core.Tests.Helpers; 6 | global using Microsoft.VisualStudio.TestTools.UnitTesting; -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Helpers/TestHelpers.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Text; 3 | #pragma warning disable CS8604 4 | #pragma warning disable CS8600 5 | #pragma warning disable CS8602 6 | namespace BookmarkSync.Core.Tests.Helpers; 7 | 8 | public static class EntityTests 9 | { 10 | public static bool HasMethod(this object obj, string methodName) 11 | { 12 | var type = obj.GetType(); 13 | try 14 | { 15 | return type.GetMethod(methodName) != null; 16 | } 17 | catch (AmbiguousMatchException) 18 | { 19 | return true; 20 | } 21 | } 22 | public static bool HasProperty(this object obj, string propertyName) 23 | { 24 | var type = obj.GetType(); 25 | return type.GetProperty(propertyName) != null; 26 | } 27 | public static int PropertyCount(this object obj) 28 | { 29 | var type = obj.GetType(); 30 | return type.GetProperties().Length; 31 | } 32 | public static T SetProperties(T domainObject, bool recursive = false) 33 | { 34 | var props = domainObject.GetType().GetProperties(); 35 | foreach (var prop in props) 36 | { 37 | var propType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; 38 | try 39 | { 40 | object propObj = null; 41 | object data; 42 | switch (propType.Name.ToLower()) 43 | { 44 | case "string": 45 | data = "test"; 46 | break; 47 | case "int": 48 | case "int32": 49 | data = 2; 50 | break; 51 | case "datetime": 52 | data = DateTime.Now; 53 | break; 54 | case "bool": 55 | case "boolean": 56 | data = true; 57 | break; 58 | case "decimal": 59 | data = decimal.Parse("1.23"); 60 | break; 61 | case "double": 62 | data = double.Parse("3.21"); 63 | break; 64 | default: 65 | if (propType.IsInterface) 66 | { 67 | propObj = null; 68 | } 69 | else if (propType.IsArray) 70 | { 71 | var elementType = propType.GetElementType(); 72 | propObj = Array.CreateInstance(elementType, 1); 73 | } 74 | else 75 | { 76 | var ctr = propType.GetConstructors()[0]; 77 | propObj = ctr.GetParameters().Any() ? null : Activator.CreateInstance(propType); 78 | } 79 | data = propObj; 80 | break; 81 | } 82 | if (data != null && prop.CanWrite) 83 | { 84 | prop.SetValue(domainObject, data); 85 | Assert.AreEqual(data, prop.GetValue(domainObject)); 86 | } 87 | if (recursive && propObj != null) 88 | { 89 | if (propType.IsGenericType) 90 | { 91 | var myListElementType = propType.GetGenericArguments().Single(); 92 | propObj = Activator.CreateInstance(myListElementType); 93 | } 94 | SetProperties(propObj, recursive); 95 | } 96 | } 97 | catch (Exception ex) 98 | { 99 | var msg = string.Format( 100 | "Error creating instance of {0} because: {1}", 101 | propType.Name, ex.Message); 102 | Assert.IsNotNull(prop.GetValue(domainObject), msg); 103 | } 104 | } 105 | return domainObject; 106 | } 107 | } 108 | public class TestHelpers 109 | { 110 | public static string RandomString(int size) 111 | { 112 | StringBuilder builder = new StringBuilder(); 113 | char ch; 114 | for (int i = 0; i < size; i++) 115 | { 116 | ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); 117 | builder.Append(ch); 118 | } 119 | return builder.ToString(); 120 | } 121 | private static readonly Random random = new((int)DateTime.Now.Ticks); 122 | } 123 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/SnakeCaseContractResolverTests.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Json; 2 | 3 | namespace BookmarkSync.Core.Tests; 4 | 5 | [TestClass] 6 | public class SnakeCaseContractResolverTests 7 | { 8 | [DataTestMethod] 9 | [DataRow("clientId", "client_id")] 10 | public void ResolvePropertyName_IsSnakeCase(string input, string expected) 11 | { 12 | // Arrange 13 | var resolver = SnakeCaseContractResolver.Instance; 14 | 15 | // Act 16 | var actual = resolver.GetResolvedPropertyName(input); 17 | 18 | // Assert 19 | Assert.AreEqual(expected, actual); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Utilities/HtmlUtilitiesTests.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Utilities; 2 | 3 | namespace BookmarkSync.Core.Tests.Utilities; 4 | 5 | [TestClass] 6 | public class HtmlUtilitiesTests 7 | { 8 | [TestMethod] 9 | public void ConvertToPlainText_Success() 10 | { 11 | // Arrange 12 | const string 13 | html = "

example paragraph

", 14 | expected = "\r\nexample paragraph"; 15 | 16 | // Act 17 | string actual = HtmlUtilities.ConvertToPlainText(html); 18 | 19 | // Assert 20 | Assert.AreEqual(expected, actual); 21 | } 22 | [TestMethod] 23 | public void ConvertToPlainText_WithBr() 24 | { 25 | // Arrange 26 | const string 27 | html = "

example paragraph
with breaks

", 28 | expected = "\r\nexample paragraph\r\nwith breaks"; 29 | 30 | // Act 31 | string actual = HtmlUtilities.ConvertToPlainText(html); 32 | 33 | // Assert 34 | Assert.AreEqual(expected, actual); 35 | } 36 | [TestMethod] 37 | public void ConvertToPlainText_WithComments() 38 | { 39 | // Arrange 40 | const string 41 | html = """ 42 | 43 | html document 44 | """, 45 | expected = "html document"; 46 | 47 | // Act 48 | string actual = HtmlUtilities.ConvertToPlainText(html).Trim(); 49 | 50 | // Assert 51 | Assert.AreEqual(expected, actual); 52 | } 53 | 54 | [TestMethod] 55 | public void ConvertToPlainText_WithScripts() 56 | { 57 | // Arrange 58 | const string 59 | html = """ 60 | html document 61 | 64 | """, 65 | expected = "html document"; 66 | 67 | // Act 68 | string actual = HtmlUtilities.ConvertToPlainText(html).Trim(); 69 | 70 | // Assert 71 | Assert.AreEqual(expected, actual); 72 | } 73 | [TestMethod] 74 | public void ConvertToPlainText_WithStyle() 75 | { 76 | // Arrange 77 | const string 78 | html = """ 79 | 85 | html document 86 | """, 87 | expected = "html document"; 88 | 89 | // Act 90 | string actual = HtmlUtilities.ConvertToPlainText(html).Trim(); 91 | 92 | // Assert 93 | Assert.AreEqual(expected, actual); 94 | } 95 | } -------------------------------------------------------------------------------- /tests/BookmarkSync.Core.Tests/Utilities/UriUtilitiesTests.cs: -------------------------------------------------------------------------------- 1 | using BookmarkSync.Core.Utilities; 2 | 3 | namespace BookmarkSync.Core.Tests.Utilities; 4 | 5 | [TestClass] 6 | public class UriUtilitiesTests 7 | { 8 | [DataTestMethod] 9 | [DataRow("https://example.com")] 10 | [DataRow("https://example.com/")] 11 | public void UriUtilities_HttpsProto(string uri) 12 | { 13 | string actual = uri.RemoveProto(); 14 | Assert.AreEqual("example.com", actual); 15 | } 16 | [DataTestMethod] 17 | [DataRow("http://example.com")] 18 | [DataRow("http://example.com/")] 19 | public void UriUtilities_HttpProto(string uri) 20 | { 21 | string actual = uri.RemoveProto(); 22 | Assert.AreEqual("example.com", actual); 23 | } 24 | [DataTestMethod] 25 | [DataRow("example.com")] 26 | [DataRow("example.com/")] 27 | public void UriUtilities_NoProto(string uri) 28 | { 29 | string actual = uri.RemoveProto(); 30 | Assert.AreEqual("example.com", actual); 31 | } 32 | [TestMethod] 33 | [ExpectedException(typeof(ArgumentException))] 34 | public void UrlUtilities_RemoveProto_EmptyString() 35 | { 36 | // Act 37 | string.Empty.RemoveProto(); 38 | 39 | // Assert - Exception: ArgumentException 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Infrastructure.Tests/BookmarkSync.Infrastructure.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | all 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Infrastructure.Tests/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | // Global using directives 2 | 3 | global using BookmarkSync.Core.Configuration; 4 | global using BookmarkSync.Infrastructure.Services.Bookmarking; 5 | global using BookmarkSync.Infrastructure.Services.Bookmarking.Briefkasten; 6 | global using BookmarkSync.Infrastructure.Services.Bookmarking.LinkAce; 7 | global using BookmarkSync.Infrastructure.Services.Bookmarking.Linkding; 8 | global using BookmarkSync.Infrastructure.Services.Bookmarking.Pinboard; 9 | global using Microsoft.Extensions.Configuration; 10 | global using Microsoft.VisualStudio.TestTools.UnitTesting; -------------------------------------------------------------------------------- /tests/BookmarkSync.Infrastructure.Tests/Services/BookmarkingServiceTests.cs: -------------------------------------------------------------------------------- 1 | namespace BookmarkSync.Infrastructure.Tests.Services; 2 | 3 | [TestClass] 4 | public class BookmarkingServiceTests 5 | { 6 | [TestMethod] 7 | [ExpectedException(typeof(InvalidOperationException))] 8 | public void GetBookmarkingService_Exception() 9 | { 10 | // Arrange 11 | var config = new Dictionary 12 | { 13 | { 14 | "App:Bookmarking:Service", "Nonsense" 15 | } 16 | }; 17 | var configuration = new ConfigurationBuilder() 18 | .AddInMemoryCollection(config) 19 | .Build(); 20 | 21 | IConfigManager configManager = new ConfigManager(configuration); 22 | HttpClient httpClient = new(); 23 | 24 | // Act 25 | var unused = BookmarkingService.GetBookmarkingService(configManager, httpClient); 26 | 27 | // Assert - Exception 28 | } 29 | [TestMethod] 30 | public void GetBookmarkingService_Briefkasten() 31 | { 32 | // Arrange 33 | var config = new Dictionary 34 | { 35 | { 36 | "App:Bookmarking:Service", "Briefkasten" 37 | }, 38 | { 39 | "App:Bookmarking:ApiToken", "ABC123DEF456" 40 | }, 41 | { 42 | "App:Bookmarking:BriefkastenUri", "https://briefkastenhq.com" 43 | } 44 | }; 45 | var configuration = new ConfigurationBuilder() 46 | .AddInMemoryCollection(config) 47 | .Build(); 48 | 49 | IConfigManager configManager = new ConfigManager(configuration); 50 | HttpClient httpClient = new(); 51 | 52 | // Act 53 | var obj = BookmarkingService.GetBookmarkingService(configManager, httpClient); 54 | 55 | // Assert 56 | Assert.AreEqual(typeof(BriefkastenBookmarkingService), obj.GetType()); 57 | Assert.IsInstanceOfType(obj, typeof(BriefkastenBookmarkingService)); 58 | } 59 | [TestMethod] 60 | public void GetBookmarkingService_LinkAce() 61 | { 62 | // Arrange 63 | var config = new Dictionary 64 | { 65 | { 66 | "App:Bookmarking:Service", "LinkAce" 67 | }, 68 | { 69 | "App:Bookmarking:ApiToken", "secret:123456789" 70 | }, 71 | { 72 | "App:Bookmarking:LinkAceUri", "https://your-linkace-url.com" 73 | } 74 | }; 75 | var configuration = new ConfigurationBuilder() 76 | .AddInMemoryCollection(config) 77 | .Build(); 78 | 79 | IConfigManager configManager = new ConfigManager(configuration); 80 | HttpClient httpClient = new(); 81 | 82 | // Act 83 | var obj = BookmarkingService.GetBookmarkingService(configManager, httpClient); 84 | 85 | // Assert 86 | Assert.AreEqual(typeof(LinkAceBookmarkingService), obj.GetType()); 87 | Assert.IsInstanceOfType(obj, typeof(LinkAceBookmarkingService)); 88 | } 89 | [TestMethod] 90 | public void GetBookmarkingService_Linkding() 91 | { 92 | // Arrange 93 | var config = new Dictionary 94 | { 95 | { 96 | "App:Bookmarking:Service", "linkding" 97 | }, 98 | { 99 | "App:Bookmarking:ApiToken", "3781368521fd4fae365dac100f28dbce533a4f9a" 100 | }, 101 | { 102 | "App:Bookmarking:LinkdingUri", "https://your-linkace-url.com" 103 | } 104 | }; 105 | var configuration = new ConfigurationBuilder() 106 | .AddInMemoryCollection(config) 107 | .Build(); 108 | 109 | IConfigManager configManager = new ConfigManager(configuration); 110 | HttpClient httpClient = new(); 111 | 112 | // Act 113 | var obj = BookmarkingService.GetBookmarkingService(configManager, httpClient); 114 | 115 | // Assert 116 | Assert.AreEqual(typeof(LinkdingBookmarkingService), obj.GetType()); 117 | Assert.IsInstanceOfType(obj, typeof(LinkdingBookmarkingService)); 118 | } 119 | [TestMethod] 120 | public void GetBookmarkingService_Pinboard() 121 | { 122 | // Arrange 123 | var config = new Dictionary 124 | { 125 | { 126 | "App:Bookmarking:Service", "Pinboard" 127 | }, 128 | { 129 | "App:Bookmarking:ApiToken", "secret:123456789" 130 | } 131 | }; 132 | var configuration = new ConfigurationBuilder() 133 | .AddInMemoryCollection(config) 134 | .Build(); 135 | 136 | IConfigManager configManager = new ConfigManager(configuration); 137 | HttpClient httpClient = new(); 138 | 139 | // Act 140 | var obj = BookmarkingService.GetBookmarkingService(configManager, httpClient); 141 | 142 | // Assert 143 | Assert.AreEqual(typeof(PinboardBookmarkingService), obj.GetType()); 144 | Assert.IsInstanceOfType(obj, typeof(PinboardBookmarkingService)); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Infrastructure.Tests/Services/Briefkasten/BriefkastenBookmarkingServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using BookmarkSync.Core.Entities; 3 | using Moq; 4 | using Moq.Protected; 5 | 6 | namespace BookmarkSync.Infrastructure.Tests.Services.Briefkasten; 7 | 8 | [TestClass] 9 | public class BriefkastenBookmarkingServiceTests 10 | { 11 | [TestInitialize] 12 | public void Init() 13 | { 14 | var config = new Dictionary 15 | { 16 | { 17 | "App:Bookmarking:Service", "Briefkasten" 18 | }, 19 | { 20 | "App:Bookmarking:ApiToken", "token123456" 21 | }, 22 | { 23 | "App:Bookmarking:BriefkastenUri", "https://briefkastenhq.com/" 24 | } 25 | }; 26 | var configuration = new ConfigurationBuilder() 27 | .AddInMemoryCollection(config) 28 | .Build(); 29 | IConfigManager configManager = new ConfigManager(configuration); 30 | _configManager = configManager; 31 | } 32 | private IConfigManager _configManager; 33 | [TestMethod] 34 | public async Task Briefkasten_Save_Success() 35 | { 36 | // Arrange 37 | var httpResponse = new HttpResponseMessage(); 38 | httpResponse.StatusCode = HttpStatusCode.OK; 39 | 40 | Mock mockHandler = new(); 41 | mockHandler.Protected() 42 | .Setup>("SendAsync", 43 | ItExpr.Is(r => 44 | r.Method == HttpMethod.Post && r.RequestUri.ToString() 45 | .StartsWith(_configManager.GetConfigValue("App:Bookmarking:BriefkastenUri"))), 46 | ItExpr.IsAny()) 47 | .ReturnsAsync(httpResponse); 48 | 49 | var httpClient = new HttpClient(mockHandler.Object); 50 | var bookmarkingService = BookmarkingService.GetBookmarkingService(_configManager, httpClient); 51 | var bookmark = new Bookmark 52 | { 53 | Uri = "https://example.com" 54 | }; 55 | 56 | // Act 57 | var result = await bookmarkingService.Save(bookmark); 58 | 59 | // Assert 60 | Assert.IsNotNull(result); 61 | Assert.IsTrue(result.IsSuccessStatusCode); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Infrastructure.Tests/Services/LinkAce/LinkAceBookmarkingServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Mime; 3 | using System.Text; 4 | using BookmarkSync.Core.Entities; 5 | using Moq; 6 | using Moq.Protected; 7 | 8 | namespace BookmarkSync.Infrastructure.Tests.Services.LinkAce; 9 | 10 | [TestClass] 11 | public class LinkAceBookmarkingServiceTests 12 | { 13 | [TestInitialize] 14 | public void Init() 15 | { 16 | var config = new Dictionary 17 | { 18 | { 19 | "App:Bookmarking:Service", "LinkAce" 20 | }, 21 | { 22 | "App:Bookmarking:ApiToken", "token123456" 23 | }, 24 | { 25 | "App:Bookmarking:LinkAceUri", "https://links.example.com/" 26 | } 27 | }; 28 | var configuration = new ConfigurationBuilder() 29 | .AddInMemoryCollection(config) 30 | .Build(); 31 | IConfigManager configManager = new ConfigManager(configuration); 32 | _configManager = configManager; 33 | } 34 | private IConfigManager _configManager; 35 | [TestMethod] 36 | public void LinkAce_Save_Success() 37 | { 38 | // Arrange 39 | var getHttpResponse = new HttpResponseMessage(); 40 | getHttpResponse.StatusCode = HttpStatusCode.OK; 41 | getHttpResponse.Content = new StringContent(@" 42 | { 43 | ""current_page"": 1, 44 | ""data"": [], 45 | ""first_page_url"": ""https://links.fminus.co/api/v1/search/links?page=1"", 46 | ""from"": null, 47 | ""last_page"": 1, 48 | ""last_page_url"": ""https://links.fminus.co/api/v1/search/links?page=1"", 49 | ""links"": [ 50 | { 51 | ""url"": null, 52 | ""label"": ""« Previous"", 53 | ""active"": false 54 | }, 55 | { 56 | ""url"": ""https://links.fminus.co/api/v1/search/links?page=1"", 57 | ""label"": ""1"", 58 | ""active"": true 59 | }, 60 | { 61 | ""url"": null, 62 | ""label"": ""Next »"", 63 | ""active"": false 64 | } 65 | ], 66 | ""next_page_url"": null, 67 | ""path"": ""https://links.fminus.co/api/v1/search/links"", 68 | ""per_page"": 24, 69 | ""prev_page_url"": null, 70 | ""to"": null, 71 | ""total"": 0 72 | } 73 | ", Encoding.UTF8, MediaTypeNames.Application.Json); 74 | var postHttpResponse = new HttpResponseMessage(); 75 | postHttpResponse.StatusCode = HttpStatusCode.OK; 76 | 77 | Mock mockHandler = new(); 78 | // GET 79 | mockHandler.Protected() 80 | .Setup>("SendAsync", 81 | ItExpr.Is(r => 82 | r.Method == HttpMethod.Get && r.RequestUri.ToString() 83 | .StartsWith(_configManager.GetConfigValue("App:Bookmarking:LinkAceUri"))), 84 | ItExpr.IsAny()) 85 | .ReturnsAsync(getHttpResponse); 86 | // POST 87 | mockHandler.Protected() 88 | .Setup>("SendAsync", 89 | ItExpr.Is(r => 90 | r.Method == HttpMethod.Post && r.RequestUri.ToString() 91 | .StartsWith(_configManager.GetConfigValue("App:Bookmarking:LinkAceUri"))), 92 | ItExpr.IsAny()) 93 | .ReturnsAsync(postHttpResponse); 94 | 95 | var httpClient = new HttpClient(mockHandler.Object); 96 | var bookmarkingService = BookmarkingService.GetBookmarkingService(_configManager, httpClient); 97 | var bookmark = new Bookmark 98 | { 99 | Uri = "https://example.com" 100 | }; 101 | 102 | // Act 103 | var result = bookmarkingService.Save(bookmark).Result; 104 | 105 | // Assert 106 | Assert.IsNotNull(result); 107 | Assert.IsTrue(result.IsSuccessStatusCode); 108 | } 109 | [TestMethod] 110 | public void LinkAce_Save_Success_Link_Exists() 111 | { 112 | // Arrange 113 | var getHttpResponse = new HttpResponseMessage(); 114 | getHttpResponse.StatusCode = HttpStatusCode.OK; 115 | getHttpResponse.Content = new StringContent(@" 116 | { 117 | ""current_page"": 1, 118 | ""data"": [ 119 | { 120 | ""id"": 1098, 121 | ""user_id"": 1, 122 | ""url"": ""https://photos.jrgnsn.net/album/classic-atreus-build"", 123 | ""title"": ""Classic Atreus Build - jphotos"", 124 | ""description"": ""Pictures from my Atreus keyboard build"", 125 | ""is_private"": false, 126 | ""created_at"": ""2020-09-21T21:39:11.000000Z"", 127 | ""updated_at"": ""2023-06-09T16:16:37.000000Z"", 128 | ""deleted_at"": null, 129 | ""icon"": ""link"", 130 | ""status"": 1, 131 | ""check_disabled"": false, 132 | ""thumbnail"": null, 133 | ""tags"": [ 134 | { 135 | ""id"": 603, 136 | ""user_id"": 1, 137 | ""name"": ""atreus"", 138 | ""is_private"": false, 139 | ""created_at"": ""2023-06-09T16:16:36.000000Z"", 140 | ""updated_at"": ""2023-06-09T16:16:36.000000Z"", 141 | ""deleted_at"": null, 142 | ""pivot"": { 143 | ""link_id"": 1098, 144 | ""tag_id"": 603 145 | } 146 | }, 147 | { 148 | ""id"": 234, 149 | ""user_id"": 1, 150 | ""name"": ""diy"", 151 | ""is_private"": false, 152 | ""created_at"": ""2023-06-09T16:07:30.000000Z"", 153 | ""updated_at"": ""2023-06-09T16:07:30.000000Z"", 154 | ""deleted_at"": null, 155 | ""pivot"": { 156 | ""link_id"": 1098, 157 | ""tag_id"": 234 158 | } 159 | }, 160 | { 161 | ""id"": 605, 162 | ""user_id"": 1, 163 | ""name"": ""keyboard"", 164 | ""is_private"": false, 165 | ""created_at"": ""2023-06-09T16:16:37.000000Z"", 166 | ""updated_at"": ""2023-06-09T16:16:37.000000Z"", 167 | ""deleted_at"": null, 168 | ""pivot"": { 169 | ""link_id"": 1098, 170 | ""tag_id"": 605 171 | } 172 | } 173 | ] 174 | } 175 | ], 176 | ""first_page_url"": ""https://links.fminus.co/api/v1/search/links?page=1"", 177 | ""from"": 1, 178 | ""last_page"": 1, 179 | ""last_page_url"": ""https://links.fminus.co/api/v1/search/links?page=1"", 180 | ""links"": [ 181 | { 182 | ""url"": null, 183 | ""label"": ""« Previous"", 184 | ""active"": false 185 | }, 186 | { 187 | ""url"": ""https://links.fminus.co/api/v1/search/links?page=1"", 188 | ""label"": ""1"", 189 | ""active"": true 190 | }, 191 | { 192 | ""url"": null, 193 | ""label"": ""Next »"", 194 | ""active"": false 195 | } 196 | ], 197 | ""next_page_url"": null, 198 | ""path"": ""https://links.fminus.co/api/v1/search/links"", 199 | ""per_page"": 24, 200 | ""prev_page_url"": null, 201 | ""to"": 1, 202 | ""total"": 1 203 | } 204 | ", Encoding.UTF8, MediaTypeNames.Application.Json); 205 | var postHttpResponse = new HttpResponseMessage(); 206 | postHttpResponse.StatusCode = HttpStatusCode.OK; 207 | 208 | Mock mockHandler = new(); 209 | // GET 210 | mockHandler.Protected() 211 | .Setup>("SendAsync", 212 | ItExpr.Is(r => 213 | r.Method == HttpMethod.Get && r.RequestUri.ToString() 214 | .StartsWith(_configManager.GetConfigValue("App:Bookmarking:LinkAceUri"))), 215 | ItExpr.IsAny()) 216 | .ReturnsAsync(getHttpResponse); 217 | // POST 218 | mockHandler.Protected() 219 | .Setup>("SendAsync", 220 | ItExpr.Is(r => 221 | r.Method == HttpMethod.Patch && r.RequestUri.ToString() 222 | .StartsWith(_configManager.GetConfigValue("App:Bookmarking:LinkAceUri"))), 223 | ItExpr.IsAny()) 224 | .ReturnsAsync(postHttpResponse); 225 | 226 | var httpClient = new HttpClient(mockHandler.Object); 227 | var bookmarkingService = BookmarkingService.GetBookmarkingService(_configManager, httpClient); 228 | var bookmark = new Bookmark 229 | { 230 | Uri = "https://photos.jrgnsn.net/album/classic-atreus-build" 231 | }; 232 | 233 | // Act 234 | var result = bookmarkingService.Save(bookmark).Result; 235 | 236 | // Assert 237 | Assert.IsNotNull(result); 238 | Assert.IsTrue(result.IsSuccessStatusCode); 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Infrastructure.Tests/Services/Linkding/LinkdingBookmarkingServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using BookmarkSync.Core.Entities; 3 | using Moq; 4 | using Moq.Protected; 5 | 6 | namespace BookmarkSync.Infrastructure.Tests.Services.Linkding; 7 | 8 | [TestClass] 9 | public class LinkdingBookmarkingServiceTests 10 | { 11 | [TestInitialize] 12 | public void Init() 13 | { 14 | var config = new Dictionary 15 | { 16 | { 17 | "App:Bookmarking:Service", "linkding" 18 | }, 19 | { 20 | "App:Bookmarking:ApiToken", "token123456" 21 | }, 22 | { 23 | "App:Bookmarking:LinkdingUri", "https://links.example.com" 24 | } 25 | }; 26 | var configuration = new ConfigurationBuilder() 27 | .AddInMemoryCollection(config) 28 | .Build(); 29 | IConfigManager configManager = new ConfigManager(configuration); 30 | _configManager = configManager; 31 | } 32 | private IConfigManager _configManager; 33 | [TestMethod] 34 | public async Task Linkding_Save_Success() 35 | { 36 | // Arrange 37 | var httpResponse = new HttpResponseMessage(); 38 | httpResponse.StatusCode = HttpStatusCode.OK; 39 | 40 | Mock mockHandler = new(); 41 | mockHandler.Protected() 42 | .Setup>("SendAsync", 43 | ItExpr.Is(r => 44 | r.Method == HttpMethod.Post && r.RequestUri.ToString() 45 | .StartsWith(_configManager.GetConfigValue("App:Bookmarking:LinkdingUri"))), 46 | ItExpr.IsAny()) 47 | .ReturnsAsync(httpResponse); 48 | 49 | var httpClient = new HttpClient(mockHandler.Object); 50 | var bookmarkingService = BookmarkingService.GetBookmarkingService(_configManager, httpClient); 51 | var bookmark = new Bookmark 52 | { 53 | Uri = "https://example.com" 54 | }; 55 | 56 | // Act 57 | var result = await bookmarkingService.Save(bookmark); 58 | 59 | // Assert 60 | Assert.IsNotNull(result); 61 | Assert.IsTrue(result.IsSuccessStatusCode); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Infrastructure.Tests/Services/Mastodon/MastodonServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Mime; 3 | using System.Text; 4 | using BookmarkSync.Core.Entities; 5 | using BookmarkSync.Core.Entities.Config; 6 | using BookmarkSync.Infrastructure.Services.Mastodon; 7 | using Moq; 8 | using Moq.Protected; 9 | using Newtonsoft.Json; 10 | using Serilog; 11 | using Serilog.Events; 12 | using Serilog.Sinks.TestCorrelator; 13 | 14 | namespace BookmarkSync.Infrastructure.Tests.Services.Mastodon; 15 | 16 | [TestClass] 17 | public class MastodonServiceTests 18 | { 19 | [AssemblyInitialize] 20 | public static void ConfigureGlobalLogger(TestContext testContext) 21 | { 22 | Log.Logger = new LoggerConfiguration() 23 | .MinimumLevel.Debug() 24 | .WriteTo.TestCorrelator().CreateLogger(); 25 | } 26 | [TestMethod] 27 | public async Task MastodonService_Delete_Bookmark_Success() 28 | { 29 | // Arrange 30 | var httpResponse = new HttpResponseMessage(); 31 | httpResponse.StatusCode = HttpStatusCode.OK; 32 | var instance = new Instance 33 | { 34 | Uri = "https://localhost:3000" 35 | }; 36 | 37 | Mock mockHandler = new(); 38 | mockHandler.Protected() 39 | .Setup>("SendAsync", 40 | ItExpr.Is(r => 41 | r.Method == HttpMethod.Post && r.RequestUri.ToString().StartsWith(instance.Uri)), 42 | ItExpr.IsAny()) 43 | .ReturnsAsync(httpResponse); 44 | 45 | var httpClient = new HttpClient(mockHandler.Object); 46 | 47 | using (TestCorrelator.CreateContext()) 48 | { 49 | var mastodonService = new MastodonService(httpClient); 50 | mastodonService.SetInstance(instance); 51 | 52 | // Act 53 | await mastodonService.DeleteBookmark(new Bookmark 54 | { 55 | Id = "123456" 56 | }); 57 | 58 | // Assert 59 | var logs = TestCorrelator.GetLogEventsFromCurrentContext(); 60 | Assert.IsNotNull(logs); 61 | var logEvents = logs.ToList(); 62 | Assert.AreEqual(2, logEvents.Count); 63 | var logMessage = logEvents.Where(e => e.Level == LogEventLevel.Information).ToList()[0]; 64 | Assert.AreEqual(LogEventLevel.Information, logMessage.Level); 65 | Assert.IsTrue(logMessage.MessageTemplate.ToString().Contains("deleted successfully")); 66 | } 67 | } 68 | [TestMethod] 69 | public async Task MastodonService_Failed_To_Delete_Bookmark() 70 | { 71 | // Arrange 72 | var httpResponse = new HttpResponseMessage(); 73 | httpResponse.StatusCode = HttpStatusCode.BadRequest; 74 | var instance = new Instance 75 | { 76 | Uri = "https://localhost:3000" 77 | }; 78 | 79 | Mock mockHandler = new(); 80 | mockHandler.Protected() 81 | .Setup>("SendAsync", 82 | ItExpr.Is(r => 83 | r.Method == HttpMethod.Post && r.RequestUri.ToString().StartsWith(instance.Uri)), 84 | ItExpr.IsAny()) 85 | .ReturnsAsync(httpResponse); 86 | 87 | var httpClient = new HttpClient(mockHandler.Object); 88 | 89 | using (TestCorrelator.CreateContext()) 90 | { 91 | var mastodonService = new MastodonService(httpClient); 92 | mastodonService.SetInstance(instance); 93 | 94 | // Act 95 | await mastodonService.DeleteBookmark(new Bookmark 96 | { 97 | Id = "123456" 98 | }); 99 | 100 | // Assert 101 | var logs = TestCorrelator.GetLogEventsFromCurrentContext(); 102 | Assert.IsNotNull(logs); 103 | var logEvents = logs.ToList(); 104 | Assert.AreEqual(2, logEvents.Count); 105 | var logMessage = logEvents.Where(e => e.Level == LogEventLevel.Warning).ToList()[0]; 106 | Assert.AreEqual(LogEventLevel.Warning, logMessage.Level); 107 | Assert.IsTrue(logMessage.MessageTemplate.ToString().Contains("Couldn't delete bookmark")); 108 | Assert.IsTrue(logMessage.Properties.TryGetValue("StatusCode", out var statusCodeValue)); 109 | var statusCode = (HttpStatusCode?)((ScalarValue)statusCodeValue).Value; 110 | Assert.AreEqual(httpResponse.StatusCode, statusCode); 111 | } 112 | } 113 | [TestMethod] 114 | public async Task MastodonService_Failed_To_Delete_Bookmark_403_Forbidden() 115 | { 116 | // Arrange 117 | var httpResponse = new HttpResponseMessage(); 118 | httpResponse.StatusCode = HttpStatusCode.Forbidden; 119 | var instance = new Instance 120 | { 121 | Uri = "https://localhost:3000" 122 | }; 123 | 124 | Mock mockHandler = new(); 125 | mockHandler.Protected() 126 | .Setup>("SendAsync", 127 | ItExpr.Is(r => 128 | r.Method == HttpMethod.Post && r.RequestUri.ToString().StartsWith(instance.Uri)), 129 | ItExpr.IsAny()) 130 | .ReturnsAsync(httpResponse); 131 | 132 | var httpClient = new HttpClient(mockHandler.Object); 133 | 134 | using (TestCorrelator.CreateContext()) 135 | { 136 | var mastodonService = new MastodonService(httpClient); 137 | mastodonService.SetInstance(instance); 138 | 139 | // Act 140 | await mastodonService.DeleteBookmark(new Bookmark 141 | { 142 | Id = "123456" 143 | }); 144 | 145 | // Assert 146 | var logs = TestCorrelator.GetLogEventsFromCurrentContext(); 147 | Assert.IsNotNull(logs); 148 | var logEvents = logs.ToList(); 149 | Assert.AreEqual(2, logEvents.Count); 150 | var logMessage = logEvents.Where(e => e.Level == LogEventLevel.Warning).ToList()[0]; 151 | Assert.AreEqual(LogEventLevel.Warning, logMessage.Level); 152 | Assert.IsTrue(logMessage.MessageTemplate.ToString().Contains("403 Forbidden")); 153 | } 154 | } 155 | [TestMethod] 156 | public async Task MastodonService_GetBookmarks_Success_Empty_List() 157 | { 158 | // Arrange 159 | var expectedBookmarkList = new List(); 160 | string json = JsonConvert.SerializeObject(expectedBookmarkList); 161 | 162 | var httpResponse = new HttpResponseMessage(); 163 | httpResponse.StatusCode = HttpStatusCode.OK; 164 | httpResponse.Content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json); 165 | var instance = new Instance 166 | { 167 | Uri = "https://localhost:3000" 168 | }; 169 | 170 | Mock mockHandler = new(); 171 | mockHandler.Protected() 172 | .Setup>("SendAsync", 173 | ItExpr.Is(r => 174 | r.Method == HttpMethod.Get && r.RequestUri.ToString().StartsWith(instance.Uri)), 175 | ItExpr.IsAny()) 176 | .ReturnsAsync(httpResponse); 177 | 178 | var httpClient = new HttpClient(mockHandler.Object); 179 | 180 | using (TestCorrelator.CreateContext()) 181 | { 182 | var mastodonService = new MastodonService(httpClient); 183 | mastodonService.SetInstance(instance); 184 | 185 | // Act 186 | var result = await mastodonService.GetBookmarks(); 187 | 188 | // Assert 189 | var logs = TestCorrelator.GetLogEventsFromCurrentContext(); 190 | Assert.IsNotNull(logs); 191 | var logEvents = logs.ToList(); 192 | Assert.AreEqual(1, logEvents.Count); 193 | var logMessage = logEvents[0]; 194 | Assert.AreEqual(LogEventLevel.Debug, logMessage.Level); 195 | 196 | Assert.AreEqual(0, result.Count); 197 | } 198 | } 199 | [TestMethod] 200 | public async Task MastodonService_GetBookmarks_Success_Non_Empty_List() 201 | { 202 | // Arrange 203 | var expectedBookmarkList = new List 204 | { 205 | new(), 206 | new() 207 | }; 208 | string json = JsonConvert.SerializeObject(expectedBookmarkList); 209 | 210 | var httpResponse = new HttpResponseMessage(); 211 | httpResponse.StatusCode = HttpStatusCode.OK; 212 | httpResponse.Content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json); 213 | var instance = new Instance 214 | { 215 | Uri = "https://localhost:3000" 216 | }; 217 | 218 | Mock mockHandler = new(); 219 | mockHandler.Protected() 220 | .Setup>("SendAsync", 221 | ItExpr.Is(r => 222 | r.Method == HttpMethod.Get && r.RequestUri.ToString().StartsWith(instance.Uri)), 223 | ItExpr.IsAny()) 224 | .ReturnsAsync(httpResponse); 225 | 226 | var httpClient = new HttpClient(mockHandler.Object); 227 | 228 | using (TestCorrelator.CreateContext()) 229 | { 230 | var mastodonService = new MastodonService(httpClient); 231 | mastodonService.SetInstance(instance); 232 | 233 | // Act 234 | var result = await mastodonService.GetBookmarks(); 235 | 236 | // Assert 237 | var logs = TestCorrelator.GetLogEventsFromCurrentContext(); 238 | Assert.IsNotNull(logs); 239 | var logEvents = logs.ToList(); 240 | Assert.AreEqual(1, logEvents.Count); 241 | var logMessage = logEvents[0]; 242 | Assert.AreEqual(LogEventLevel.Debug, logMessage.Level); 243 | 244 | Assert.AreEqual(2, result.Count); 245 | } 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /tests/BookmarkSync.Infrastructure.Tests/Services/Pinboard/PinboardBookmarkingServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using BookmarkSync.Core.Entities; 3 | using Moq; 4 | using Moq.Protected; 5 | 6 | namespace BookmarkSync.Infrastructure.Tests.Services.Pinboard; 7 | 8 | [TestClass] 9 | public class PinboardBookmarkingServiceTests 10 | { 11 | [TestInitialize] 12 | public void Init() 13 | { 14 | var config = new Dictionary 15 | { 16 | { 17 | "App:Bookmarking:Service", "Pinboard" 18 | }, 19 | { 20 | "App:Bookmarking:ApiToken", "token123456" 21 | } 22 | }; 23 | var configuration = new ConfigurationBuilder() 24 | .AddInMemoryCollection(config) 25 | .Build(); 26 | IConfigManager configManager = new ConfigManager(configuration); 27 | _configManager = configManager; 28 | } 29 | private IConfigManager _configManager; 30 | private readonly string _pinboardUri = "https://api.pinboard.in"; 31 | [TestMethod] 32 | public async Task Pinboard_Save_Success() 33 | { 34 | // Arrange 35 | var httpResponse = new HttpResponseMessage(); 36 | httpResponse.StatusCode = HttpStatusCode.OK; 37 | 38 | Mock mockHandler = new(); 39 | mockHandler.Protected() 40 | .Setup>("SendAsync", 41 | ItExpr.Is(r => 42 | r.Method == HttpMethod.Get && r.RequestUri.ToString() 43 | .StartsWith(_pinboardUri)), 44 | ItExpr.IsAny()) 45 | .ReturnsAsync(httpResponse); 46 | 47 | var httpClient = new HttpClient(mockHandler.Object); 48 | var bookmarkingService = BookmarkingService.GetBookmarkingService(_configManager, httpClient); 49 | var bookmark = new Bookmark 50 | { 51 | Uri = "https://example.com" 52 | }; 53 | 54 | // Act 55 | var result = await bookmarkingService.Save(bookmark); 56 | 57 | // Assert 58 | Assert.IsNotNull(result); 59 | Assert.IsTrue(result.IsSuccessStatusCode); 60 | } 61 | [TestMethod] 62 | public async Task Pinboard_Save_Success_Long_Title() 63 | { 64 | // Arrange 65 | var httpResponse = new HttpResponseMessage(); 66 | httpResponse.StatusCode = HttpStatusCode.OK; 67 | 68 | Mock mockHandler = new(); 69 | mockHandler.Protected() 70 | .Setup>("SendAsync", 71 | ItExpr.Is(r => 72 | r.Method == HttpMethod.Get && r.RequestUri.ToString() 73 | .StartsWith(_pinboardUri)), 74 | ItExpr.IsAny()) 75 | .ReturnsAsync(httpResponse); 76 | 77 | var httpClient = new HttpClient(mockHandler.Object); 78 | var bookmarkingService = BookmarkingService.GetBookmarkingService(_configManager, httpClient); 79 | var bookmark = new Bookmark 80 | { 81 | Uri = "https://example.com", 82 | // ReSharper disable StringLiteralTypo 83 | Content = 84 | "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus suscipit, urna quis consectetur sodales, ante enim auctor leo, ut tincidunt nibh tortor ac magna. Aenean suscipit tincidunt tincidunt. Curabitur et eros elit. Duis consequat felis justo, sit amet semper est scelerisque ac. Aenean ac. " 85 | // ReSharper restore StringLiteralTypo 86 | }; 87 | 88 | // Act 89 | var result = await bookmarkingService.Save(bookmark); 90 | 91 | // Assert 92 | Assert.IsNotNull(result); 93 | Assert.IsTrue(result.IsSuccessStatusCode); 94 | } 95 | } 96 | --------------------------------------------------------------------------------