Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
2ff595a3ef |
|||
|
30bcb070d9 |
|||
|
689b1a48c2 |
|||
|
e72df234bc |
|||
|
b157dce4e4 |
|||
|
97b350be2d |
|||
|
ed8f41bd4a |
|||
|
650e5f5e30 |
|||
|
0728d2a3f7 |
|||
|
f1c23965b2 |
|||
|
a131a6ddf8 |
158 changed files with 61684 additions and 324 deletions
1
.gitattributes
vendored
1
.gitattributes
vendored
|
|
@ -1,5 +1,6 @@
|
|||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
*.onnx binary
|
||||
|
||||
# Custom for Visual Studio
|
||||
*.cs diff=csharp
|
||||
|
|
|
|||
4
.vscode/launch.json
vendored
4
.vscode/launch.json
vendored
|
|
@ -17,8 +17,7 @@
|
|||
"program": "${workspaceFolder}/src/PostIt/PostIt.Desktop/bin/Debug/net10.0/PostIt.Desktop.dll",
|
||||
"env": {
|
||||
"POSTIT_SETTINGS_JSON": "/home/paul/Workspace/yavsc/src/PostIt/PostIt/postit-settings.json"
|
||||
},
|
||||
"preLaunchTask": "dotnet: build-postit-desktop"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Android Debug",
|
||||
|
|
@ -57,7 +56,6 @@
|
|||
"request": "launch",
|
||||
"projectPath": "${workspaceFolder}/src/Yavsc.Blogs/Yavsc.Blogs.csproj"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "Test PostIt.Android launch (Xamarin.UITest)",
|
||||
"type": "coreclr",
|
||||
|
|
|
|||
17
.vscode/tasks.json
vendored
17
.vscode/tasks.json
vendored
|
|
@ -1,7 +1,6 @@
|
|||
{
|
||||
"version": "2.0.0",
|
||||
"isRoot": true,
|
||||
|
||||
"tasks": [
|
||||
{
|
||||
"label": "build-debug-android",
|
||||
|
|
@ -136,6 +135,22 @@
|
|||
"group": {
|
||||
"kind": "build"
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "build-postit-browser",
|
||||
"type": "process",
|
||||
"problemMatcher": ["$msCompile"],
|
||||
"isBuildCommand": true,
|
||||
"isTestCommand": false,
|
||||
"isBackground": true,
|
||||
"command": "dotnet",
|
||||
"args": ["build", "/property:GenerateFullPaths=true"],
|
||||
"options": {
|
||||
"cwd": "src/PostIt/PostIt.Browser"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build"
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
20
CHANGELOG.md
20
CHANGELOG.md
|
|
@ -5,6 +5,25 @@
|
|||
|
||||
### Added
|
||||
|
||||
* [Resource usage] Let users with the `Administrator` role continue making requests after reaching their consumption quota, while still recording their usage.
|
||||
|
||||
* [PostIt.Android/Podcasts] Add an optional persisted background blur for camera preview and broadcasting. Run the bundled PPHumanSeg model locally with ONNX Runtime and composite with OpenGL before encoding; preserve the unfiltered pipeline for calls and OBS.
|
||||
|
||||
* [Podcasts/OBS/PostIt] Replace the MediaMTX relay with direct encrypted SRT ingestion managed by [FFmpeg.NET](https://github.com/cmxl/FFmpeg.NET). Reserve bounded UDP listeners on activation, display a secret SRT URL with an empty OBS stream-key field, start on received media, preserve revocation/expiry/quotas and authenticated replay, and invalidate in-memory activations after restart. Remove relay configuration and its authentication endpoint; update deployment, privacy and real-media regressions. Use separate request connections to the shared SQLite test database for reliable concurrent podcast requests.
|
||||
|
||||
* [Podcasts/OBS/PostIt] Add opt-in MediaMTX RTMPS ingestion for programmed emissions, activated explicitly from PostIt with one-time scoped, expiring and revocable keys. Start on publisher connection, remux H.264/AAC into the existing authenticated segments and MP4 replay workflow, bound concurrency/duration/buffering, enforce consumption and effective disk quotas, account storage with deletion refunds, and report owner-only ingest errors. Add relay configuration, installation instructions and real synthetic RTMP/RTMPS-to-replay regressions, including active revocation.
|
||||
|
||||
* [Yavsc/PostIt/Privacy] Close and pseudonymize withdrawn accounts, cancel PayPal subscriptions before confirming withdrawal, erase managed personal files, avatars and podcasts, and reject old sessions across hosts. Purge eligible technical payment residues one year after effective withdrawal automatically and through a confirmed administrator-only PostIt action; preserve accounting records separately. Clarify the privacy policy, recipients, third-party integrations, withdrawal failures and deployment responsibilities. Make the unique email constraint mutable to support pseudonymization without deleting accounting identities.
|
||||
|
||||
* [Yavsc/API/Blogs/PostIt] Refund tracked storage points when personal files are deleted or replaced, and when generated PDFs are replaced. Persist per-file accounting receipts, preserve them on rename, reject refunds for untracked legacy files, and allow deletion at the consumption limit without refunding API/CPU/transfer costs. Update CGU and installation instructions.
|
||||
|
||||
* [Yavsc/PostIt/PayPal] Add monthly Découverte (EUR 1 excluding VAT) and Premium (EUR 2 excluding VAT) resource subscriptions, charged at EUR 1.20 / EUR 2.40 including 20% VAT. Confirmed monthly PayPal payments erase up to one / three default quotas, carry two thirds of unused monthly credit without expiry, and preserve historical counters. Add persistent idempotent payment credits, refund reconciliation, authenticated Web subscription/cancellation pages, verified REST webhooks, PostIt links and balances, migration and updated CGU.
|
||||
* [Yavsc/PostIt/Subscriptions] Align new users' free quota with the existing 500 MiB database default; grant twice that standard quota for Discovery (1,000 MiB) and five times for Premium (2,500 MiB) during confirmed paid monthly periods, including their remainder after cancellation. Restore the user's base quota after expiry or refund without deleting files, refuse uploads beyond available space before writing, and expose the effective quota in profile and usage responses.
|
||||
* [PostIt/API/Blogs/Yavsc.Org] Compute cumulative resource consumption in configurable points per API call, recorded CPU second, MiB transferred and MiB added to storage, with backend-defined defaults, a default 1,000-point limit and per-user overrides. Serialize accounting and known-cost admission across PostgreSQL hosts, count streamed HTTP bodies, reject further consuming operations with HTTP 429, and check personal uploads before writing. Keep usage/session access available, display the indicator and balance in PostIt, and publish linked CGU explaining the rule and after-measurement enforcement.
|
||||
* [PostIt.Android] Embed managed assemblies in APKs by default, including Debug builds launched outside the Makefile, to prevent the native startup abort "No assemblies found" when fast-deployment files are absent.
|
||||
* [PostIt] Remove the redundant "Post detail" heading and its grid row from the blog editor, including the compact layout.
|
||||
* [PostIt/Android] Combine system-bar/cutout safe-area insets with actual keyboard overlap at the root, instead of replacing Avalonia's automatic safe-area padding with keyboard-only padding. Preserve the toolbar, session banner, attachments and status controls; place article details beside the editor during landscape keyboard input. Only on Android, temporarily hide the title input while editing in compact mode with the keyboard open, restoring it on keyboard closure or focus change without modifying the draft. Verify visible controls outside native system bars, at least three editor lines and the editor's bottom above IME insets.
|
||||
* [PostIt/Android] Remove the outer blog-page scroll container so the editor, reader and list retain bounded viewports. Keep the editing caret visible after the keyboard resizes the editor; request the native keyboard on a touch tap, not a scroll gesture, without cycling focus or replacing the selection. Add headless regressions and a debug-only device check using a local synthetic article.
|
||||
* [PostIt.Android] Fix the crash when starting a podcast broadcast with camera preview active: detach preview callbacks using the retained surface holder, before deferred native-view destruction, without accessing an already disposed SurfaceView. Add a device regression covering preview teardown followed by local capture.
|
||||
* [PostIt.Android] Keep the screen awake during foreground video playback and release it on pause, stop, completion, error or video teardown. Add a persisted, default-off podcast option to keep the screen awake during camera preview/live capture; release on capture end and allow normal sleep in the background without changing the broadcast service. Include native LibVLC libraries when building with a single runtime identifier (including physical ARM64 phones).
|
||||
* [PostIt/Podcasts] Preview the selected camera before starting a live broadcast, without creating an emission, encoding files or opening the microphone. Release preview on stop, navigation, logout and Android backgrounding, and before starting the actual broadcast. Correct Android portrait orientation for rear and front cameras: subtract the sensor rotation already carried by Camera2's SurfaceTexture matrix, reversing the remaining rotation when that matrix mirrors the front camera (it was turned 90° or upside down); track display changes for both preview and encoded frames, preserving aspect ratio and fixed live stream dimensions.
|
||||
|
|
@ -14,6 +33,7 @@
|
|||
* [PostIt/Calls] Support direct IPv6 SRTP calls using global, ULA and loopback addresses, shared endpoint validation, IPv6 UDP sockets and bracketed reception URLs. Exclude scoped/link-local, multicast, unspecified and IPv4-mapped addresses; verify real bidirectional IPv6 audio/video, wrong-key rejection and port lifecycle with LibVLC.
|
||||
* [PostIt/Calls] Allow directly assigned public IPv4 addresses for direct SRTP calls, alongside LAN/VPN and loopback addresses. Share unicast validation between interface discovery, media and server signaling; continue rejecting unspecified, link-local, multicast, reserved and IPv6 addresses. Keep explicit address-disclosure consent and no automatic NAT traversal.
|
||||
* [PostIt] Update bundled settings with the default podcast title, camera/microphone preferences and French language selection.
|
||||
* [Performers] Allow performer profiles without a business registration for amateur use; keep activities available while disabling estimate issuance and new invoicing in the UI and server APIs.
|
||||
|
||||
## [1.0.8-rc34] - unstable
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="DotMarkdown" Version="0.3.0" />
|
||||
<PackageVersion Include="xFFmpeg.NET" Version="7.4.0" />
|
||||
<PackageVersion Include="Markdig" Version="1.4.1" />
|
||||
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="10.0.13" />
|
||||
<PackageVersion Include="HigginsSoft.IdentityServer8" Version="$(IdentityServer8Version)" />
|
||||
|
|
|
|||
341
INSTALL.md
341
INSTALL.md
|
|
@ -76,8 +76,321 @@ login callback, updating and uninstallation on Windows with a standard
|
|||
(non-administrator) account. Installer compilation alone does not validate
|
||||
these Windows runtime behaviours.
|
||||
|
||||
## Resource consumption and CGU
|
||||
|
||||
### Account withdrawal and payment retention
|
||||
|
||||
Apply the `AccountWithdrawal` migration before deploying all three hosts. It adds
|
||||
withdrawal timestamps and replaces the immutable alternate email key with a
|
||||
required unique email index, preserving uniqueness while allowing pseudonymization.
|
||||
Do not run the withdrawal flow until every host uses the matching backend.
|
||||
|
||||
Yavsc.Org must have write/delete access to the same managed volumes as API/Blogs:
|
||||
`Site:UserFilesRoot`, `Site:Avatars` and `Podcast:RootPath`.
|
||||
Use absolute paths shared across processes; defaults relative to application
|
||||
directories are not shared automatically. Accounting files under `Site:Bills`
|
||||
are not erased by withdrawal. Symbolic links in managed user directories are
|
||||
refused rather than followed.
|
||||
|
||||
The account is blocked before cancellation/erasure, and withdrawal is only
|
||||
confirmed when these operations and pseudonymization succeed. On an explicit
|
||||
failure, an administrator must fix the cause and retry the existing administrative
|
||||
withdrawal action. Ensure no live upload/encoding operation is still writing to
|
||||
the user's volumes during withdrawal; drain such operations before retrying.
|
||||
|
||||
The Org hosted worker purges eligible technical payment records at startup and
|
||||
checks at most every minute, with an earlier wake-up for a known anniversary.
|
||||
Monitor errors and service availability: scheduled processing
|
||||
cannot ensure an exact wall-clock deletion while the host is stopped. At least
|
||||
one Org instance must run, and an external operations process must enforce the
|
||||
one-year retention deadline during prolonged downtime. PostIt administrators can
|
||||
also confirm and run `POST /api/v1/administration/payment-residues/purge`.
|
||||
The report counts accounts, subscriptions, monthly payments, donations and legacy
|
||||
PayPal payments. Active accounts and unfinished withdrawals are never purged.
|
||||
No new subscription credits may be granted after withdrawal begins.
|
||||
|
||||
Invoice payments, invoices and other legal accounting records are excluded.
|
||||
Define and publish the actual accounting, logs and backup retention policy for
|
||||
the deployment, verify configured providers and international-transfer safeguards,
|
||||
and prevent withdrawn data from being reactivated by backup restoration.
|
||||
|
||||
Configure the **same** `ResourceUsage` section on Yavsc.Api, Yavsc.Blogs and
|
||||
Yavsc.Org. API and Blogs must also use the same application database.
|
||||
All three hosts and configuration templates inherit the backend defaults
|
||||
from [ResourceUsageOptions](src/Yavsc.Server/Settings/ResourceUsageOptions.cs).
|
||||
Deploy matching backend versions across hosts. The public CGU renders the
|
||||
effective coefficients and limit. The default limit is 1,000 points.
|
||||
The following is an example explicit override, not a duplicate of defaults.
|
||||
Use the account's immutable user ID (`sub`), not its login, for overrides:
|
||||
|
||||
```json
|
||||
{
|
||||
"ResourceUsage": {
|
||||
"ApiCallWeight": 0.2,
|
||||
"CpuSecondWeight": 0.1,
|
||||
"BandwidthMbWeight": 0.05,
|
||||
"StorageMbWeight": 0.5,
|
||||
"DefaultLimit": 1000,
|
||||
"UserLimits": {
|
||||
"example-account-id": 20000
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Environment variables follow ASP.NET's convention, for example
|
||||
`ResourceUsage__DefaultLimit` and
|
||||
`ResourceUsage__UserLimits__example-account-id`. Restart all three services
|
||||
after changing the rule. Invalid weights or limits fail startup.
|
||||
Existing cumulative `ResourceUsageRecords` are reused, and changing weights
|
||||
recalculates their gross indicator. Apply the `ResourceSubscriptions`
|
||||
migration before deploying any of the three hosts: it adds the credit
|
||||
balance and subscription/payment tables without clearing existing counters.
|
||||
|
||||
Consumption is in **points**, independent of `EstimatedCompensation` and
|
||||
currency. Counters have no automatic reset. Storage means cumulative
|
||||
instrumented writes less individually tracked bytes removed or replaced,
|
||||
not total filesystem occupancy. Replacements refund their tracked previous
|
||||
size and charge the new size. Legacy files without an individual receipt
|
||||
receive no refund; storage counters never become negative. Deletion remains
|
||||
available at the consumption limit, but API/transfer/CPU costs are not refunded.
|
||||
Apply the `RefundableResourceStorage` migration before deployment; its empty
|
||||
receipt table deliberately does not infer provenance from historical counters.
|
||||
Renames preserve receipts and repeated PDF generation replaces the previous
|
||||
tracked volume rather than charging the whole file again. The historical CPU counter is
|
||||
instrumented elapsed processing time, not exhaustive CPU profiling.
|
||||
|
||||
Authenticated HTTP operations are admitted atomically against known costs
|
||||
(API call and declared request body). Personal-file uploads additionally
|
||||
check their aggregate storage cost before writing. Response bytes and
|
||||
unknown-length request bodies are measured through counting streams, and
|
||||
remaining costs are recorded after execution, including failed requests.
|
||||
PostgreSQL transaction-scoped advisory locks serialize admission and
|
||||
accounting for each user across hosts. In-flight operations can exceed the
|
||||
limit through costs unknown at admission; subsequent operations return
|
||||
HTTP 429 with `resource_quota_exceeded` Problem Details. No permanent account
|
||||
suspension or strict running-operation interruption is performed.
|
||||
|
||||
`GET /api/v1/resource-usage/me` returns `Consumption`, `ConsumptionLimit`,
|
||||
`RemainingConsumption` and `IsQuotaReached`, alongside existing counters.
|
||||
It also returns `GrossConsumption`, `AppliedCredits` and `CreditBalance`.
|
||||
`Consumption` is the gross indicator less acquired credits, floored at zero.
|
||||
`RemainingConsumption` includes both unused free quota and carried credit.
|
||||
Usage consultation (including the role-protected admin overview), login,
|
||||
session refresh and the CGU remain accessible without consuming quota.
|
||||
The quota does not measure local PostIt resources, direct peer calls or
|
||||
WebSocket traffic. HTTP upload size limits and disk quotas still apply.
|
||||
|
||||
The public page `/Home/CGU` describes the effective rule and default limit
|
||||
(and the individual limit for a signed-in user). It is linked from the Web
|
||||
footer and PostIt's **About** page, using the configured authentication
|
||||
authority. PostIt displays consumption and remaining points in **My profile**
|
||||
and the administration usage views.
|
||||
|
||||
### Monthly resource subscriptions (PayPal REST)
|
||||
|
||||
The free registration keeps the configured cumulative quota without a
|
||||
monthly reset. Discovery costs EUR 1 excluding VAT (EUR 1.20 including 20%
|
||||
VAT) per month; Premium costs EUR 2 excluding VAT (EUR 2.40 including VAT).
|
||||
Every **confirmed payment** grants up to one / three default quotas,
|
||||
respectively, with renewal on the UTC monthly anniversary of the PayPal
|
||||
start date. The pack allowance is captured at subscription creation, not
|
||||
multiplied by an individual user's quota override.
|
||||
|
||||
At reconciliation, old carried credit is used first; the new allowance
|
||||
erases remaining net usage. Two thirds of the unused allowance are added
|
||||
to permanent carried credit, rounded down to eight decimal places.
|
||||
Old carried credit never loses another third and survives cancellation.
|
||||
Example: 400 points of usage and 1,000 new points erase 400 and carry
|
||||
400; an idle Premium month carries 2,000 points.
|
||||
Counters are never deleted. Pending/failed payments give no credit.
|
||||
Refunds (including partial refunds) revoke the corresponding award once.
|
||||
|
||||
Discovery grants **twice `Constants.DefaultFSQ`** (1,000 MiB), and Premium
|
||||
**five times `Constants.DefaultFSQ`** (2,500 MiB) of disk space during each
|
||||
confirmed, non-reversed paid monthly period. Free registrations use the standard quota.
|
||||
The reference is the standard free quota (500 MiB), not an individual's
|
||||
administratively adjusted `DiskQuota`. That base quota is never overwritten.
|
||||
New user objects now use the existing 500 MiB database default rather than
|
||||
the former 512 MiB CLR initializer; existing accounts retain their stored quota.
|
||||
Cancellation retains the disk allowance through the UTC anniversary ending
|
||||
the paid period; expiry or refund restores the base quota without deleting
|
||||
existing files. Uploads exceeding available space are refused before writing.
|
||||
The maximum size of one file and separate podcast limits are unchanged.
|
||||
Pending/failed payments grant no disk bonus. Apply the
|
||||
`ResourceSubscriptions`, `PremiumDiskQuota` and `DiscoveryDiskQuota` EF migrations to the shared
|
||||
database before deploying any host. Profile and usage responses expose the
|
||||
effective disk quota; usage also exposes `PremiumDiskQuotaUntil` and `DiscoveryDiskQuotaUntil`.
|
||||
When paid periods overlap, Premium takes precedence until its expiry, then
|
||||
any still-paid Discovery period applies.
|
||||
|
||||
Configure only **Yavsc.Org** for PayPal subscriptions. API and Blogs need
|
||||
the migrated shared database and matching resource weights, not PayPal
|
||||
credentials. Existing Classic donation settings remain unchanged.
|
||||
Use the existing `PayPal:Mode`, `PayPal:ClientId` and `PayPal:ClientSecret`
|
||||
REST settings; keep credentials in user-secrets or environment variables.
|
||||
|
||||
```json
|
||||
{
|
||||
"ResourceSubscriptions": {
|
||||
"DiscoveryPlanId": "P-REPLACEWITHDISCOVERYPLAN",
|
||||
"PremiumPlanId": "P-REPLACEWITHPREMIUMPLAN",
|
||||
"WebhookId": "REPLACEWITHWEBHOOKID",
|
||||
"DiscoveryPriceExcludingTax": 1,
|
||||
"PremiumPriceExcludingTax": 2,
|
||||
"VatPercent": 20
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Before enabling checkout, create a PayPal subscription product and two
|
||||
**ACTIVE** billing plans in the same REST app and environment:
|
||||
one indefinite `REGULAR` cycle with `interval_unit: MONTH`,
|
||||
`interval_count: 1`, `total_cycles: 0`, and EUR `fixed_price.value`
|
||||
of **1.20** / **2.40** respectively. These are **already VAT-inclusive**
|
||||
amounts: do not add PayPal tax, setup fees, trials, quantity support or
|
||||
shipping fees. Disable billing outstanding balances in the plans
|
||||
(`auto_bill_outstanding: false`) to avoid bundling missed installments
|
||||
into an amount that does not match one monthly payment.
|
||||
Checkout checks the configured plan against its expected TTC amount and
|
||||
refuses automatic collection of outstanding balances.
|
||||
Numerically invalid pricing fails startup; missing plan IDs/webhook/
|
||||
credentials returns an explicit unavailable error instead of a fake success.
|
||||
|
||||
Register the HTTPS endpoint
|
||||
`https://<Yavsc.Org host>/ResourceSubscription/Notify` in that REST app.
|
||||
Subscribe to `BILLING.SUBSCRIPTION.ACTIVATED`, `UPDATED`, `CANCELLED`,
|
||||
`SUSPENDED`, `EXPIRED`, `PAYMENT.FAILED`, and `PAYMENT.SALE.COMPLETED`,
|
||||
`REFUNDED`, `REVERSED` (the lifecycle events use the
|
||||
`BILLING.SUBSCRIPTION.` prefix). Set the returned webhook ID in configuration.
|
||||
The server verifies the signature through PayPal, then fetches the bound
|
||||
subscription and transaction history; it never grants credit from an
|
||||
unverified webhook or the browser return. Payment IDs and monthly cycles
|
||||
are unique, and the same per-user PostgreSQL lock serializes usage and awards.
|
||||
Delayed notifications take effect on the usage measured when reconciled.
|
||||
|
||||
Users manage subscriptions at `/ResourceSubscription`, linked from the Web
|
||||
footer and PostIt's About/profile pages. A browser Web login may be required
|
||||
independently of PostIt's session. Create/refresh/cancel require antiforgery
|
||||
tokens and ownership; the management page remains available at the quota.
|
||||
**Refresh payments** reconciles missed notifications and historical refunds.
|
||||
Cancellation is confirmed with PayPal, not merely recorded locally.
|
||||
Only one non-terminal subscription is allowed per account.
|
||||
An uncertain creation is retried with its same PayPal request ID for at
|
||||
most 24 hours; an older unresolved creation requires merchant-side review
|
||||
before allowing a second checkout. Do not delete that record and retry
|
||||
without checking PayPal for a possible existing agreement.
|
||||
|
||||
Run a real Sandbox approval, first payment, renewal, repeated webhook,
|
||||
refund and cancellation before enabling production. The repository tests
|
||||
use synthetic PayPal transports and do not validate merchant credentials
|
||||
or PayPal account eligibility.
|
||||
|
||||
## Podcast live broadcasts and replays
|
||||
|
||||
### OBS Studio for planned emissions
|
||||
|
||||
OBS publishes **encrypted SRT directly to Yavsc.Api**, using
|
||||
[FFmpeg.NET](https://github.com/cmxl/FFmpeg.NET) (`xFFmpeg.NET`) to manage FFmpeg
|
||||
listeners. No MediaMTX, external media server, authentication callback or RTMPS
|
||||
certificate is required. Install **FFmpeg with libsrt, H.264/AAC and MPEG-TS
|
||||
support** on the **single Yavsc.Api media host** (`ffmpeg -h protocol=srt`).
|
||||
OBS supports SRT in its Custom streaming service; see its
|
||||
[SRT streaming guide](https://obsproject.com/kb/srt-protocol-streaming-guide).
|
||||
This replaces the previous RTMP/RTMPS transport, not the authenticated playback API.
|
||||
|
||||
Apply the `PodcastObsIngestion` migration on the shared database. Configure
|
||||
`Podcast:Obs` on **Yavsc.Api only**, for example:
|
||||
|
||||
```json
|
||||
{
|
||||
"Podcast": {
|
||||
"Obs": {
|
||||
"Enabled": true,
|
||||
"ServerUrl": "srt://obs.example.org",
|
||||
"ListenAddress": "0.0.0.0",
|
||||
"FirstPort": 10000,
|
||||
"PortCount": 16,
|
||||
"ActivationMinutes": 30,
|
||||
"MaxDurationMinutes": 120,
|
||||
"MaxConcurrentBroadcasts": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`ServerUrl` contains the public SRT host only, with no port, path, secret or query.
|
||||
`ListenAddress` is a literal local IP address (IPv4 or IPv6); configure a matching
|
||||
public address family. Open/forward **UDP 10000-10015** in this example.
|
||||
An ordinary HTTP reverse proxy does not carry SRT. NAT forwarding must preserve
|
||||
the advertised port numbers.
|
||||
One FFmpeg process and UDP port are reserved per armed emission, even before OBS
|
||||
connects. Armed and running emissions share `MaxConcurrentBroadcasts`; an exhausted
|
||||
pool returns HTTP 503. The port range is bounded (at most 128 ports) and must be
|
||||
large enough for the concurrency limit. Listener startup failure is reported,
|
||||
not treated as successful activation.
|
||||
Keep process arguments and credentials accessible only to the service administrator.
|
||||
Limit ingress bitrate at the network level and in OBS: application quotas are checked
|
||||
on completed media segments, not on every incoming packet.
|
||||
|
||||
In PostIt:
|
||||
|
||||
1. Prepare an emission and select it.
|
||||
2. Choose **Activer OBS / renouveler la cle**.
|
||||
3. In OBS, select **Parametres > Stream > Service : Personnalise**, then copy
|
||||
the complete displayed **secret SRT URL as Server**, leaving **Stream Key empty**.
|
||||
The URL includes caller mode, a random passphrase and enforced AES-256 encryption.
|
||||
Use **H.264 video**, **AAC audio**,
|
||||
a **2-second keyframe interval** and a bitrate producing segments below 8 MiB.
|
||||
4. Start streaming in OBS before the activation expires. The actual emission
|
||||
starts when the first complete media segment arrives, even if the scheduled date is later.
|
||||
No camera capture in PostIt is required; PostIt may be closed afterwards.
|
||||
5. Stop OBS or choose **Revoquer OBS et arreter le diffuseur** in PostIt.
|
||||
Committed segments remain available and the normal MP4 worker prepares replay.
|
||||
|
||||
Passphrases are scoped to one emission, displayed once and rotated on activation.
|
||||
Only a SHA-256 hash and lifecycle metadata are stored in the database; FFmpeg needs
|
||||
the actual passphrase in memory/process arguments for SRT encryption. It is never
|
||||
included in status responses or persisted in PostIt. Navigation/logout clears
|
||||
the displayed secret URL but does not revoke a running
|
||||
external emission. Revocation is available at the consumption limit.
|
||||
After disconnect, restart or timeout, the emission ends rather than silently
|
||||
resuming under a new publisher: prepare a new emission for another broadcast.
|
||||
An API restart invalidates all old activations; an unstarted emission must be
|
||||
activated again because its passphrase is not recoverable from the database.
|
||||
An invalid handshake can end an armed listener; no podcast is created without
|
||||
media, and the owner can activate again. Rate-limit connection attempts at deployment.
|
||||
|
||||
The worker manages bounded FFmpeg.NET listener/remuxing tasks. It rejects ended,
|
||||
deleted, revoked or withdrawn accounts and caps
|
||||
concurrent captures and duration (the lower of planned duration and configured
|
||||
maximum). Revocation cancels the corresponding FFmpeg process and frees its port.
|
||||
Activation expiry stops unused listeners. The passphrase is required before SRT
|
||||
media can be received; a stream name alone is not an authentication mechanism.
|
||||
Committed segments are charged as transferred and stored MiB under the same
|
||||
consumption rule; their storage receipts are refunded on podcast deletion.
|
||||
OBS storage counts towards the user's effective disk quota and the existing
|
||||
podcast media limits. Pending capture files are monitored and bounded; enforcement
|
||||
can overshoot by one polling interval of incoming data. Processing errors are
|
||||
reported in the owner-only OBS status endpoint, without exposing secret URLs or
|
||||
FFmpeg diagnostics. Monitor process/cleanup failures and drain active captures
|
||||
before maintenance. An API outage ends ingestion and requires reactivation.
|
||||
|
||||
The normal HTTP API authenticates playback; OBS stream credentials never grant
|
||||
viewer or account access.
|
||||
|
||||
For the real media regressions, install FFmpeg with libsrt and run:
|
||||
|
||||
```bash
|
||||
dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj --filter-class '*PodcastObsTests'
|
||||
```
|
||||
|
||||
The tests launch loopback-only listeners, generate synthetic H.264/AAC media
|
||||
with FFmpeg, verify encrypted SRT through FFmpeg.NET, wrong-passphrase rejection,
|
||||
revocation during streaming,
|
||||
AAC audio, HLS segments, MP4 replay and refund,
|
||||
then stops its own processes and removes its temporary files.
|
||||
|
||||
PostIt Desktop's home page provides **Podcasts : directs et replays**.
|
||||
Install LibVLC 3 with the `livehttp`, MPEG-TS, x264 and AAC plugins on the
|
||||
Desktop machine. Windows capture uses DirectShow; Linux uses V4L2 and the
|
||||
|
|
@ -100,7 +413,8 @@ replays; only the broadcaster can upload, complete or delete their podcast.
|
|||
Media is not anonymous and no access token is included in a playback URL.
|
||||
|
||||
Configure Yavsc.Api's `Podcast` section (or environment variables such as
|
||||
`Podcast__RootPath`). No database migration is needed. Install **FFmpeg 5+
|
||||
`Podcast__RootPath`). The base media store needs no database migration;
|
||||
planned emissions and OBS require their migrations documented above. Install **FFmpeg 5+
|
||||
on the API server** (with `concatf`, MPEG-TS, MP4 and AAC bitstream-filter
|
||||
support; for Debian/Ubuntu: `apt-get install ffmpeg`). The API runtime stage
|
||||
in the main Dockerfile includes it. Only stream-copy remuxing is performed,
|
||||
|
|
@ -131,7 +445,10 @@ Defaults allow 8 MiB per segment (also the HTTP endpoint's hard limit),
|
|||
1 GiB retained per owner, 7,200 segments per episode and 100 episodes per
|
||||
owner. At the target two-second segment duration, this is roughly four hours
|
||||
per episode; the byte quota can be reached earlier. Podcast quotas are
|
||||
separate from the legacy user-files `DiskQuota`. Deleting an ended podcast
|
||||
separate from the legacy user-files `DiskQuota` for native HTTP capture.
|
||||
OBS source segments also count towards the user's effective disk quota and
|
||||
instrumented consumption; the additional MP4 is counted only by `MaxOwnerBytes`.
|
||||
Deleting an ended podcast
|
||||
releases its podcast quota. Reverse proxies must allow an 8 MiB PUT body
|
||||
and forward Authorization, Range and Content-Range on every API request/response.
|
||||
The retained MPEG-TS **and** the additional MP4 count toward `MaxOwnerBytes`.
|
||||
|
|
@ -209,6 +526,22 @@ at IDR frames, with timestamps used for segment durations. Closed segments
|
|||
enter the same ordered upload/retry/quota/replay pipeline as desktop.
|
||||
Devices without a supported camera/encoder report a startup error.
|
||||
|
||||
On Android, the optional **Flouter le decor de la camera** setting is saved
|
||||
locally and disabled by default. It applies to podcast camera preview and
|
||||
recording, not calls or OBS. The bundled Apache-2.0 PPHumanSeg model from
|
||||
[OpenCV Zoo](https://github.com/opencv/opencv_zoo/tree/main/models/human_segmentation_pphumanseg)
|
||||
is evaluated locally with ONNX Runtime; OpenGL blends the blurred background
|
||||
before the native encoder. No frames are sent to a third party. Segmentation
|
||||
is imperfect and can expose parts of the background: check the preview and do
|
||||
not rely on it to conceal sensitive surroundings. Performance and battery
|
||||
usage depend on the device. Capture stops on processing failure.
|
||||
The bundled `pphumanseg.onnx` is the OpenCV Zoo 2023mar model (SHA-256
|
||||
`552d8a984054e59b5d773d24b9b12022b22046ceb2bbc4c9aaeaceb36a9ddf24`);
|
||||
its Apache-2.0 license is included beside the asset.
|
||||
ONNX Runtime's Android library requires API 24; it is only loaded by the
|
||||
podcast capture code, which is restricted to API 26 and later. The manifest
|
||||
override preserves PostIt's existing API 23 minimum for its other features.
|
||||
|
||||
Camera frames are rotated through an OpenGL surface before encoding, so both
|
||||
live playback and replays have upright pixels without relying on rotation
|
||||
metadata (not supported by the MPEG-TS recorder). The sensor, front/rear lens
|
||||
|
|
@ -305,6 +638,6 @@ You'll need to send e-mail ... using smtp and the provider of your choice, see t
|
|||
|
||||
### Google
|
||||
|
||||
I'll have to make with it, a least a moment, it needs a *service account*, and some setup,
|
||||
in the `appsettings.*.json` file, and
|
||||
I'll have to make with it, a least a moment, it needs a *service account*, and some setup,
|
||||
in the `appsettings.*.json` file, and
|
||||
the execution environment variable GOOGLE_APPLICATION_CREDENTIALS to a value pointing the json description file for the Google Service account.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
{
|
||||
"ResourceUsage": {
|
||||
"UserLimits": {}
|
||||
},
|
||||
"Site": {
|
||||
"Authority": "https://preprod-yavsc.$DOMAIN",
|
||||
"Audience": ["api"],
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
{
|
||||
"ResourceUsage": {
|
||||
"UserLimits": {}
|
||||
},
|
||||
"Site": {
|
||||
"Title": "Yavsc Blogs",
|
||||
"Description": "A collection of blogs about software development, technology, and programming.",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,15 @@
|
|||
{
|
||||
"ResourceSubscriptions": {
|
||||
"DiscoveryPlanId": "",
|
||||
"PremiumPlanId": "",
|
||||
"WebhookId": "",
|
||||
"DiscoveryPriceExcludingTax": 1,
|
||||
"PremiumPriceExcludingTax": 2,
|
||||
"VatPercent": 20
|
||||
},
|
||||
"ResourceUsage": {
|
||||
"UserLimits": {}
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information"
|
||||
|
|
@ -18,7 +29,8 @@
|
|||
"ApiUrl": "https://preprod-api.$DOMAIN",
|
||||
"CorsAllowedOrigins": [
|
||||
"https://preprod-blogs.$DOMAIN",
|
||||
"https://preprod-api.$DOMAIN"
|
||||
"https://preprod-api.$DOMAIN",
|
||||
"https://postit.$DOMAIN"
|
||||
],
|
||||
"Banner": "/images/banner-dewang.jpg",
|
||||
"Owner": {
|
||||
|
|
|
|||
|
|
@ -12,6 +12,13 @@
|
|||
|
||||
## Surface : un code-base, trois front-ends
|
||||
|
||||
Le projet Android active `EmbedAssembliesIntoApk` par défaut, y compris en
|
||||
Debug : un APK installé directement doit contenir les assemblies .NET,
|
||||
sans dépendre des fichiers de Fast Deployment sous `files/.__override__`.
|
||||
Sans elles, le runtime Android abandonne avant de charger l'interface
|
||||
avec « No assemblies found ». Le Makefile conserve également ce réglage
|
||||
explicite pour ses commandes de compilation.
|
||||
|
||||
```
|
||||
┌────────────────────────┐
|
||||
│ PostIt (lib) │
|
||||
|
|
@ -92,6 +99,13 @@ de chaque téléphone.
|
|||
|
||||
## Administration et profil personnel
|
||||
|
||||
Le quota disque renvoyé par le profil est le quota effectif : Découverte donne
|
||||
deux fois et Premium cinq fois le quota gratuit standard durant la mensualité confirmée payée,
|
||||
y compris après résiliation jusqu'à son échéance UTC. Ensuite, ou après
|
||||
remboursement, le quota habituel reprend sans suppression des fichiers.
|
||||
Les téléversements dépassant l'espace disponible sont refusés avant écriture.
|
||||
La taille maximale par fichier et les quotas podcast restent inchangés.
|
||||
|
||||
L'accueil présente un seul accès **Administration**, visible et exécutable
|
||||
uniquement pour le rôle exact `Administrator`. `SessionStatusViewModel.RefreshAsync`
|
||||
lit les rôles dans `GET account/me` après le rafraîchissement de session ;
|
||||
|
|
@ -112,6 +126,37 @@ indépendamment de la visibilité du bouton dans PostIt.
|
|||
endpoints `account/me` pour lire et enregistrer les informations personnelles.
|
||||
Elle affiche aussi `resource-usage/me`, sans appeler la liste des usages
|
||||
globaux. Une indisponibilité de l'usage n'empêche pas la gestion du profil.
|
||||
La consommation est chargée avant le profil, pour rester consultable même
|
||||
si une opération de gestion reçoit un refus de quota. L'administration
|
||||
charge également les usages avant ses autres outils et les conserve sur
|
||||
un refus HTTP 429, tant que le rôle administrateur est toujours présent.
|
||||
|
||||
L'indicateur est exprimé en points selon les coefficients effectifs du
|
||||
backend, présentés dans les CGU. Le stockage correspond aux volumes
|
||||
instrumentés ajoutés, moins les volumes individuellement suivis supprimés
|
||||
ou remplacés. Les anciens fichiers sans suivi ne sont pas remboursés.
|
||||
La suppression reste disponible au seuil ; CPU, appels API et transferts
|
||||
ne sont pas remboursés. Les renommages conservent le suivi individuel.
|
||||
Le profil et les vues d'administration affichent le seuil effectif, le
|
||||
solde et l'atteinte du quota, indépendamment de l'estimation financière.
|
||||
La section serveur `ResourceUsage` configure les coefficients et les
|
||||
seuils individuels ; voir [INSTALL.md](../../INSTALL.md#resource-consumption-and-cgu).
|
||||
Le contrôle admet les coûts connus puis constate les coûts restants :
|
||||
il bloque les opérations suivantes, sans interrompre strictement celles
|
||||
déjà en cours.
|
||||
|
||||
La page **À propos** ouvre les CGU dédiées de PostIt et de Yavsc sur
|
||||
`Home/CGU` auprès de l'autorité configurée, y compris sans session.
|
||||
Cette page publique présente les coefficients réellement configurés,
|
||||
la période cumulée, le seuil et les limites de la mesure.
|
||||
**Mon profil** et **À propos** proposent aussi un lien vers
|
||||
`ResourceSubscription` sur cette même autorité. La souscription mensuelle
|
||||
et la résiliation PayPal utilisent la session Web et des formulaires
|
||||
antiforgery ; PostIt ne stocke ni identifiant marchand ni secret PayPal.
|
||||
Le profil affiche la consommation brute, l'usage effacé et le crédit
|
||||
reporté, en plus de l'indicateur net. Les crédits Découverte/Premium ne
|
||||
suppriment pas les compteurs : les paiements confirmés sont rapprochés
|
||||
par Yavsc.Org et leur déduction est appliquée aussi au quota API/Blogs.
|
||||
|
||||
### Outils d'administration du site
|
||||
|
||||
|
|
@ -376,7 +421,8 @@ de modifier cette répartition. La liste et l'article défilent séparément.
|
|||
|
||||
Lorsque la largeur de la fenêtre atteint ou dépasse sa hauteur, le lecteur
|
||||
ou l'éditeur passe à gauche (deux tiers de la largeur par défaut), et
|
||||
l'en-tête, la recherche, les commandes et la liste passent à droite.
|
||||
l'en-tête, la recherche et la liste passent à droite ; les commandes
|
||||
restent dans la barre de navigation.
|
||||
Le séparateur devient vertical. En portrait, la disposition verticale
|
||||
revient sans recréer les contrôles ni perdre le brouillon.
|
||||
Le seuil utilise les dimensions clientes de la fenêtre, indépendamment
|
||||
|
|
@ -395,6 +441,41 @@ dépasser le viewport pour que les barres automatiques s'activent.
|
|||
Ne pas placer cette grille dans un `StackPanel` vertical ou un
|
||||
`ScrollViewer` de page, qui lui donnerait une hauteur de mesure illimitée.
|
||||
|
||||
Après un redimensionnement de la zone de texte (notamment à l'ouverture du
|
||||
clavier Android avec `AdjustResize`), l'éditeur remet le curseur dans son
|
||||
viewport après la mise en page, uniquement s'il garde le focus. Un toucher
|
||||
dans la zone éditable demande aussi le clavier via le pont natif Android,
|
||||
sans retirer puis redonner le focus ni modifier la sélection. Les autres
|
||||
plateformes conservent leur gestion habituelle du clavier.
|
||||
|
||||
`MainView` compose les marges de `TopLevel.InsetsManager` (barres système
|
||||
et découpes) avec le recouvrement réel indiqué par `TopLevel.InputPane`,
|
||||
car le clavier ne redimensionne pas toujours la fenêtre Android en mode
|
||||
edge-to-edge. Si `AdjustResize` a déjà réduit la fenêtre, cette réserve
|
||||
ne soustrait pas une seconde fois la hauteur du clavier. La racine gère
|
||||
explicitement ces marges et désactive `TopLevel.AutoSafeAreaPadding` pour
|
||||
éviter deux propriétaires du même padding. Ne pas remplacer les marges
|
||||
système par un padding contenant uniquement la hauteur du clavier.
|
||||
En disposition large, tant que le clavier est ouvert et que l'article
|
||||
garde le focus, son titre et ses pièces jointes passent dans
|
||||
une colonne à côté du texte. La barre de commandes, la bannière de session
|
||||
et le statut restent visibles. La disposition habituelle revient à la
|
||||
fermeture du clavier ou au changement de focus, sans recréer le brouillon.
|
||||
Sous Android uniquement, le champ du titre est masqué pendant la saisie
|
||||
compacte avec le clavier ouvert, en portrait comme en paysage ; il réapparaît à la fermeture du clavier
|
||||
ou quand le focus quitte l'article. Sa valeur n'est jamais effacée.
|
||||
|
||||
En Debug Android, `fr.pschneider.postit.MarkdownEditorTestActivity` ouvre
|
||||
un billet synthétique local, vérifie au moins trois lignes visibles et
|
||||
le bas de l'éditeur au-dessus des insets natifs du clavier et les contrôles
|
||||
en dehors des barres système,
|
||||
ferme puis rouvre le clavier par toucher sans perte de focus. Le résultat
|
||||
est écrit dans `files/markdown-editor-test-result.txt`. Ce test nécessite
|
||||
Android 11 ou plus pour vérifier les insets du clavier ; il ne publie
|
||||
aucun billet et retire sa page à la fin.
|
||||
L'extra booléen `landscape=true` force le paysage pendant le test et restaure
|
||||
l'orientation demandée précédemment à la fin.
|
||||
|
||||
## Navigation
|
||||
|
||||
Le host de navigation est un `NavigationPage x:Name="NavRoot"`
|
||||
|
|
|
|||
|
|
@ -39,5 +39,6 @@
|
|||
<PackageVersion Include="Xamarin.AndroidX.Lifecycle.Process" Version="2.11.0.1" />
|
||||
<PackageVersion Include="Xamarin.UITest" Version="4.4.2" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.13" />
|
||||
<PackageVersion Include="Microsoft.ML.OnnxRuntime" Version="1.31.1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
|
|||
203
src/PostIt/PostIt.Android/Assets/PodcastBackground/LICENSE
Normal file
203
src/PostIt/PostIt.Android/Assets/PodcastBackground/LICENSE
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
22323
src/PostIt/PostIt.Android/Assets/PodcastBackground/pphumanseg.onnx
Normal file
22323
src/PostIt/PostIt.Android/Assets/PodcastBackground/pphumanseg.onnx
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -44,6 +44,28 @@ public class MainActivity : AvaloniaMainActivity
|
|||
|
||||
private void OnScreenAwakeChanged() => RunOnUiThread(UpdateScreenAwake);
|
||||
|
||||
internal static void ShowSoftKeyboard()
|
||||
{
|
||||
if (Current is not { } activity || !IsForeground)
|
||||
{
|
||||
global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a foreground activity.");
|
||||
return;
|
||||
}
|
||||
|
||||
activity.RunOnUiThread(() =>
|
||||
{
|
||||
if (activity.CurrentFocus is not { } view
|
||||
|| activity.GetSystemService(InputMethodService) is not global::Android.Views.InputMethods.InputMethodManager inputMethod)
|
||||
{
|
||||
global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a focused native view and input method.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!inputMethod.ShowSoftInput(view, global::Android.Views.InputMethods.ShowFlags.Implicit))
|
||||
global::Android.Util.Log.Warn("PostIt", "The input method did not accept the keyboard activation request.");
|
||||
});
|
||||
}
|
||||
|
||||
private void UpdateScreenAwake()
|
||||
{
|
||||
if (Window is not { } window) return;
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ internal static class PlatformBootstrap
|
|||
|
||||
Platform.CreateServiceProvider = AndroidServiceProvider.GetOrCreate;
|
||||
Platform.BackgroundChatService = AndroidBackgroundChatService.Instance;
|
||||
Platform.ShowSoftKeyboard = MainActivity.ShowSoftKeyboard;
|
||||
Platform.TryGetCurrentLocationAsync = AndroidCurrentLocationProvider.TryGetCurrentLocationAsync;
|
||||
Platform.CreateVideoSurface = (player, replay) => new AndroidVideoSurface(player, replay);
|
||||
if (System.OperatingSystem.IsAndroidVersionAtLeast(26))
|
||||
|
|
@ -35,6 +36,8 @@ internal static class PlatformBootstrap
|
|||
Platform.RequestPodcastPermissionsAsync = AndroidPodcastCapture.RequestPermissionsAsync;
|
||||
Platform.CreatePodcastCaptureAsync = AndroidPodcastCapture.StartAsync;
|
||||
Platform.CreatePodcastPreviewAsync = AndroidPodcastCapture.StartPreviewAsync;
|
||||
Platform.CreateBlurredPodcastCaptureAsync = AndroidPodcastCapture.StartBlurredAsync;
|
||||
Platform.CreateBlurredPodcastPreviewAsync = AndroidPodcastCapture.StartBlurredPreviewAsync;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
<ApplicationVersion>1</ApplicationVersion>
|
||||
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
|
||||
<AndroidPackageFormat>apk</AndroidPackageFormat>
|
||||
<EmbedAssembliesIntoApk>true</EmbedAssembliesIntoApk>
|
||||
<AndroidEnableProfiledAot>false</AndroidEnableProfiledAot>
|
||||
<!-- LibVLC's native package targets inspect the plural RID property. -->
|
||||
<RuntimeIdentifiers Condition="'$(RuntimeIdentifiers)' == '' and '$(RuntimeIdentifier)' != ''">$(RuntimeIdentifier)</RuntimeIdentifiers>
|
||||
|
|
@ -24,6 +25,7 @@
|
|||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia.Android" />
|
||||
<PackageReference Include="LibVLCSharp" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" />
|
||||
<PackageReference Include="VideoLAN.LibVLC.Android" />
|
||||
<PackageReference Include="Xamarin.AndroidX.Core.SplashScreen" />
|
||||
<PackageReference Include="Xamarin.AndroidX.Browser" />
|
||||
|
|
@ -32,9 +34,11 @@
|
|||
<ProjectReference Include="..\PostIt\PostIt.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
|
||||
<Compile Include="..\PostIt.Tests\AndroidMarkdownEditorTestActivity.cs" Link="Tests\AndroidMarkdownEditorTestActivity.cs" />
|
||||
<Compile Include="..\PostIt.Tests\AndroidChatServiceTestActivity.cs" Link="Tests\AndroidChatServiceTestActivity.cs" />
|
||||
<Compile Include="..\PostIt.Tests\AndroidPodcastCaptureTestActivity.cs" Link="Tests\AndroidPodcastCaptureTestActivity.cs" />
|
||||
<Compile Include="..\PostIt.Tests\AndroidCameraFrameRotationTestActivity.cs" Link="Tests\AndroidCameraFrameRotationTestActivity.cs" />
|
||||
<Compile Include="..\PostIt.Tests\AndroidPodcastBlurTestActivity.cs" Link="Tests\AndroidPodcastBlurTestActivity.cs" />
|
||||
<Compile Include="..\PostIt.Tests\AndroidLanCallTestActivity.cs" Link="Tests\AndroidLanCallTestActivity.cs" />
|
||||
<Compile Include="..\PostIt.Tests\AndroidScreenAwakeTestActivity.cs" Link="Tests\AndroidScreenAwakeTestActivity.cs" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools" android:installLocation="auto">
|
||||
<!-- ONNX Runtime is loaded only for podcast capture, which requires API 26. -->
|
||||
<uses-sdk tools:overrideLibrary="ai.onnxruntime" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Android.Graphics;
|
||||
using Android.Content;
|
||||
using Android.Opengl;
|
||||
using Android.OS;
|
||||
using Android.Views;
|
||||
|
|
@ -17,9 +18,32 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
attribute vec2 textureCoordinate;
|
||||
uniform mat4 textureMatrix;
|
||||
varying vec2 uv;
|
||||
varying vec2 maskUv;
|
||||
void main() {
|
||||
gl_Position = vec4(position, 0.0, 1.0);
|
||||
uv = (textureMatrix * vec4(textureCoordinate, 0.0, 1.0)).xy;
|
||||
maskUv = (position + vec2(1.0)) * 0.5;
|
||||
}
|
||||
""";
|
||||
private const string BlurFragmentShader = """
|
||||
#extension GL_OES_EGL_image_external : require
|
||||
precision mediump float;
|
||||
uniform samplerExternalOES cameraTexture;
|
||||
uniform sampler2D personMask;
|
||||
uniform vec2 blurStep;
|
||||
varying vec2 uv;
|
||||
varying vec2 maskUv;
|
||||
void main() {
|
||||
vec4 original = texture2D(cameraTexture, uv);
|
||||
vec4 blurred = vec4(0.0);
|
||||
for (int x = -2; x <= 2; x++) {
|
||||
for (int y = -2; y <= 2; y++) {
|
||||
blurred += texture2D(cameraTexture, uv + vec2(float(x), float(y)) * blurStep);
|
||||
}
|
||||
}
|
||||
blurred /= 25.0;
|
||||
float person = texture2D(personMask, maskUv).r;
|
||||
gl_FragColor = mix(blurred, original, person);
|
||||
}
|
||||
""";
|
||||
private const string FragmentShader = """
|
||||
|
|
@ -59,7 +83,17 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
private int _program;
|
||||
private int _textureId;
|
||||
private int _matrixLocation;
|
||||
private int _blurProgram;
|
||||
private int _blurMatrixLocation;
|
||||
private int _maskTexture;
|
||||
private int _samplingTexture;
|
||||
private int _framebuffer;
|
||||
private IPodcastPersonSegmenter? _segmenter;
|
||||
private ByteBuffer? _samplingBuffer;
|
||||
private ByteBuffer? _maskBuffer;
|
||||
private byte[]? _samplingBytes;
|
||||
private bool _rendering;
|
||||
private bool _blackout;
|
||||
private bool _disposed;
|
||||
private int _rotation;
|
||||
private int _remainingRotation = -1;
|
||||
|
|
@ -76,12 +110,13 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
}
|
||||
|
||||
internal static async Task<AndroidCameraFrameRotator> CreateAsync(
|
||||
Surface? encoderSurface, int width, int height, int rotation, Action<Exception> failed)
|
||||
Surface? encoderSurface, int width, int height, int rotation, Action<Exception> failed, Context? blurContext = null,
|
||||
Func<Context, IPodcastPersonSegmenter>? segmenterFactory = null)
|
||||
{
|
||||
var rotator = new AndroidCameraFrameRotator(failed);
|
||||
try
|
||||
{
|
||||
await rotator.InvokeAsync(() => rotator.Initialize(encoderSurface, width, height, rotation));
|
||||
await rotator.InvokeAsync(() => rotator.Initialize(encoderSurface, width, height, rotation, blurContext, segmenterFactory));
|
||||
return rotator;
|
||||
}
|
||||
catch
|
||||
|
|
@ -91,7 +126,8 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
}
|
||||
}
|
||||
|
||||
private void Initialize(Surface? encoderSurface, int width, int height, int rotation)
|
||||
private void Initialize(Surface? encoderSurface, int width, int height, int rotation, Context? blurContext,
|
||||
Func<Context, IPodcastPersonSegmenter>? segmenterFactory)
|
||||
{
|
||||
_rotation = rotation;
|
||||
_inputWidth = width;
|
||||
|
|
@ -126,7 +162,7 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
if (!EGL14.EglMakeCurrent(_display, _window, _window, _context))
|
||||
throw EglError("Activation du contexte EGL");
|
||||
|
||||
_program = CreateProgram();
|
||||
_program = CreateProgram(FragmentShader);
|
||||
var ids = new int[1];
|
||||
GLES20.GlGenTextures(1, ids, 0);
|
||||
_textureId = ids[0];
|
||||
|
|
@ -142,6 +178,7 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
BindAttribute("textureCoordinate", _coordinates);
|
||||
_matrixLocation = GLES20.GlGetUniformLocation(_program, "textureMatrix");
|
||||
GLES20.GlUniform1i(GLES20.GlGetUniformLocation(_program, "cameraTexture"), 0);
|
||||
if (blurContext is not null) InitializeBlur(blurContext, segmenterFactory);
|
||||
_outputWidth = rotation is 90 or 270 ? height : width;
|
||||
_outputHeight = rotation is 90 or 270 ? width : height;
|
||||
GLES20.GlViewport(0, 0, _outputWidth, _outputHeight);
|
||||
|
|
@ -181,6 +218,82 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
}
|
||||
}
|
||||
|
||||
private void InitializeBlur(Context context, Func<Context, IPodcastPersonSegmenter>? segmenterFactory)
|
||||
{
|
||||
_segmenter = segmenterFactory is null ? new PodcastPersonSegmenter(context) : segmenterFactory(context);
|
||||
_samplingBytes = new byte[PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size * 4];
|
||||
_samplingBuffer = ByteBuffer.AllocateDirect(_samplingBytes.Length)
|
||||
?? throw new InvalidOperationException("Tampon de segmentation indisponible.");
|
||||
_maskBuffer = ByteBuffer.AllocateDirect(PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size)
|
||||
?? throw new InvalidOperationException("Tampon du masque indisponible.");
|
||||
_blurProgram = CreateProgram(BlurFragmentShader);
|
||||
GLES20.GlUseProgram(_blurProgram);
|
||||
_blurMatrixLocation = GLES20.GlGetUniformLocation(_blurProgram, "textureMatrix");
|
||||
GLES20.GlUniform1i(GLES20.GlGetUniformLocation(_blurProgram, "cameraTexture"), 0);
|
||||
GLES20.GlUniform1i(GLES20.GlGetUniformLocation(_blurProgram, "personMask"), 1);
|
||||
GLES20.GlUniform2f(GLES20.GlGetUniformLocation(_blurProgram, "blurStep"), 4f / _inputWidth, 4f / _inputHeight);
|
||||
var ids = new int[1];
|
||||
GLES20.GlGenTextures(1, ids, 0);
|
||||
_maskTexture = ids[0];
|
||||
GLES20.GlActiveTexture(GLES20.GlTexture1);
|
||||
GLES20.GlBindTexture(GLES20.GlTexture2d, _maskTexture);
|
||||
SetTextureParameters();
|
||||
GLES20.GlTexImage2D(GLES20.GlTexture2d, 0, GLES20.GlLuminance,
|
||||
PodcastPersonSegmenter.Size, PodcastPersonSegmenter.Size, 0, GLES20.GlLuminance, GLES20.GlUnsignedByte, null);
|
||||
GLES20.GlGenTextures(1, ids, 0);
|
||||
_samplingTexture = ids[0];
|
||||
GLES20.GlBindTexture(GLES20.GlTexture2d, _samplingTexture);
|
||||
SetTextureParameters();
|
||||
GLES20.GlTexImage2D(GLES20.GlTexture2d, 0, GLES20.GlRgba,
|
||||
PodcastPersonSegmenter.Size, PodcastPersonSegmenter.Size, 0, GLES20.GlRgba, GLES20.GlUnsignedByte, null);
|
||||
GLES20.GlGenFramebuffers(1, ids, 0);
|
||||
_framebuffer = ids[0];
|
||||
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, _framebuffer);
|
||||
GLES20.GlFramebufferTexture2D(GLES20.GlFramebuffer, GLES20.GlColorAttachment0,
|
||||
GLES20.GlTexture2d, _samplingTexture, 0);
|
||||
if (GLES20.GlCheckFramebufferStatus(GLES20.GlFramebuffer) != GLES20.GlFramebufferComplete)
|
||||
throw new InvalidOperationException("Surface de segmentation OpenGL indisponible.");
|
||||
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, 0);
|
||||
GLES20.GlBindTexture(GLES20.GlTexture2d, _maskTexture);
|
||||
GLES20.GlActiveTexture(GLES20.GlTexture0);
|
||||
GLES20.GlUseProgram(_program);
|
||||
BindAttribute("position", _vertices!);
|
||||
BindAttribute("textureCoordinate", _coordinates!);
|
||||
CheckGl();
|
||||
}
|
||||
|
||||
private static void SetTextureParameters()
|
||||
{
|
||||
GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlLinear);
|
||||
GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlLinear);
|
||||
GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
|
||||
GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
|
||||
}
|
||||
|
||||
private void UpdatePersonMask()
|
||||
{
|
||||
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, _framebuffer);
|
||||
GLES20.GlViewport(0, 0, PodcastPersonSegmenter.Size, PodcastPersonSegmenter.Size);
|
||||
GLES20.GlDrawArrays(GLES20.GlTriangleStrip, 0, 4);
|
||||
_samplingBuffer!.Position(0);
|
||||
GLES20.GlReadPixels(0, 0, PodcastPersonSegmenter.Size, PodcastPersonSegmenter.Size,
|
||||
GLES20.GlRgba, GLES20.GlUnsignedByte, _samplingBuffer);
|
||||
CheckGl();
|
||||
_samplingBuffer.Position(0);
|
||||
_samplingBuffer.Get(_samplingBytes!);
|
||||
var mask = _segmenter!.Segment(_samplingBytes!);
|
||||
_maskBuffer!.Position(0);
|
||||
_maskBuffer.Put(mask);
|
||||
_maskBuffer.Position(0);
|
||||
GLES20.GlActiveTexture(GLES20.GlTexture1);
|
||||
GLES20.GlBindTexture(GLES20.GlTexture2d, _maskTexture);
|
||||
GLES20.GlTexSubImage2D(GLES20.GlTexture2d, 0, 0, 0, PodcastPersonSegmenter.Size,
|
||||
PodcastPersonSegmenter.Size, GLES20.GlLuminance, GLES20.GlUnsignedByte, _maskBuffer);
|
||||
GLES20.GlActiveTexture(GLES20.GlTexture0);
|
||||
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, 0);
|
||||
CheckGl();
|
||||
}
|
||||
|
||||
private void DrawFrame(SurfaceTexture texture)
|
||||
{
|
||||
if (!_rendering) return;
|
||||
|
|
@ -191,6 +304,21 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
texture.UpdateTexImage();
|
||||
var presentationTime = _clock.GetPresentationTime(texture.Timestamp, Java.Lang.JavaSystem.NanoTime());
|
||||
if (presentationTime is null) return;
|
||||
if (_blackout)
|
||||
{
|
||||
if (!_previewOnly)
|
||||
{
|
||||
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, 0);
|
||||
GLES20.GlViewport(0, 0, _outputWidth, _outputHeight);
|
||||
GLES20.GlClearColor(0, 0, 0, 1);
|
||||
GLES20.GlClear(GLES20.GlColorBufferBit);
|
||||
CheckGl();
|
||||
if (!EGLExt.EglPresentationTimeANDROID(_display, _window, presentationTime.Value)
|
||||
|| !EGL14.EglSwapBuffers(_display, _window))
|
||||
throw EglError("Envoi d'une image noire a l'encodeur");
|
||||
}
|
||||
return;
|
||||
}
|
||||
texture.GetTransformMatrix(_textureMatrix);
|
||||
var remainingRotation = CameraFrameOrientation.GetRemainingRotation(_rotation, _textureMatrix);
|
||||
if (_remainingRotation != remainingRotation)
|
||||
|
|
@ -204,6 +332,14 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
$"Camera texture transform: [{FirstTextureTransform}], sensor/display rotation={_rotation}, remaining rotation={remainingRotation}");
|
||||
}
|
||||
GLES20.GlUniformMatrix4fv(_matrixLocation, 1, false, _textureMatrix, 0);
|
||||
if (_segmenter is not null) UpdatePersonMask();
|
||||
if (_blurProgram != 0)
|
||||
{
|
||||
GLES20.GlUseProgram(_blurProgram);
|
||||
BindAttribute("position", _vertices!);
|
||||
BindAttribute("textureCoordinate", _coordinates!);
|
||||
GLES20.GlUniformMatrix4fv(_blurMatrixLocation, 1, false, _textureMatrix, 0);
|
||||
}
|
||||
if (!_previewOnly)
|
||||
{
|
||||
SetViewport(_outputWidth, _outputHeight);
|
||||
|
|
@ -215,11 +351,25 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
throw EglError("Envoi de l'image a l'encodeur");
|
||||
}
|
||||
DrawPreview();
|
||||
if (_blurProgram != 0)
|
||||
{
|
||||
GLES20.GlUseProgram(_program);
|
||||
BindAttribute("position", _vertices!);
|
||||
BindAttribute("textureCoordinate", _coordinates!);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_rendering = false;
|
||||
_failed(new InvalidOperationException("Rotation de la capture Android impossible.", ex));
|
||||
if (_blackout)
|
||||
{
|
||||
_rendering = false;
|
||||
global::Android.Util.Log.Error("PostIt.Podcast", $"Arret de la capture impossible : {ex}");
|
||||
}
|
||||
else
|
||||
{
|
||||
_blackout = true;
|
||||
_failed(new InvalidOperationException("Traitement de la capture Android impossible.", ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -315,14 +465,14 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
throw new InvalidOperationException($"Compilation du shader camera impossible : {error}");
|
||||
}
|
||||
|
||||
private static int CreateProgram()
|
||||
private static int CreateProgram(string fragmentSource)
|
||||
{
|
||||
var vertex = CreateShader(GLES20.GlVertexShader, VertexShader);
|
||||
var fragment = 0;
|
||||
var program = 0;
|
||||
try
|
||||
{
|
||||
fragment = CreateShader(GLES20.GlFragmentShader, FragmentShader);
|
||||
fragment = CreateShader(GLES20.GlFragmentShader, fragmentSource);
|
||||
program = GLES20.GlCreateProgram();
|
||||
GLES20.GlAttachShader(program, vertex);
|
||||
GLES20.GlAttachShader(program, fragment);
|
||||
|
|
@ -384,6 +534,13 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
|
|||
_texture?.Release();
|
||||
_texture?.Dispose();
|
||||
_listener?.Dispose();
|
||||
_segmenter?.Dispose();
|
||||
_samplingBuffer?.Dispose();
|
||||
_maskBuffer?.Dispose();
|
||||
if (_framebuffer != 0) GLES20.GlDeleteFramebuffers(1, [_framebuffer], 0);
|
||||
if (_samplingTexture != 0) GLES20.GlDeleteTextures(1, [_samplingTexture], 0);
|
||||
if (_maskTexture != 0) GLES20.GlDeleteTextures(1, [_maskTexture], 0);
|
||||
if (_blurProgram != 0) GLES20.GlDeleteProgram(_blurProgram);
|
||||
if (_program != 0) GLES20.GlDeleteProgram(_program);
|
||||
if (_textureId != 0) GLES20.GlDeleteTextures(1, [_textureId], 0);
|
||||
_vertices?.Dispose();
|
||||
|
|
|
|||
|
|
@ -85,9 +85,16 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
|
||||
public static async Task<IPodcastCapture> StartAsync(string camera, string? microphone, string directory, CancellationToken ct)
|
||||
=> await StartCoreAsync(camera, microphone,
|
||||
(stream, token) => new TransportStreamCapture(directory).RunAsync(stream, token), null, null, ct);
|
||||
(stream, token) => new TransportStreamCapture(directory).RunAsync(stream, token), null, null, ct, false);
|
||||
|
||||
public static async Task<IPodcastCapture> StartPreviewAsync(string camera, CancellationToken ct)
|
||||
public static async Task<IPodcastCapture> StartBlurredAsync(string camera, string? microphone, string directory, CancellationToken ct)
|
||||
=> await StartCoreAsync(camera, microphone,
|
||||
(stream, token) => new TransportStreamCapture(directory).RunAsync(stream, token), null, null, ct, true);
|
||||
|
||||
public static Task<IPodcastCapture> StartPreviewAsync(string camera, CancellationToken ct) => StartPreviewAsync(camera, ct, false);
|
||||
public static Task<IPodcastCapture> StartBlurredPreviewAsync(string camera, CancellationToken ct) => StartPreviewAsync(camera, ct, true);
|
||||
|
||||
private static async Task<IPodcastCapture> StartPreviewAsync(string camera, CancellationToken ct, bool blur)
|
||||
{
|
||||
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
|
||||
await PodcastPermissions.EnsureAsync(activity, false, ct, notifications: false);
|
||||
|
|
@ -99,7 +106,7 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
Platform.PlaybackSuspending += capture.RequestStop;
|
||||
try
|
||||
{
|
||||
await capture.StartNativeAsync(camera, false, null, null, ct);
|
||||
await capture.StartNativeAsync(camera, false, null, null, ct, blur);
|
||||
return capture;
|
||||
}
|
||||
catch
|
||||
|
|
@ -111,11 +118,11 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
|
||||
internal static Task<IPodcastCapture> StartCallAsync(string camera, string microphone,
|
||||
Func<int, CancellationToken, Task> output, Func<Task> stopOutput, CancellationToken ct) =>
|
||||
StartCoreAsync(camera, microphone, null, output, stopOutput, ct);
|
||||
StartCoreAsync(camera, microphone, null, output, stopOutput, ct, false);
|
||||
|
||||
private static async Task<IPodcastCapture> StartCoreAsync(string camera, string? microphone,
|
||||
Func<Stream, CancellationToken, Task>? output,
|
||||
Func<int, CancellationToken, Task>? pipeOutput, Func<Task>? stopOutput, CancellationToken ct)
|
||||
Func<int, CancellationToken, Task>? pipeOutput, Func<Task>? stopOutput, CancellationToken ct, bool blur)
|
||||
{
|
||||
await RequestPermissionsAsync(microphone, ct);
|
||||
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
|
||||
|
|
@ -133,7 +140,7 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await capture.StartNativeAsync(camera, microphone is not null, output, pipeOutput, ct);
|
||||
await capture.StartNativeAsync(camera, microphone is not null, output, pipeOutput, ct, blur);
|
||||
return capture;
|
||||
}
|
||||
catch
|
||||
|
|
@ -145,16 +152,16 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
|
||||
private async Task StartNativeAsync(string cameraId, bool microphone,
|
||||
Func<Stream, CancellationToken, Task>? output,
|
||||
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct)
|
||||
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct, bool blur)
|
||||
{
|
||||
await _stopGate.WaitAsync(ct);
|
||||
try { await ConfigureNativeAsync(cameraId, microphone, output, pipeOutput, ct); }
|
||||
try { await ConfigureNativeAsync(cameraId, microphone, output, pipeOutput, ct, blur); }
|
||||
finally { _stopGate.Release(); }
|
||||
}
|
||||
|
||||
private async Task ConfigureNativeAsync(string cameraId, bool microphone,
|
||||
Func<Stream, CancellationToken, Task>? output,
|
||||
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct)
|
||||
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct, bool blur)
|
||||
{
|
||||
var manager = GetManager(_context);
|
||||
using var characteristics = manager.GetCameraCharacteristics(cameraId);
|
||||
|
|
@ -205,7 +212,8 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
}
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
|
||||
_rotator = await AndroidCameraFrameRotator.CreateAsync(_surface, size.Width, size.Height, rotation, Fail);
|
||||
_rotator = await AndroidCameraFrameRotator.CreateAsync(_surface, size.Width, size.Height, rotation, Fail,
|
||||
blur ? _context : null);
|
||||
_preview = new AndroidCapturePreview(_rotator);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
|
||||
|
|
|
|||
72
src/PostIt/PostIt.Android/Services/PodcastPersonSegmenter.cs
Normal file
72
src/PostIt/PostIt.Android/Services/PodcastPersonSegmenter.cs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Android.Content;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
|
||||
namespace PostIt.Android.Services;
|
||||
|
||||
internal interface IPodcastPersonSegmenter : IDisposable
|
||||
{
|
||||
byte[] Segment(byte[] rgba);
|
||||
}
|
||||
|
||||
internal sealed class PodcastPersonSegmenter : IPodcastPersonSegmenter
|
||||
{
|
||||
internal const int Size = 192;
|
||||
private const int Pixels = Size * Size;
|
||||
private readonly InferenceSession _session;
|
||||
private readonly RunOptions _runOptions = new();
|
||||
private readonly float[] _input = new float[3 * Pixels];
|
||||
private readonly byte[] _mask = new byte[Pixels];
|
||||
private readonly string _inputName;
|
||||
|
||||
internal PodcastPersonSegmenter(Context context)
|
||||
{
|
||||
using var asset = context.Assets?.Open("PodcastBackground/pphumanseg.onnx")
|
||||
?? throw new InvalidOperationException("Modele de segmentation Android introuvable.");
|
||||
using var model = new MemoryStream();
|
||||
asset.CopyTo(model);
|
||||
using var options = new SessionOptions { IntraOpNumThreads = 2, InterOpNumThreads = 1 };
|
||||
_session = new InferenceSession(model.ToArray(), options);
|
||||
_inputName = _session.InputNames.Single();
|
||||
}
|
||||
|
||||
public byte[] Segment(byte[] rgba)
|
||||
{
|
||||
if (rgba.Length != Pixels * 4) throw new ArgumentException("Image de segmentation invalide.", nameof(rgba));
|
||||
for (var y = 0; y < Size; y++)
|
||||
{
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var pixel = y * Size + x;
|
||||
var source = ((Size - 1 - y) * Size + x) * 4;
|
||||
_input[pixel] = rgba[source] / 127.5f - 1;
|
||||
_input[Pixels + pixel] = rgba[source + 1] / 127.5f - 1;
|
||||
_input[2 * Pixels + pixel] = rgba[source + 2] / 127.5f - 1;
|
||||
}
|
||||
}
|
||||
using var input = OrtValue.CreateTensorValueFromMemory(_input, [1, 3, Size, Size]);
|
||||
using var outputs = _session.Run(_runOptions, new Dictionary<string, OrtValue> { [_inputName] = input }, _session.OutputNames);
|
||||
var result = outputs[0].GetTensorDataAsSpan<float>();
|
||||
if (result.Length != 2 * Pixels) throw new InvalidDataException("Sortie du modele de segmentation invalide.");
|
||||
for (var y = 0; y < Size; y++)
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var pixel = y * Size + x;
|
||||
var background = result[pixel];
|
||||
var person = result[Pixels + pixel];
|
||||
if (!float.IsFinite(background) || !float.IsFinite(person))
|
||||
throw new InvalidDataException("Sortie du modele de segmentation non finie.");
|
||||
_mask[(Size - 1 - y) * Size + x] = person > background ? (byte)255 : (byte)0;
|
||||
}
|
||||
return _mask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_session.Dispose();
|
||||
_runOptions.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@
|
|||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
<PublishTrimmed>false</PublishTrimmed>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia.Browser" />
|
||||
|
|
@ -15,4 +16,4 @@
|
|||
<ItemGroup>
|
||||
<ProjectReference Include="..\PostIt\PostIt.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ sealed class Program
|
|||
public static void Main(string[] args)
|
||||
{
|
||||
Platform.IsPodcastSupported = true;
|
||||
Platform.CreateBrowser = () => new CustomSchemeBrowser("postit://callback");
|
||||
|
||||
CLIOptionHandler.HandleArgs(args);
|
||||
|
||||
// Short-circuit 2nd-instance launches (OS handing us the
|
||||
|
|
|
|||
19
src/PostIt/PostIt.Tests/AboutTermsTests.cs
Normal file
19
src/PostIt/PostIt.Tests/AboutTermsTests.cs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
using PostIt.ViewModels;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
public sealed class AboutTermsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Terms_follow_the_configured_instance_and_changes_to_it()
|
||||
{
|
||||
var settings = new Settings();
|
||||
settings.Authentication.Authority = "https://first.example/";
|
||||
var model = new AboutPageViewModel(settings);
|
||||
Assert.Equal("https://first.example/Home/CGU", model.TermsUri.AbsoluteUri);
|
||||
Assert.Equal("https://first.example/ResourceSubscription", model.SubscriptionsUri.AbsoluteUri);
|
||||
settings.Authentication.Authority = "https://second.example";
|
||||
Assert.Equal("https://second.example/Home/CGU", model.TermsUri.AbsoluteUri);
|
||||
Assert.Equal("https://second.example/ResourceSubscription", model.SubscriptionsUri.AbsoluteUri);
|
||||
}
|
||||
}
|
||||
|
|
@ -15,6 +15,32 @@ namespace PostIt.Tests;
|
|||
|
||||
public class AdministrationAccessTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Profile_quota_failure_keeps_the_consumption_visible_without_enabling_profile_changes()
|
||||
{
|
||||
await using var api = new ProfileTransport("Performer") { ExhaustedQuota = true };
|
||||
var model = new UserProfilePageViewModel(api, usageClient: api.UsageClient);
|
||||
await model.RefreshAsync();
|
||||
Assert.True(model.ResourceUsage?.IsQuotaReached);
|
||||
Assert.False(model.IsProfileLoaded);
|
||||
Assert.False(model.SaveProfileCommand.CanExecute(null));
|
||||
Assert.Contains("resource_quota_exceeded", model.StatusMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Administration_quota_failure_keeps_the_authorized_usage_overview()
|
||||
{
|
||||
await using var api = new ProfileTransport("Administrator");
|
||||
var session = new SessionStatusViewModel { Api = api };
|
||||
await session.RefreshAsync();
|
||||
api.ExhaustedQuota = true;
|
||||
var model = new AdministrationPageViewModel(api, api.UsageClient, session);
|
||||
await model.RefreshAsync();
|
||||
Assert.True(Assert.Single(model.UsageOverview).IsQuotaReached);
|
||||
Assert.Empty(model.Users);
|
||||
Assert.Contains("les usages restent consultables", model.StatusMessage);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData("Moderator", false)]
|
||||
[InlineData("Administrator", true)]
|
||||
|
|
@ -242,6 +268,7 @@ public class AdministrationAccessTests
|
|||
public Task<Me>? PendingProfile { get; set; }
|
||||
public bool FailProfile { get; set; }
|
||||
public bool FailUsage { get; set; }
|
||||
public bool ExhaustedQuota { get; set; }
|
||||
public bool HideIpAddressInCalls { get; set; }
|
||||
public ResourceUsageApiClient UsageClient => new(this, Settings.ApiUrl);
|
||||
|
||||
|
|
@ -268,6 +295,8 @@ public class AdministrationAccessTests
|
|||
object result;
|
||||
if (path.EndsWith("/account/me"))
|
||||
{
|
||||
if (ExhaustedQuota)
|
||||
throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests);
|
||||
if (FailProfile)
|
||||
throw new HttpRequestException("Profile unavailable");
|
||||
result = PendingProfile is not null ? await PendingProfile
|
||||
|
|
@ -277,11 +306,22 @@ public class AdministrationAccessTests
|
|||
{
|
||||
if (FailUsage)
|
||||
throw new HttpRequestException("Usage unavailable");
|
||||
var usage = new ResourceUsageSummary { UserId = "alice-id", UserName = "alice", ApiCalls = 12m };
|
||||
var usage = new ResourceUsageSummary
|
||||
{
|
||||
UserId = "alice-id", UserName = "alice", ApiCalls = 12m,
|
||||
Consumption = ExhaustedQuota ? 10000m : 0.24m,
|
||||
ConsumptionLimit = 10000m,
|
||||
RemainingConsumption = ExhaustedQuota ? 0m : 9999.76m,
|
||||
IsQuotaReached = ExhaustedQuota
|
||||
};
|
||||
result = path.EndsWith("/admin") ? new List<ResourceUsageSummary> { usage } : usage;
|
||||
}
|
||||
else if (path.EndsWith("/users"))
|
||||
{
|
||||
if (ExhaustedQuota)
|
||||
throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests);
|
||||
result = new List<UserInfo> { new() { UserId = "alice-id", UserName = "alice" } };
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException($"Unexpected endpoint: {path}");
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,31 @@ namespace PostIt.Tests;
|
|||
|
||||
public class AdministrationToolsTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Payment_purge_requires_confirmation_reports_counts_and_clears_on_logout()
|
||||
{
|
||||
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
|
||||
var session = new SessionStatusViewModel { Api = profile };
|
||||
await session.RefreshAsync();
|
||||
await using var transport = new AdminTransport();
|
||||
var vm = new AdministrationPageViewModel(null, session: session,
|
||||
administrationClient: new AdministrationApiClient(transport, () => "https://example.invalid/api/v1"));
|
||||
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
|
||||
Assert.Empty(transport.Paths);
|
||||
vm.ConfirmDestructiveAction = true;
|
||||
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
|
||||
Assert.Contains("POST https://example.invalid/api/v1/administration/payment-residues/purge", transport.Paths);
|
||||
Assert.Contains("2 compte(s)", vm.PaymentPurgeReport);
|
||||
Assert.False(vm.ConfirmDestructiveAction);
|
||||
session.Api = null;
|
||||
session.Refresh();
|
||||
transport.Paths.Clear();
|
||||
vm.ConfirmDestructiveAction = true;
|
||||
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
|
||||
Assert.Empty(transport.Paths);
|
||||
Assert.Empty(vm.PaymentPurgeReport);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(400, 800)]
|
||||
[InlineData(800, 400)]
|
||||
|
|
@ -207,6 +232,8 @@ public class AdministrationToolsTests
|
|||
: await PendingSecret.Task;
|
||||
else if (typeof(T) == typeof(ImportResult))
|
||||
result = new ImportResult(0, 0, 0);
|
||||
else if (typeof(T) == typeof(PaymentResiduePurgeResult))
|
||||
result = new PaymentResiduePurgeResult(2, 3, 4, 1, 1);
|
||||
else
|
||||
throw new NotSupportedException(typeof(T).Name);
|
||||
return JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(result))!;
|
||||
|
|
|
|||
241
src/PostIt/PostIt.Tests/AndroidMarkdownEditorTestActivity.cs
Normal file
241
src/PostIt/PostIt.Tests/AndroidMarkdownEditorTestActivity.cs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
#if ANDROID
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.Content.PM;
|
||||
using Android.OS;
|
||||
using Android.Views;
|
||||
using Android.Views.InputMethods;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.LogicalTree;
|
||||
using Avalonia.Threading;
|
||||
using AvaloniaEdit;
|
||||
using PostIt.Android;
|
||||
using PostIt.Controls;
|
||||
using PostIt.ViewModels;
|
||||
using PostIt.Views.Blogs;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
[Activity(Name = "fr.pschneider.postit.MarkdownEditorTestActivity", Exported = true)]
|
||||
public sealed class AndroidMarkdownEditorTestActivity : Activity
|
||||
{
|
||||
private string _stage = "startup";
|
||||
private ScreenOrientation? _previousOrientation;
|
||||
protected override async void OnCreate(Bundle? state)
|
||||
{
|
||||
base.OnCreate(state);
|
||||
var result = Path.Combine(FilesDir!.AbsolutePath, "markdown-editor-test-result.txt");
|
||||
File.WriteAllText(result, "RUNNING");
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60));
|
||||
await RunAsync(timeout.Token);
|
||||
File.WriteAllText(result, "PASS\nbounded viewport above IME,at least three visible lines,visible caret,keyboard reopen,retained focus");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
File.WriteAllText(result, $"FAIL at {_stage}\n" + ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
RunOnUiThread(Finish);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
if (!OperatingSystem.IsAndroidVersionAtLeast(30))
|
||||
throw new PlatformNotSupportedException("Android 11 required for keyboard visibility assertions.");
|
||||
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
|
||||
_stage = "waiting for main activity";
|
||||
await WaitAsync(() => MainActivity.IsForeground && (Avalonia.Application.Current as App)?.View is not null, ct);
|
||||
var root = ((App)Avalonia.Application.Current!).View!;
|
||||
if (Intent?.GetBooleanExtra("landscape", false) == true)
|
||||
{
|
||||
_previousOrientation = MainActivity.Current!.RequestedOrientation;
|
||||
MainActivity.Current.RequestedOrientation = ScreenOrientation.Landscape;
|
||||
await WaitAsync(() => TopLevel.GetTopLevel(root)!.ClientSize.Width > TopLevel.GetTopLevel(root)!.ClientSize.Height, ct);
|
||||
}
|
||||
var navigation = root.FindControl<NavigationPage>("NavRoot")!;
|
||||
BlogsPage? page = null;
|
||||
TextEditor? source = null;
|
||||
var focusLosses = 0;
|
||||
try
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(async () =>
|
||||
{
|
||||
page = new BlogsPage
|
||||
{
|
||||
DataContext = new BlogsViewModel
|
||||
{
|
||||
IsEditing = true,
|
||||
DraftTitle = "Local keyboard test",
|
||||
DraftArticle = string.Join("\n", Enumerable.Range(1, 150).Select(i => $"Line {i}: local keyboard test"))
|
||||
}
|
||||
};
|
||||
await navigation.PushAsync(page, null);
|
||||
source = page.GetLogicalDescendants().OfType<MarkdownEditorControl>().Single()
|
||||
.FindControl<TextEditor>("SourceEditor")!;
|
||||
});
|
||||
_stage = "waiting for editor layout";
|
||||
await WaitAsync(() => source!.TextArea.Bounds.Height > 0, ct);
|
||||
await Dispatcher.UIThread.InvokeAsync(() => CheckSystemBars(root));
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
if (!source!.TextArea.Focus())
|
||||
throw new InvalidOperationException("Unable to focus the mounted editor.");
|
||||
source.CaretOffset = source.Document.TextLength;
|
||||
source.TextArea.Caret.BringCaretToView();
|
||||
source.TextArea.LostFocus += (_, _) => focusLosses++;
|
||||
});
|
||||
_stage = "waiting for native input connection";
|
||||
await WaitAsync(() =>
|
||||
{
|
||||
var activity = MainActivity.Current!;
|
||||
var manager = (InputMethodManager)activity.GetSystemService(InputMethodService)!;
|
||||
return activity.CurrentFocus is { } view && view.HasWindowFocus
|
||||
&& manager.InvokeIsActive(view) && manager.IsAcceptingText;
|
||||
}, ct);
|
||||
_stage = "opening keyboard";
|
||||
await TapAsync(source!, root);
|
||||
await WaitAsync(KeyboardVisible, ct);
|
||||
await Task.Delay(500, ct);
|
||||
await Dispatcher.UIThread.InvokeAsync(() => CheckCaret(source!, root));
|
||||
var activity = MainActivity.Current!;
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
var manager = (InputMethodManager)activity.GetSystemService(InputMethodService)!;
|
||||
if (!manager.HideSoftInputFromWindow(activity.CurrentFocus!.WindowToken, HideSoftInputFlags.None))
|
||||
throw new InvalidOperationException("Keyboard hide request rejected.");
|
||||
});
|
||||
await WaitAsync(() => !KeyboardVisible(), ct);
|
||||
await Task.Delay(500, ct);
|
||||
await Dispatcher.UIThread.InvokeAsync(() => CheckSystemBars(root));
|
||||
await TapAsync(source!, root);
|
||||
_stage = "reopening keyboard";
|
||||
await WaitAsync(KeyboardVisible, ct);
|
||||
await Task.Delay(500, ct);
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
CheckCaret(source!, root);
|
||||
if (focusLosses != 0) throw new InvalidOperationException($"Editor lost focus {focusLosses} times.");
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (page is not null)
|
||||
await Dispatcher.UIThread.InvokeAsync(async () =>
|
||||
{
|
||||
if (ReferenceEquals(navigation.NavigationStack.LastOrDefault(), page))
|
||||
await navigation.PopAsync();
|
||||
});
|
||||
if (_previousOrientation is { } orientation && MainActivity.Current is { } main)
|
||||
main.RunOnUiThread(() => main.RequestedOrientation = orientation);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool KeyboardVisible()
|
||||
=> OperatingSystem.IsAndroidVersionAtLeast(30)
|
||||
&& MainActivity.Current?.Window?.DecorView?.RootWindowInsets?.IsVisible(WindowInsets.Type.Ime()) == true;
|
||||
|
||||
private static void CheckCaret(TextEditor source, Control root)
|
||||
{
|
||||
var area = source.TextArea;
|
||||
if (!area.IsFocused) throw new InvalidOperationException("Editor is not focused.");
|
||||
var rect = area.Caret.CalculateCaretRectangle();
|
||||
var view = area.TextView;
|
||||
var bottom = rect.Bottom - view.ScrollOffset.Y;
|
||||
if (rect.Top - view.ScrollOffset.Y < -1 || bottom > view.Bounds.Height + 1)
|
||||
throw new InvalidOperationException($"Caret outside viewport: bottom={bottom}, height={view.Bounds.Height}.");
|
||||
var editorBottom = source.TranslatePoint(new Point(0, source.Bounds.Height), root)!.Value.Y;
|
||||
if (editorBottom > root.Bounds.Height + 1)
|
||||
throw new InvalidOperationException($"Editor outside root: bottom={editorBottom}, height={root.Bounds.Height}.");
|
||||
if (view.Bounds.Height < view.DefaultLineHeight * 3)
|
||||
throw new InvalidOperationException($"Less than three visible lines: viewport={view.Bounds.Height}, line={view.DefaultLineHeight}.");
|
||||
if (OperatingSystem.IsAndroidVersionAtLeast(30) && KeyboardVisible())
|
||||
{
|
||||
var activity = MainActivity.Current!;
|
||||
var decor = activity.Window!.DecorView;
|
||||
var keyboardTop = decor.Height - decor.RootWindowInsets!.GetInsets(WindowInsets.Type.Ime()).Bottom;
|
||||
var location = new int[2];
|
||||
activity.CurrentFocus!.GetLocationInWindow(location);
|
||||
var topLevel = TopLevel.GetTopLevel(root)!;
|
||||
var bottomInWindow = source.TranslatePoint(new Point(0, source.Bounds.Height), topLevel)!.Value.Y
|
||||
* topLevel.RenderScaling + location[1];
|
||||
if (bottomInWindow > keyboardTop + 2)
|
||||
throw new InvalidOperationException($"Editor hidden by keyboard: bottom={bottomInWindow}, keyboardTop={keyboardTop}.");
|
||||
}
|
||||
CheckSystemBars(root);
|
||||
}
|
||||
|
||||
private static void CheckSystemBars(Control root)
|
||||
{
|
||||
if (!OperatingSystem.IsAndroidVersionAtLeast(30))
|
||||
throw new PlatformNotSupportedException("Android 11 required for native inset assertions.");
|
||||
var activity = MainActivity.Current!;
|
||||
var decor = activity.Window!.DecorView;
|
||||
var insets = decor.RootWindowInsets!;
|
||||
var bars = insets.GetInsets(WindowInsets.Type.SystemBars() | WindowInsets.Type.DisplayCutout());
|
||||
var location = new int[2];
|
||||
activity.CurrentFocus!.GetLocationInWindow(location);
|
||||
var topLevel = TopLevel.GetTopLevel(root)!;
|
||||
var navigation = root.FindControl<NavigationPage>("NavRoot")!;
|
||||
var banner = root.FindControl<PostIt.Views.SessionStatusBanner>("SessionBanner")!;
|
||||
var top = navigation.TranslatePoint(new Point(), topLevel)!.Value.Y * topLevel.RenderScaling + location[1];
|
||||
var bottom = banner.TranslatePoint(new Point(0, banner.Bounds.Height), topLevel)!.Value.Y
|
||||
* topLevel.RenderScaling + location[1];
|
||||
var visibleBottom = decor.Height - bars.Bottom;
|
||||
if (KeyboardVisible())
|
||||
visibleBottom = Math.Min(visibleBottom, decor.Height - insets.GetInsets(WindowInsets.Type.Ime()).Bottom);
|
||||
if (top < bars.Top - 2 || bottom > visibleBottom + 2 || !banner.IsVisible)
|
||||
throw new InvalidOperationException($"Controls overlap system bars: top={top}, safeTop={bars.Top}, bottom={bottom}, safeBottom={visibleBottom}, banner={banner.IsVisible}.");
|
||||
if (navigation.NavigationStack.LastOrDefault() is BlogsPage page)
|
||||
{
|
||||
var bar = NavigationPage.GetTopCommandBar(page)!;
|
||||
var shouldShowTitle = !KeyboardVisible();
|
||||
if (!bar.IsVisible || bar.Bounds.Height <= 0
|
||||
|| page.FindControl<TextBox>("DraftTitleTextBox")?.IsVisible != shouldShowTitle)
|
||||
throw new InvalidOperationException("Blog controls are unavailable.");
|
||||
if (page.FindControl<TextBox>("DraftTitleTextBox")?.Text != "Local keyboard test")
|
||||
throw new InvalidOperationException("The title changed during keyboard layout transitions.");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task TapAsync(TextEditor source, Control root)
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
var activity = MainActivity.Current!;
|
||||
var point = source.TextArea.TranslatePoint(new Point(80, source.TextArea.Bounds.Height / 2), root)!.Value;
|
||||
var location = new int[2];
|
||||
activity.CurrentFocus!.GetLocationInWindow(location);
|
||||
var scale = TopLevel.GetTopLevel(root)!.RenderScaling;
|
||||
var x = (float)(point.X * scale + location[0]);
|
||||
var y = (float)(point.Y * scale + location[1]);
|
||||
var now = SystemClock.UptimeMillis();
|
||||
using var properties = new MotionEvent.PointerProperties { Id = 0, ToolType = MotionEventToolType.Finger };
|
||||
using var coordinates = new MotionEvent.PointerCoords { X = x, Y = y, Pressure = 1, Size = 1 };
|
||||
using var down = MotionEvent.Obtain(now, now, MotionEventActions.Down, 1,
|
||||
new[] { properties }, new[] { coordinates }, 0, 0, 1, 1, 0, 0,
|
||||
InputSourceType.Touchscreen, 0)!;
|
||||
using var up = MotionEvent.Obtain(now, now + 50, MotionEventActions.Up, 1,
|
||||
new[] { properties }, new[] { coordinates }, 0, 0, 1, 1, 0, 0,
|
||||
InputSourceType.Touchscreen, 0)!;
|
||||
activity.DispatchTouchEvent(down);
|
||||
activity.DispatchTouchEvent(up);
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task WaitAsync(Func<bool> condition, CancellationToken ct)
|
||||
{
|
||||
while (!await Dispatcher.UIThread.InvokeAsync(condition))
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
171
src/PostIt/PostIt.Tests/AndroidPodcastBlurTestActivity.cs
Normal file
171
src/PostIt/PostIt.Tests/AndroidPodcastBlurTestActivity.cs
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
#if ANDROID
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Threading.Tasks;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.Graphics;
|
||||
using Android.Media;
|
||||
using Android.OS;
|
||||
using PostIt.Android.Services;
|
||||
using Path = System.IO.Path;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
[Activity(Name = "fr.pschneider.postit.PodcastBlurTestActivity", Exported = true)]
|
||||
[SupportedOSPlatform("android26.0")]
|
||||
public sealed class AndroidPodcastBlurTestActivity : Activity
|
||||
{
|
||||
protected override async void OnCreate(Bundle? state)
|
||||
{
|
||||
base.OnCreate(state);
|
||||
var result = Path.Combine(FilesDir!.AbsolutePath, "podcast-blur-test-result.txt");
|
||||
File.WriteAllText(result, "RUNNING");
|
||||
try
|
||||
{
|
||||
await VerifyAsync();
|
||||
await VerifyRealModelAsync();
|
||||
await VerifyFailureAsync();
|
||||
File.WriteAllText(result, "PASS\nsegmentation=ONNX\nreal-model-preview=verified\npreview=verified\nencoded=created\nfailure=closed\nsource=synthetic");
|
||||
}
|
||||
catch (Exception ex) { File.WriteAllText(result, $"FAIL\n{ex}"); }
|
||||
finally { Finish(); }
|
||||
}
|
||||
|
||||
private async Task VerifyAsync()
|
||||
{
|
||||
const int width = 640, height = 480;
|
||||
using (var segmenter = new PodcastPersonSegmenter(this))
|
||||
{
|
||||
var mask = segmenter.Segment(new byte[PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size * 4]);
|
||||
if (mask.Length != PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size)
|
||||
throw new InvalidOperationException("Masque de segmentation invalide.");
|
||||
}
|
||||
var path = Path.Combine(FilesDir!.AbsolutePath, "podcast-blur-test.ts");
|
||||
#pragma warning disable CS0618
|
||||
using var recorder = OperatingSystem.IsAndroidVersionAtLeast(31) ? new MediaRecorder(this) : new MediaRecorder();
|
||||
#pragma warning restore CS0618
|
||||
recorder.SetVideoSource(VideoSource.Surface);
|
||||
recorder.SetOutputFormat(OutputFormat.Mpeg2Ts);
|
||||
recorder.SetVideoSize(width, height);
|
||||
recorder.SetVideoFrameRate(30);
|
||||
recorder.SetVideoEncodingBitRate(1200000);
|
||||
recorder.SetVideoEncoder(VideoEncoder.H264);
|
||||
recorder.SetOutputFile(path);
|
||||
recorder.Prepare();
|
||||
using var surface = recorder.Surface ?? throw new InvalidOperationException("Encodeur indisponible.");
|
||||
using var preview = ImageReader.NewInstance(width, height, (ImageFormatType)Format.Rgba8888, 3)
|
||||
?? throw new InvalidOperationException("Apercu indisponible.");
|
||||
Exception? failure = null;
|
||||
using var rotator = await AndroidCameraFrameRotator.CreateAsync(surface, width, height, 0,
|
||||
error => failure = error, this, _ => new SplitMask());
|
||||
await rotator.SetPreviewAsync(preview.Surface, width, height, error => failure = error);
|
||||
recorder.Start();
|
||||
await rotator.StartAsync();
|
||||
using var paint = new Paint();
|
||||
var frames = 0;
|
||||
Task? stop = null;
|
||||
for (var frame = 0; frame < 60; frame++)
|
||||
{
|
||||
if (failure is not null) throw failure;
|
||||
if (frame == 40) stop = Task.Run(recorder.Stop);
|
||||
if (stop?.IsCompleted == true) break;
|
||||
using var canvas = rotator.CameraSurface.LockCanvas(null)
|
||||
?? throw new InvalidOperationException("Camera synthetique indisponible.");
|
||||
try
|
||||
{
|
||||
for (var x = 0; x < width; x += 8)
|
||||
{
|
||||
paint.Color = x / 8 % 2 == 0 ? Color.Black : Color.White;
|
||||
canvas.DrawRect(x, 0, x + 8, height, paint);
|
||||
}
|
||||
}
|
||||
finally { rotator.CameraSurface.UnlockCanvasAndPost(canvas); }
|
||||
await Task.Delay(70);
|
||||
using var image = preview.AcquireLatestImage();
|
||||
if (image is not null)
|
||||
{
|
||||
var plane = image.GetPlanes()![0];
|
||||
var buffer = plane.Buffer!;
|
||||
int Red(int x, int y) => buffer.Get(y * plane.RowStride + x * plane.PixelStride) & 255;
|
||||
var background = Math.Abs(Red(100, 240) - Red(108, 240));
|
||||
var foreground = Math.Abs(Red(500, 240) - Red(508, 240));
|
||||
if (frame > 5 && (background > 120 || foreground < 150))
|
||||
throw new InvalidOperationException($"Apercu incorrect : decor={background}, personne={foreground}.");
|
||||
frames++;
|
||||
image.Close();
|
||||
}
|
||||
}
|
||||
if (failure is not null) throw failure;
|
||||
if (frames < 5) throw new InvalidOperationException($"Apercu insuffisant : {frames} images.");
|
||||
await (stop ?? throw new InvalidOperationException("Arret de l'encodeur non demande."))
|
||||
.WaitAsync(TimeSpan.FromSeconds(15));
|
||||
if (new FileInfo(path).Length == 0) throw new InvalidOperationException("Video encodee vide.");
|
||||
}
|
||||
|
||||
private sealed class SplitMask : IPodcastPersonSegmenter
|
||||
{
|
||||
private readonly byte[] _mask = new byte[PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size];
|
||||
|
||||
public SplitMask()
|
||||
{
|
||||
for (var y = 0; y < PodcastPersonSegmenter.Size; y++)
|
||||
for (var x = PodcastPersonSegmenter.Size / 2; x < PodcastPersonSegmenter.Size; x++)
|
||||
_mask[y * PodcastPersonSegmenter.Size + x] = 255;
|
||||
}
|
||||
public byte[] Segment(byte[] rgba) => _mask;
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private async Task VerifyFailureAsync()
|
||||
{
|
||||
using var preview = ImageReader.NewInstance(640, 480, (ImageFormatType)Format.Rgba8888, 3)
|
||||
?? throw new InvalidOperationException("Apercu indisponible.");
|
||||
var failed = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var rotator = await AndroidCameraFrameRotator.CreateAsync(null, 640, 480, 0,
|
||||
error => failed.TrySetResult(error), this, _ => new FailingMask());
|
||||
await rotator.SetPreviewAsync(preview.Surface, preview.Width, preview.Height,
|
||||
error => failed.TrySetResult(error));
|
||||
await rotator.StartAsync();
|
||||
using var canvas = rotator.CameraSurface.LockCanvas(null)
|
||||
?? throw new InvalidOperationException("Camera synthetique indisponible.");
|
||||
try { canvas.DrawColor(Color.Red); }
|
||||
finally { rotator.CameraSurface.UnlockCanvasAndPost(canvas); }
|
||||
await failed.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
using var image = preview.AcquireLatestImage();
|
||||
if (image is not null) throw new InvalidOperationException("Une image non filtree a ete affichee apres l'echec.");
|
||||
}
|
||||
|
||||
private async Task VerifyRealModelAsync()
|
||||
{
|
||||
using var preview = ImageReader.NewInstance(640, 480, (ImageFormatType)Format.Rgba8888, 3)
|
||||
?? throw new InvalidOperationException("Apercu indisponible.");
|
||||
Exception? failure = null;
|
||||
using var rotator = await AndroidCameraFrameRotator.CreateAsync(null, 640, 480, 0,
|
||||
error => failure = error, this);
|
||||
await rotator.SetPreviewAsync(preview.Surface, preview.Width, preview.Height, error => failure = error);
|
||||
await rotator.StartAsync();
|
||||
var frames = 0;
|
||||
for (var i = 0; i < 15; i++)
|
||||
{
|
||||
if (failure is not null) throw failure;
|
||||
using var canvas = rotator.CameraSurface.LockCanvas(null)
|
||||
?? throw new InvalidOperationException("Camera synthetique indisponible.");
|
||||
try { canvas.DrawColor(Color.Gray); }
|
||||
finally { rotator.CameraSurface.UnlockCanvasAndPost(canvas); }
|
||||
await Task.Delay(100);
|
||||
using var image = preview.AcquireLatestImage();
|
||||
if (image is not null) { frames++; image.Close(); }
|
||||
}
|
||||
if (failure is not null) throw failure;
|
||||
if (frames < 2) throw new InvalidOperationException($"Apercu avec modele reel insuffisant : {frames} images.");
|
||||
}
|
||||
|
||||
private sealed class FailingMask : IPodcastPersonSegmenter
|
||||
{
|
||||
public byte[] Segment(byte[] rgba) => throw new InvalidOperationException("Echec de segmentation simule.");
|
||||
public void Dispose() { }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
|
@ -228,7 +228,6 @@ public class BlogReaderTests
|
|||
{
|
||||
Assert.True(reader.Bounds.Right <= list.Bounds.Left);
|
||||
Assert.Equal(2, Grid.GetColumn(page.BlogsHeaderPanel));
|
||||
Assert.Equal(2, Grid.GetColumn(page.BlogsCommandBar));
|
||||
Assert.Equal(reader.Margin.Top, reader.Bounds.Top);
|
||||
Assert.Equal(page.StatusBar.Bounds.Top - reader.Margin.Bottom, reader.Bounds.Bottom);
|
||||
Assert.Equal(36, page.TranslatePoint(new Point(), nav)!.Value.Y);
|
||||
|
|
@ -237,9 +236,9 @@ public class BlogReaderTests
|
|||
{
|
||||
Assert.True(list.Bounds.Bottom <= reader.Bounds.Top);
|
||||
Assert.Equal(0, Grid.GetColumn(page.BlogsHeaderPanel));
|
||||
Assert.Equal(0, Grid.GetColumn(page.BlogsCommandBar));
|
||||
}
|
||||
|
||||
Assert.Same(page.BlogsCommandBar, NavigationPage.GetTopCommandBar(page));
|
||||
var articleScroll = page.FindControl<MarkdownScrollViewer>("ArticleReader")!
|
||||
.GetVisualDescendants().OfType<ScrollViewer>().Single();
|
||||
Assert.InRange(articleScroll.Viewport.Height, 1, window.ClientSize.Height);
|
||||
|
|
|
|||
|
|
@ -1,12 +1,17 @@
|
|||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.LogicalTree;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using AvaloniaEdit;
|
||||
using PostIt.Controls;
|
||||
using PostIt.Services;
|
||||
using PostIt.ViewModels;
|
||||
using PostIt.Views;
|
||||
using PostIt.Views.Blogs;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
|
@ -16,6 +21,201 @@ public class MarkdownEditorScrollTests
|
|||
private static readonly string LongArticle =
|
||||
string.Join("\n\n", Enumerable.Range(1, 100).Select(i => $"Paragraph {i}: article content."));
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Landscape_keyboard_preserves_controls_and_restores_editor_layout()
|
||||
{
|
||||
var root = new MainView();
|
||||
var page = new BlogsPage { DataContext = new BlogsViewModel { IsEditing = true, DraftArticle = LongArticle } };
|
||||
var window = new Window { Width = 800, Height = 400, Content = root };
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
await root.NavRoot.PushAsync(page, null);
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
var editor = page.ArticleEditor;
|
||||
var source = editor.FindControl<TextEditor>("SourceEditor")!;
|
||||
source.TextArea.Focus();
|
||||
source.CaretOffset = source.Document.TextLength;
|
||||
root.ApplyKeyboardOcclusion(new Rect(0, 200, 800, 200));
|
||||
window.UpdateLayout();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
Assert.True(page.DraftTitleTextBox.IsVisible);
|
||||
Assert.True(page.AttachmentsBorder.IsVisible);
|
||||
Assert.True(root.SessionBanner.IsVisible);
|
||||
Assert.Equal(1, Grid.GetColumn(page.DraftTitleTextBox));
|
||||
Assert.Equal(1, Grid.GetColumn(page.AttachmentsBorder));
|
||||
Assert.True(page.StatusBar.IsVisible);
|
||||
Assert.Equal(2, Grid.GetColumn(page.StatusBar));
|
||||
Assert.Same(page.BlogsCommandBar, NavigationPage.GetTopCommandBar(page));
|
||||
Assert.True(source.TextArea.Bounds.Height >= source.TextArea.TextView.DefaultLineHeight * 3);
|
||||
var bottom = source.TranslatePoint(new Point(0, source.Bounds.Height), window)!.Value.Y;
|
||||
Assert.InRange(bottom, 1, 200);
|
||||
var document = source.Document;
|
||||
root.ApplyKeyboardOcclusion(null);
|
||||
window.UpdateLayout();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
Assert.True(page.DraftTitleTextBox.IsVisible);
|
||||
Assert.True(page.AttachmentsBorder.IsVisible);
|
||||
Assert.True(root.SessionBanner.IsVisible);
|
||||
Assert.Equal(0, Grid.GetColumn(page.DraftTitleTextBox));
|
||||
Assert.Same(document, source.Document);
|
||||
Assert.True(source.TextArea.IsFocused);
|
||||
|
||||
window.Height = 200;
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
root.ApplyKeyboardOcclusion(new Rect(0, 200, 800, 200));
|
||||
Assert.Equal(0, root.Padding.Bottom);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseWindow(window, page.ArticleEditor);
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void Keyboard_padding_preserves_system_bar_insets_and_restores_them()
|
||||
{
|
||||
var root = new MainView();
|
||||
var window = new Window { Width = 600, Height = 800, Content = root };
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
var safeArea = new Thickness(10, 24, 12, 30);
|
||||
root.ApplySafeArea(safeArea);
|
||||
Assert.Equal(safeArea, root.Padding);
|
||||
root.ApplyKeyboardOcclusion(new Rect(0, 500, 600, 300));
|
||||
Assert.Equal(new Thickness(10, 24, 12, 300), root.Padding);
|
||||
root.ApplySafeArea(new Thickness(20, 26, 22, 32));
|
||||
Assert.Equal(new Thickness(20, 26, 22, 300), root.Padding);
|
||||
root.ApplyKeyboardOcclusion(null);
|
||||
window.UpdateLayout();
|
||||
Assert.Equal(new Thickness(20, 26, 22, 32), root.Padding);
|
||||
var navigationTop = root.NavRoot.TranslatePoint(new Point(), window)!.Value.Y;
|
||||
var bannerBottom = root.SessionBanner.TranslatePoint(new Point(0, root.SessionBanner.Bounds.Height), window)!.Value.Y;
|
||||
Assert.True(navigationTop >= 26);
|
||||
Assert.True(bannerBottom <= 768);
|
||||
Assert.True(root.SessionBanner.IsVisible);
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void Resizing_keeps_the_focused_caret_visible_without_changing_selection(bool focused)
|
||||
{
|
||||
var editor = new MarkdownEditorControl { MarkdownText = LongArticle };
|
||||
var other = new TextBox();
|
||||
var panel = new DockPanel();
|
||||
DockPanel.SetDock(other, Dock.Top);
|
||||
panel.Children.Add(other);
|
||||
panel.Children.Add(editor);
|
||||
var window = new Window { Width = 600, Height = 500, Content = panel };
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
var source = editor.FindControl<TextEditor>("SourceEditor")!;
|
||||
source.TextArea.Focus();
|
||||
source.Select(LongArticle.Length - 20, 10);
|
||||
source.TextArea.Caret.BringCaretToView();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
var selectedText = source.SelectedText;
|
||||
var caretOffset = source.CaretOffset;
|
||||
var scroller = FindArticleScroller(editor, false);
|
||||
if (!focused)
|
||||
{
|
||||
other.Focus();
|
||||
scroller.ScrollToHome();
|
||||
}
|
||||
|
||||
window.Height = 250;
|
||||
window.UpdateLayout();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
|
||||
Assert.Equal(selectedText, source.SelectedText);
|
||||
Assert.Equal(caretOffset, source.CaretOffset);
|
||||
if (focused)
|
||||
{
|
||||
Assert.True(source.TextArea.IsFocused);
|
||||
var caret = source.TextArea.Caret.CalculateCaretRectangle();
|
||||
var view = source.TextArea.TextView;
|
||||
Assert.InRange(caret.Top - view.ScrollOffset.Y, 0, view.Bounds.Height);
|
||||
Assert.InRange(caret.Bottom - view.ScrollOffset.Y, 0, view.Bounds.Height);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.True(other.IsFocused);
|
||||
Assert.Equal(0, scroller.Offset.Y);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseWindow(window, editor);
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void Repeated_touch_requests_keyboard_without_losing_focus_and_read_only_does_not()
|
||||
{
|
||||
var editor = new MarkdownEditorControl { MarkdownText = LongArticle };
|
||||
var window = new Window { Width = 600, Height = 400, Content = editor };
|
||||
var previous = Platform.ShowSoftKeyboard;
|
||||
var requests = 0;
|
||||
Platform.ShowSoftKeyboard = () => requests++;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
var source = editor.FindControl<TextEditor>("SourceEditor")!;
|
||||
source.TextArea.Focus();
|
||||
var focusLosses = 0;
|
||||
source.TextArea.LostFocus += (_, _) => focusLosses++;
|
||||
var point = source.TextArea.TranslatePoint(new Point(60, 20), window)!.Value;
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
using var touch = window.TouchBegin(point);
|
||||
window.TouchEnd(touch, point);
|
||||
Assert.True(source.TextArea.IsFocused);
|
||||
Assert.Equal(i + 1, requests);
|
||||
}
|
||||
|
||||
window.MouseDown(point, MouseButton.Left);
|
||||
window.MouseUp(point, MouseButton.Left);
|
||||
Assert.Equal(2, requests);
|
||||
using (var scrollTouch = window.TouchBegin(point))
|
||||
{
|
||||
var end = point + new Vector(0, -80);
|
||||
window.TouchMove(scrollTouch, end);
|
||||
window.TouchEnd(scrollTouch, end);
|
||||
}
|
||||
Assert.Equal(2, requests);
|
||||
source.IsReadOnly = true;
|
||||
using var readOnlyTouch = window.TouchBegin(point);
|
||||
window.TouchEnd(readOnlyTouch, point);
|
||||
Assert.Equal(2, requests);
|
||||
Assert.Equal(0, focusLosses);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Platform.ShowSoftKeyboard = previous;
|
||||
CloseWindow(window, editor);
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ public sealed class PodcastPreferencesTests
|
|||
vm.Title = "Mon emission habituelle";
|
||||
Assert.False(vm.KeepScreenOnDuringCapture);
|
||||
vm.KeepScreenOnDuringCapture = true;
|
||||
Assert.False(vm.BlurPodcastBackground);
|
||||
vm.BlurPodcastBackground = true;
|
||||
vm.DetectDevicesCommand.Execute(null);
|
||||
Assert.Equal("rear", vm.SelectedCamera?.Value);
|
||||
Assert.Equal("", vm.SelectedMicrophone?.Value);
|
||||
|
|
@ -41,6 +43,7 @@ public sealed class PodcastPreferencesTests
|
|||
Assert.Equal("rear", restored.PodcastCameraId);
|
||||
Assert.Equal("", restored.PodcastMicrophoneId);
|
||||
Assert.True(restored.PodcastKeepScreenOn);
|
||||
Assert.True(restored.PodcastBlurBackground);
|
||||
Platform.GetPodcastCaptureDevices = () => throw new InvalidOperationException("Must use saved devices.");
|
||||
await using var otherApi = new PreferencesApi(restored, new TokenStore(path + ".tokens"));
|
||||
var other = new PodcastsPageViewModel(new PodcastApiClient(otherApi, () => restored.ApiUrl), otherApi, session);
|
||||
|
|
@ -50,13 +53,16 @@ public sealed class PodcastPreferencesTests
|
|||
Assert.Equal("", other.SelectedMicrophone?.Value);
|
||||
Assert.Equal(vm.Title, other.Title);
|
||||
Assert.True(other.KeepScreenOnDuringCapture);
|
||||
Assert.True(other.BlurPodcastBackground);
|
||||
restored.PodcastCameraId = "front";
|
||||
restored.PodcastMicrophoneId = "usb";
|
||||
restored.PodcastKeepScreenOn = false;
|
||||
restored.PodcastBlurBackground = false;
|
||||
await other.ActivateAsync();
|
||||
Assert.Equal("front", other.SelectedCamera?.Value);
|
||||
Assert.Equal("usb", other.SelectedMicrophone?.Value);
|
||||
Assert.False(other.KeepScreenOnDuringCapture);
|
||||
Assert.False(other.BlurPodcastBackground);
|
||||
|
||||
Platform.GetPodcastCaptureDevices = () => new([], []);
|
||||
other.DetectDevicesCommand.Execute(null);
|
||||
|
|
|
|||
|
|
@ -9,6 +9,83 @@ namespace PostIt.Tests;
|
|||
|
||||
public sealed class PodcastScheduleTests
|
||||
{
|
||||
[AvaloniaFact]
|
||||
public async Task Late_obs_credentials_are_not_displayed_after_selection_changes_or_navigation()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-late-{Guid.NewGuid():N}.json");
|
||||
var store = new TokenStore(path);
|
||||
store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null));
|
||||
try
|
||||
{
|
||||
await using var api = new ScheduleApi(store, path + ".settings");
|
||||
var session = new SessionStatusViewModel { Api = api };
|
||||
session.Refresh();
|
||||
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
|
||||
await vm.ActivateAsync();
|
||||
vm.SelectedPodcast = api.Plan;
|
||||
api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var activation = vm.ActivateObsCommand.ExecuteAsync(null);
|
||||
vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid() };
|
||||
vm.SelectedPodcast = api.Plan;
|
||||
api.PendingActivation.SetResult(new("srt://obs.example:10000?passphrase=secret", "", DateTimeOffset.UtcNow.AddMinutes(30)));
|
||||
await activation;
|
||||
Assert.Empty(vm.ObsServerUrl);
|
||||
Assert.Empty(vm.ObsStreamKey);
|
||||
api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
activation = vm.ActivateObsCommand.ExecuteAsync(null);
|
||||
await vm.DeactivateAsync();
|
||||
api.PendingActivation.SetResult(new("srt://obs.example:10000?passphrase=secret", "", DateTimeOffset.UtcNow.AddMinutes(30)));
|
||||
await activation;
|
||||
Assert.Empty(vm.ObsServerUrl);
|
||||
Assert.Empty(vm.ObsStreamKey);
|
||||
}
|
||||
finally { File.Delete(path); File.Delete(path + ".settings"); }
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Obs_activation_is_owned_displays_credentials_and_clears_them_on_navigation_and_revocation()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-{Guid.NewGuid():N}.json");
|
||||
var store = new TokenStore(path);
|
||||
store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null));
|
||||
try
|
||||
{
|
||||
await using var api = new ScheduleApi(store, path + ".settings");
|
||||
var session = new SessionStatusViewModel { Api = api };
|
||||
session.Refresh();
|
||||
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
|
||||
await vm.ActivateAsync();
|
||||
vm.SelectedPodcast = api.Plan;
|
||||
Assert.True(vm.ActivateObsCommand.CanExecute(null));
|
||||
await vm.ActivateObsCommand.ExecuteAsync(null);
|
||||
Assert.Equal("srt://obs.example:10000?passphrase=stream-secret", vm.ObsServerUrl);
|
||||
Assert.Empty(vm.ObsStreamKey);
|
||||
Assert.False(vm.IsBroadcasting);
|
||||
api.Settings.Save();
|
||||
Assert.DoesNotContain("stream-secret", await File.ReadAllTextAsync(path + ".settings"));
|
||||
vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid(), OwnerId = "other" };
|
||||
Assert.Empty(vm.ObsServerUrl);
|
||||
Assert.Empty(vm.ObsStreamKey);
|
||||
Assert.False(vm.ActivateObsCommand.CanExecute(null));
|
||||
vm.SelectedPodcast = api.Plan;
|
||||
await vm.ActivateObsCommand.ExecuteAsync(null);
|
||||
await vm.DeactivateAsync();
|
||||
Assert.Empty(vm.ObsServerUrl);
|
||||
Assert.Empty(vm.ObsStreamKey);
|
||||
Assert.True(api.ObsEnabled);
|
||||
await vm.ActivateAsync();
|
||||
vm.SelectedPodcast = api.Plan;
|
||||
await vm.ActivateObsCommand.ExecuteAsync(null);
|
||||
await vm.DeactivateObsCommand.ExecuteAsync(null);
|
||||
Assert.False(api.ObsEnabled);
|
||||
Assert.Empty(vm.ObsServerUrl);
|
||||
Assert.Empty(vm.ObsStreamKey);
|
||||
Assert.EndsWith("/obs", api.RevokedPath);
|
||||
await vm.DeactivateAsync();
|
||||
}
|
||||
finally { File.Delete(path); File.Delete(path + ".settings"); }
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Preparation_and_editing_send_schedule_and_optional_announcement_without_capture()
|
||||
{
|
||||
|
|
@ -62,18 +139,33 @@ public sealed class PodcastScheduleTests
|
|||
finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); }
|
||||
}
|
||||
|
||||
private sealed class ScheduleApi(TokenStore store, string settingsPath) : YavscApiClient(new Settings(settingsPath), store)
|
||||
private sealed class ScheduleApi(TokenStore store, string settingsPath)
|
||||
: YavscApiClient(new Settings(settingsPath), store), IYavscApiClient
|
||||
{
|
||||
public PodcastResponse Plan { get; private set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner",
|
||||
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0);
|
||||
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0) { FlowId = 1 };
|
||||
public bool ObsEnabled { get; private set; }
|
||||
public string? RevokedPath { get; private set; }
|
||||
public PreparePodcastRequest? Saved { get; set; }
|
||||
public string? SavedPath { get; private set; }
|
||||
public HttpMethod? SavedMethod { get; private set; }
|
||||
public TaskCompletionSource<PodcastObsCredentials>? PendingActivation { get; set; }
|
||||
|
||||
public override Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
public override async Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
{
|
||||
object response;
|
||||
if (path.EndsWith("/account/me", StringComparison.Ordinal)) response = new Me { UserId = "owner" };
|
||||
else if (path.EndsWith("/obs", StringComparison.Ordinal))
|
||||
{
|
||||
if (method == HttpMethod.Post)
|
||||
{
|
||||
ObsEnabled = true;
|
||||
response = PendingActivation is null
|
||||
? new PodcastObsCredentials("srt://obs.example:10000?passphrase=stream-secret", "", DateTimeOffset.UtcNow.AddMinutes(30))
|
||||
: await PendingActivation.Task;
|
||||
}
|
||||
else response = new PodcastObsStatus(ObsEnabled, DateTimeOffset.UtcNow.AddMinutes(30), null);
|
||||
}
|
||||
else if (method == HttpMethod.Get) response = new List<PodcastResponse> { Plan };
|
||||
else
|
||||
{
|
||||
|
|
@ -87,7 +179,16 @@ public sealed class PodcastScheduleTests
|
|||
};
|
||||
response = Plan;
|
||||
}
|
||||
return Task.FromResult((T)response);
|
||||
return (T)response;
|
||||
}
|
||||
|
||||
Task IYavscApiClient.CallAsync(HttpMethod method, string path, object? body, CancellationToken ct)
|
||||
{
|
||||
Assert.Equal(HttpMethod.Delete, method);
|
||||
Assert.EndsWith("/obs", path);
|
||||
ObsEnabled = false;
|
||||
RevokedPath = path;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -156,6 +156,21 @@ public class ProviderOngoingRequestsPageViewModelTests
|
|||
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateEstimateForSelectedCommand_is_disabled_for_an_amateur_profile()
|
||||
{
|
||||
var api = new StubProviderApi();
|
||||
var client = new BillingApiClient(api, "https://business.example/api/v1/");
|
||||
var estimateClient = new EstimateApiClient(api, "https://business.example/api/v1/");
|
||||
var vm = new ProviderOngoingRequestsPageViewModel(
|
||||
client, estimateClient: estimateClient, canIssueEstimates: false);
|
||||
|
||||
await vm.InitializeAsync();
|
||||
vm.SelectedQuery = vm.Queries[0];
|
||||
|
||||
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
|
||||
}
|
||||
|
||||
private sealed class StubProviderApi : IYavscApiClient
|
||||
{
|
||||
public HttpClient Http { get; } = new();
|
||||
|
|
|
|||
|
|
@ -7,6 +7,18 @@ namespace PostIt.Tests;
|
|||
|
||||
public class ResourceUsageApiClientTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Usage_remains_visible_when_the_rest_of_the_profile_is_unavailable()
|
||||
{
|
||||
var usage = new ResourceUsageApiClient(new FakeYavscApiClient(), "https://example.invalid/api/v1/");
|
||||
var model = new PostIt.ViewModels.UserProfilePageViewModel(null, usageClient: usage);
|
||||
await model.RefreshAsync();
|
||||
Assert.NotNull(model.ResourceUsage);
|
||||
Assert.Equal(20.65m, model.ResourceUsage.Consumption);
|
||||
Assert.Null(model.UsageError);
|
||||
Assert.False(model.IsProfileLoaded);
|
||||
Assert.False(model.IsBusy);
|
||||
}
|
||||
[Fact]
|
||||
public async Task GetCurrentAsync_calls_user_usage_endpoint()
|
||||
{
|
||||
|
|
@ -19,6 +31,10 @@ public class ResourceUsageApiClientTests
|
|||
Assert.Equal("GET", fake.LastMethod);
|
||||
Assert.Equal(12.5m, usage.ApiCalls);
|
||||
Assert.Equal(3.2m, usage.CpuSeconds);
|
||||
Assert.Equal(20.65m, usage.Consumption);
|
||||
Assert.Equal(10000m, usage.ConsumptionLimit);
|
||||
Assert.Equal(9979.35m, usage.RemainingConsumption);
|
||||
Assert.False(usage.IsQuotaReached);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -56,6 +72,9 @@ public class ResourceUsageApiClientTests
|
|||
CpuSeconds = 3.2m,
|
||||
BandwidthMb = 18.4m,
|
||||
StorageMb = 51.2m,
|
||||
Consumption = 20.65m,
|
||||
ConsumptionLimit = 10000m,
|
||||
RemainingConsumption = 9979.35m,
|
||||
EstimatedCompensation = 4.9m,
|
||||
Currency = "EUR",
|
||||
RecordedAtUtc = DateTimeOffset.UtcNow
|
||||
|
|
|
|||
|
|
@ -38,5 +38,6 @@
|
|||
<StreamGeometry x:Key="share_android_regular">M17,2.49823144 C18.9339734,2.49823144 20.5017686,4.06602662 20.5017686,6 C20.5017686,7.93397338 18.9339734,9.50176856 17,9.50176856 C15.9700352,9.50176856 15.0439275,9.0571034 14.4031791,8.34927521 L9.84455071,10.9536986 C9.94786118,11.284101 10.0035371,11.6355486 10.0035371,12 C10.0035371,12.3644514 9.94786118,12.715899 9.84455071,13.0463014 L14.4022538,15.6517469 C15.0430358,14.9433244 15.9695393,14.4982314 17,14.4982314 C18.9339734,14.4982314 20.5017686,16.0660262 20.5017686,17.9999996 C20.5017686,19.9339729 18.9339734,21.5017681 17,21.5017681 C15.0660266,21.5017681 13.4982314,19.9339729 13.4982314,17.9999996 C13.4982314,17.6355481 13.5539074,17.2841005 13.6572179,16.9536982 L9.09951477,14.3482526 C8.45873279,15.0566751 7.53222925,15.5017686 6.50176856,15.5017686 C4.56779519,15.5017686 3,13.9339734 3,12 C3,10.0660266 4.56779519,8.49823144 6.50176856,8.49823144 C7.53173336,8.49823144 8.45784104,8.9428966 9.09858948,9.65072479 L13.6572179,7.04630139 C13.5539074,6.71589903 13.4982314,6.36445142 13.4982314,6 C13.4982314,4.06602662 15.0660266,2.49823144 17,2.49823144 Z M17,15.998231 C15.8944537,15.998231 14.9982314,16.8944533 14.9982314,17.9999996 C14.9982314,19.1055458 15.8944537,20.0017681 17,20.0017681 C18.1055463,20.0017681 19.0017686,19.1055458 19.0017686,17.9999996 C19.0017686,16.8944533 18.1055463,15.998231 17,15.998231 Z M6.50176856,9.99823144 C5.39622231,9.99823144 4.5,10.8944537 4.5,12 C4.5,13.1055463 5.39622231,14.0017686 6.50176856,14.0017686 C7.60731481,14.0017686 8.50353713,13.1055463 8.50353713,12 C8.50353713,10.8944537 7.60731481,9.99823144 6.50176856,9.99823144 Z M17,3.99823144 C15.8944537,3.99823144 14.9982314,4.89445375 14.9982314,6 C14.9982314,7.10554625 15.8944537,8.00176856 17,8.00176856 C18.1055463,8.00176856 19.0017686,7.10554625 19.0017686,6 C19.0017686,4.89445375 18.1055463,3.99823144 17,3.99823144 Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="comment_edit_regular">M2 14.75C2 16.5449 3.45507 18 5.25 18H5.99921L6 20.7499C6 21.0196 6.08736 21.2822 6.24901 21.4984C6.6625 22.0512 7.44585 22.1642 7.99868 21.7507L10.1239 20.1608L10.5199 18.5768C10.5914 18.2911 10.6965 18.0162 10.8322 17.7578L7.49986 20.2506L7.49879 16.5H5.25C4.2835 16.5 3.5 15.7165 3.5 14.75V6.25C3.5 5.2835 4.2835 4.5 5.25 4.5H18.75C19.7165 4.5 20.5 5.2835 20.5 6.25V10.0946C21.0475 10.2288 21.5671 10.5054 22 10.9246V6.25C22 4.45507 20.5449 3 18.75 3H5.25C3.45507 3 2 4.45507 2 6.25V14.75Z M18.0979 11.6695L12.1955 17.5719C11.8513 17.916 11.6072 18.3472 11.4892 18.8194L11.0315 20.6501C10.8325 21.4462 11.5536 22.1674 12.3497 21.9683L14.1804 21.5106C14.6526 21.3926 15.0838 21.1485 15.4279 20.8043L21.3303 14.9019C22.223 14.0093 22.223 12.5621 21.3303 11.6695C20.4377 10.7768 18.9905 10.7768 18.0979 11.6695Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="delete_regular">M24,7.25 C27.1017853,7.25 29.629937,9.70601719 29.7458479,12.7794443 L29.75,13 L37,13 C37.6903559,13 38.25,13.5596441 38.25,14.25 C38.25,14.8972087 37.7581253,15.4295339 37.1278052,15.4935464 L37,15.5 L35.909,15.5 L34.2058308,38.0698451 C34.0385226,40.2866784 32.1910211,42 29.9678833,42 L18.0321167,42 C15.8089789,42 13.9614774,40.2866784 13.7941692,38.0698451 L12.09,15.5 L11,15.5 C10.3527913,15.5 9.8204661,15.0081253 9.75645361,14.3778052 L9.75,14.25 C9.75,13.6027913 10.2418747,13.0704661 10.8721948,13.0064536 L11,13 L18.25,13 C18.25,9.82436269 20.8243627,7.25 24,7.25 Z M33.4021054,15.5 L14.5978946,15.5 L16.2870795,37.8817009 C16.3559711,38.7945146 17.116707,39.5 18.0321167,39.5 L29.9678833,39.5 C30.883293,39.5 31.6440289,38.7945146 31.7129205,37.8817009 L33.4021054,15.5 Z M27.25,20.75 C27.8972087,20.75 28.4295339,21.2418747 28.4935464,21.8721948 L28.5,22 L28.5,33 C28.5,33.6903559 27.9403559,34.25 27.25,34.25 C26.6027913,34.25 26.0704661,33.7581253 26.0064536,33.1278052 L26,33 L26,22 C26,21.3096441 26.5596441,20.75 27.25,20.75 Z M20.75,20.75 C21.3972087,20.75 21.9295339,21.2418747 21.9935464,21.8721948 L22,22 L22,33 C22,33.6903559 21.4403559,34.25 20.75,34.25 C20.1027913,34.25 19.5704661,33.7581253 19.5064536,33.1278052 L19.5,33 L19.5,22 C19.5,21.3096441 20.0596441,20.75 20.75,20.75 Z M24,9.75 C22.2669685,9.75 20.8507541,11.1064548 20.7551448,12.8155761 L20.75,13 L27.25,13 C27.25,11.2050746 25.7949254,9.75 24,9.75 Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="chat_regular">M14.0038862,2.5 C20.3551608,2.5 25.5038862,7.64872538 25.5038862,14 C25.5038862,20.3512746 20.3551608,25.5 14.0038862,25.5 C12.0828262,25.5 10.2289934,25.0277557 8.57453454,24.1400553 L4.06949813,25.4927799 C3.40830889,25.6913248 2.71135661,25.3162775 2.51281166,24.6550883 C2.44236748,24.4204969 2.44239769,24.1703786 2.5128929,23.935823 L3.86597493,19.4333464 C2.97690068,17.777898 2.50388618,15.9226229 2.50388618,14 C2.50388618,7.64872538 7.65261155,2.5 14.0038862,2.5 Z M14.0038862,4 C8.48103868,4 4.00388618,8.4771525 4.00388618,14 C4.00388618,15.7703119 4.46384891,17.4718347 5.32571954,18.9725127 L5.48656853,19.2525809 L4.08316234,23.9225148 L8.75512584,22.5196672 L9.03501121,22.6802549 C10.5348218,23.5407899 12.2350195,24 14.0038862,24 C19.5267337,24 24.0038862,19.5228475 24.0038862,14 C24.0038862,8.4771525 19.5267337,4 14.0038862,4 Z M10.2538862,15.5 L14.7521489,15.5 C15.1663625,15.5 15.5021489,15.8357864 15.5021489,16.25 C15.5021489,16.6296958 15.219995,16.943491 14.8539195,16.9931534 L14.7521489,17 L10.2538862,17 C9.83967261,17 9.50388618,16.6642136 9.50388618,16.25 C9.50388618,15.8703042 9.78604006,15.556509 10.1521156,15.5068466 L10.2538862,15.5 L14.7521489,15.5 L10.2538862,15.5 Z M10.2538862,11 L17.7583662,11 C18.1725798,11 18.5083662,11.3357864 18.5083662,11.75 C18.5083662,12.1296958 18.2262123,12.443491 17.8601368,12.4931534 L17.7583662,12.5 L10.2538862,12.5 C9.83967261,12.5 9.50388618,12.1642136 9.50388618,11.75 C9.50388618,11.3703042 9.78604006,11.056509 10.1521156,11.0068466 L10.2538862,11 L17.7583662,11 L10.2538862,11 Z</StreamGeometry>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,19 @@
|
|||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using AvaloniaEdit.Document;
|
||||
using PostIt.Services;
|
||||
|
||||
namespace PostIt.Controls;
|
||||
|
||||
public partial class MarkdownEditorControl : UserControl
|
||||
{
|
||||
private IPointer? _touchPointer;
|
||||
private Point _touchStart;
|
||||
public static readonly StyledProperty<string?> MarkdownTextProperty =
|
||||
AvaloniaProperty.Register<MarkdownEditorControl, string?>(nameof(MarkdownText));
|
||||
|
||||
|
|
@ -38,6 +45,44 @@ public partial class MarkdownEditorControl : UserControl
|
|||
{
|
||||
InitializeComponent();
|
||||
PropertyChanged += OnPropertyChanged;
|
||||
SourceEditor.TextArea.SizeChanged += (_, _) =>
|
||||
Dispatcher.UIThread.Post(KeepCaretVisible, DispatcherPriority.Loaded);
|
||||
SourceEditor.TextArea.AddHandler(InputElement.PointerPressedEvent, OnEditorPointerPressed,
|
||||
RoutingStrategies.Tunnel, handledEventsToo: true);
|
||||
SourceEditor.TextArea.AddHandler(InputElement.PointerReleasedEvent, OnEditorPointerReleased,
|
||||
RoutingStrategies.Bubble, handledEventsToo: true);
|
||||
}
|
||||
|
||||
private void KeepCaretVisible()
|
||||
{
|
||||
if (SourceEditor.TextArea.IsFocused && SourceEditor.IsEffectivelyVisible
|
||||
&& SourceEditor.TextArea.Bounds.Height > 0)
|
||||
SourceEditor.TextArea.Caret.BringCaretToView();
|
||||
}
|
||||
|
||||
private void OnEditorPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (e.Pointer.Type != PointerType.Touch)
|
||||
return;
|
||||
_touchPointer = e.Pointer;
|
||||
_touchStart = e.GetPosition(SourceEditor.TextArea);
|
||||
}
|
||||
|
||||
private void OnEditorPointerReleased(object? sender, PointerReleasedEventArgs e)
|
||||
{
|
||||
if (!ReferenceEquals(_touchPointer, e.Pointer))
|
||||
return;
|
||||
_touchPointer = null;
|
||||
var point = e.GetPosition(SourceEditor.TextArea);
|
||||
var settings = this.GetPlatformSettings()
|
||||
?? throw new InvalidOperationException("The editor has no platform input settings.");
|
||||
var tapSize = settings.GetTapSize(PointerType.Touch);
|
||||
// AvaloniaEdit changes pointer capture during selection, so its taps may not raise Tapped.
|
||||
if (new Rect(_touchStart, default(Size)).Inflate(new Thickness(tapSize.Width, tapSize.Height)).Contains(point)
|
||||
&& SourceEditor.TextArea.IsFocused
|
||||
&& !SourceEditor.IsReadOnly
|
||||
&& new Rect(SourceEditor.TextArea.Bounds.Size).Contains(point))
|
||||
Platform.ShowSoftKeyboard?.Invoke();
|
||||
}
|
||||
|
||||
private void OnPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e)
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ namespace PostIt.Services;
|
|||
/// </summary>
|
||||
public static class Platform
|
||||
{
|
||||
public static Action? ShowSoftKeyboard { get; set; }
|
||||
public static ScreenAwakeRequests ScreenAwake { get; } = new();
|
||||
private static bool _isApplicationActive = !OperatingSystem.IsAndroid();
|
||||
public static event Action? ApplicationActivityChanged;
|
||||
|
|
@ -33,6 +34,8 @@ public static class Platform
|
|||
public static Func<string?, CancellationToken, Task>? RequestPodcastPermissionsAsync { get; set; }
|
||||
public static Func<string, string?, string, CancellationToken, Task<IPodcastCapture>>? CreatePodcastCaptureAsync { get; set; }
|
||||
public static Func<string, CancellationToken, Task<IPodcastCapture>>? CreatePodcastPreviewAsync { get; set; }
|
||||
public static Func<string, string?, string, CancellationToken, Task<IPodcastCapture>>? CreateBlurredPodcastCaptureAsync { get; set; }
|
||||
public static Func<string, CancellationToken, Task<IPodcastCapture>>? CreateBlurredPodcastPreviewAsync { get; set; }
|
||||
|
||||
/// <summary>Platform-specific video surface inside the shared video page.</summary>
|
||||
public static Func<MediaPlayer, bool, Control>? CreateVideoSurface { get; set; }
|
||||
|
|
@ -66,7 +69,7 @@ public static class Platform
|
|||
/// <c>LoginAsync</c> will surface a clear error.
|
||||
/// </summary>
|
||||
public static System.Func<IBrowser?>? CreateBrowser { get; set; } =
|
||||
() => new CustomSchemeBrowser(CustomScheme);
|
||||
() => null;
|
||||
|
||||
/// <summary>
|
||||
/// Optional platform hook used by the shared billing form to request a
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi
|
|||
private readonly EstimateApiClient? _estimateClient;
|
||||
private readonly Settings? _settings;
|
||||
private List<BillingQuerySummaryDto> _allQueries = new();
|
||||
public bool CanIssueEstimates { get; }
|
||||
|
||||
[ObservableProperty]
|
||||
public partial ObservableCollection<BillingQuerySummaryDto> Queries { get; set; } = new();
|
||||
|
|
@ -75,11 +76,13 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi
|
|||
public ProviderOngoingRequestsPageViewModel(
|
||||
BillingApiClient billingClient,
|
||||
Settings? settings = null,
|
||||
EstimateApiClient? estimateClient = null)
|
||||
EstimateApiClient? estimateClient = null,
|
||||
bool canIssueEstimates = true)
|
||||
{
|
||||
_billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient));
|
||||
_estimateClient = estimateClient;
|
||||
_settings = settings;
|
||||
CanIssueEstimates = canIssueEstimates;
|
||||
|
||||
if (_settings is not null)
|
||||
{
|
||||
|
|
@ -225,7 +228,8 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi
|
|||
}
|
||||
}
|
||||
|
||||
private bool CanCreateEstimateForSelected() => SelectedQuery is not null && _estimateClient is not null;
|
||||
private bool CanCreateEstimateForSelected()
|
||||
=> SelectedQuery is not null && _estimateClient is not null && CanIssueEstimates;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanCreateEstimateForSelected))]
|
||||
public async Task CreateEstimateForSelectedAsync()
|
||||
|
|
@ -242,6 +246,12 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi
|
|||
return;
|
||||
}
|
||||
|
||||
if (!CanIssueEstimates)
|
||||
{
|
||||
this.SetWarningStatus("Un identifiant d'entreprise est nécessaire pour émettre un devis.");
|
||||
return;
|
||||
}
|
||||
|
||||
var app = (App?)Application.Current;
|
||||
if (app is null)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -113,6 +113,17 @@ public partial class AdministrationPageViewModel
|
|||
throw new InvalidOperationException("Cochez la confirmation avant cette opération destructive.");
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private Task PurgePaymentResiduesAsync() => RunOperationAsync(async client =>
|
||||
{
|
||||
RequireConfirmation();
|
||||
var result = await client.PurgePaymentResiduesAsync();
|
||||
RequireAccess();
|
||||
PaymentPurgeReport = $"{result.Users} compte(s), {result.Subscriptions} abonnement(s), {result.Payments} mensualité(s), {result.Donations} don(s), {result.LegacyPayments} paiement(s) historique(s) purgés.";
|
||||
});
|
||||
|
||||
[ObservableProperty] public partial string PaymentPurgeReport { get; set; } = "";
|
||||
|
||||
partial void OnSelectedClientChanged(AdministrationClient? value)
|
||||
{
|
||||
ClientFields = AdministrationFieldViewModel.From(value?.Settings ?? new ClientSettings());
|
||||
|
|
|
|||
|
|
@ -96,6 +96,17 @@ public partial class AdministrationPageViewModel : ViewModelBase
|
|||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var usage = await _usageClient.GetAdminOverviewAsync().ConfigureAwait(true)
|
||||
?? throw new InvalidOperationException("Le serveur a renvoyé une liste d’usages vide.");
|
||||
if (!_session.IsAdministrator)
|
||||
{
|
||||
ClearAdministrationData();
|
||||
StatusMessage = "Le rôle Administrator est requis.";
|
||||
return;
|
||||
}
|
||||
foreach (var item in usage)
|
||||
UsageOverview.Add(item);
|
||||
|
||||
var query = SearchText.Trim();
|
||||
var usersEndpoint = string.IsNullOrWhiteSpace(query)
|
||||
? new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "users").ToString()
|
||||
|
|
@ -103,11 +114,10 @@ public partial class AdministrationPageViewModel : ViewModelBase
|
|||
|
||||
var users = await _api.CallAsync<List<UserInfo>>(HttpMethod.Get, usersEndpoint).ConfigureAwait(true)
|
||||
?? throw new InvalidOperationException("Le serveur a renvoyé une liste d’utilisateurs vide.");
|
||||
var usage = await _usageClient.GetAdminOverviewAsync().ConfigureAwait(true)
|
||||
?? throw new InvalidOperationException("Le serveur a renvoyé une liste d’usages vide.");
|
||||
|
||||
if (!_session.IsAdministrator)
|
||||
{
|
||||
ClearAdministrationData();
|
||||
StatusMessage = "Le rôle Administrator est requis.";
|
||||
return;
|
||||
}
|
||||
|
|
@ -116,8 +126,6 @@ public partial class AdministrationPageViewModel : ViewModelBase
|
|||
{
|
||||
Users.Add(user);
|
||||
}
|
||||
foreach (var item in usage)
|
||||
UsageOverview.Add(item);
|
||||
|
||||
OnPropertyChanged(nameof(FilteredUsers));
|
||||
OnPropertyChanged(nameof(SelectedUsage));
|
||||
|
|
@ -125,6 +133,16 @@ public partial class AdministrationPageViewModel : ViewModelBase
|
|||
await LoadToolsAsync();
|
||||
StatusMessage = Users.Count > 0 ? $"{Users.Count} utilisateur(s) chargé(s)." : "Aucun utilisateur trouvé.";
|
||||
}
|
||||
catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
|
||||
{
|
||||
if (!_session.IsAdministrator)
|
||||
{
|
||||
ClearAdministrationData();
|
||||
StatusMessage = "Le rôle Administrator est requis.";
|
||||
}
|
||||
else
|
||||
StatusMessage = $"Quota insuffisant : les usages restent consultables. {ex.Message}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClearAdministrationData();
|
||||
|
|
@ -138,6 +156,7 @@ public partial class AdministrationPageViewModel : ViewModelBase
|
|||
|
||||
private void ClearAdministrationData()
|
||||
{
|
||||
PaymentPurgeReport = "";
|
||||
Users.Clear();
|
||||
UsageOverview.Clear();
|
||||
SelectedUser = null;
|
||||
|
|
|
|||
|
|
@ -17,13 +17,24 @@ public partial class AboutPageViewModel : ViewModelBase
|
|||
public const string RepositoryUrl = "https://forgejo.pschneider.fr/notazof/yavsc";
|
||||
public const string IssuesUrl = RepositoryUrl + "/issues";
|
||||
|
||||
public AboutPageViewModel()
|
||||
private readonly Settings? _settings;
|
||||
|
||||
public AboutPageViewModel(Settings? settings = null)
|
||||
{
|
||||
_settings = settings;
|
||||
Version = ReadVersion();
|
||||
}
|
||||
|
||||
public string Version { get; }
|
||||
|
||||
public Uri TermsUri => new(new Uri(
|
||||
(_settings?.Authentication.Authority ?? AuthenticationSettings.DefaultAuthority).TrimEnd('/') + "/"), "Home/CGU");
|
||||
public Uri SubscriptionsUri => new(new Uri(
|
||||
(_settings?.Authentication.Authority ?? AuthenticationSettings.DefaultAuthority).TrimEnd('/') + "/"), "ResourceSubscription");
|
||||
|
||||
[ObservableProperty]
|
||||
public partial string? StatusMessage { get; set; }
|
||||
|
||||
public string Description { get; } =
|
||||
"PostIt est le client de la plateforme Yavsc : blog, devis, " +
|
||||
"demandes de prestations et fichiers personnels.";
|
||||
|
|
@ -49,13 +60,20 @@ public partial class AboutPageViewModel : ViewModelBase
|
|||
[RelayCommand]
|
||||
private Task OpenIssues() => OpenUrlAsync(IssuesUrl);
|
||||
|
||||
private static async Task OpenUrlAsync(string url)
|
||||
[RelayCommand]
|
||||
private Task OpenTerms() => OpenUrlAsync(TermsUri.AbsoluteUri);
|
||||
|
||||
[RelayCommand]
|
||||
private Task OpenSubscriptions() => OpenUrlAsync(SubscriptionsUri.AbsoluteUri);
|
||||
|
||||
private async Task OpenUrlAsync(string url)
|
||||
{
|
||||
StatusMessage = null;
|
||||
var app = (App)App.Current!;
|
||||
var topLevel = TopLevel.GetTopLevel(app.View);
|
||||
if (topLevel is not null)
|
||||
if (topLevel is null || !await topLevel.Launcher.LaunchUriAsync(new Uri(url)).ConfigureAwait(true))
|
||||
{
|
||||
await topLevel.Launcher.LaunchUriAsync(new Uri(url)).ConfigureAwait(true);
|
||||
StatusMessage = "Impossible d'ouvrir le navigateur : " + url;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ using System;
|
|||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Threading;
|
||||
|
|
@ -9,6 +10,7 @@ using CommunityToolkit.Mvvm.Input;
|
|||
using Microsoft.Extensions.DependencyInjection;
|
||||
using PostIt.Services;
|
||||
using PostIt.ViewModels.Chat;
|
||||
using Yavsc.Abstract.Workflow;
|
||||
using Yavsc.Abstract.Models.Messaging;
|
||||
using Yavsc.Api.Client;
|
||||
|
||||
|
|
@ -218,7 +220,11 @@ public class HomePageViewModel : ViewModelBase
|
|||
|
||||
var estimateClient = app.ServiceProvider?.GetRequiredService<EstimateApiClient>();
|
||||
|
||||
var vm = new ProviderOngoingRequestsPageViewModel(billingClient, Settings, estimateClient);
|
||||
var profileEndpoint = new Uri(new Uri(Api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "account/performer-profile").ToString();
|
||||
var profile = await Api.CallAsync<PerformerProfileSettings>(HttpMethod.Get, profileEndpoint).ConfigureAwait(true);
|
||||
var vm = new ProviderOngoingRequestsPageViewModel(
|
||||
billingClient, Settings, estimateClient,
|
||||
canIssueEstimates: profile?.CanIssueEstimates == true);
|
||||
await vm.InitializeAsync();
|
||||
await app.PushPageAsync(vm);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,9 @@ public partial class UserProfilePageViewModel : ViewModelBase
|
|||
private readonly YavscApiClient? _api;
|
||||
private readonly SessionStatusViewModel? _sessionStatus;
|
||||
private readonly ResourceUsageApiClient? _usageClient;
|
||||
private readonly AboutPageViewModel _subscriptionLinks;
|
||||
public IAsyncRelayCommand OpenSubscriptionsCommand => _subscriptionLinks.OpenSubscriptionsCommand;
|
||||
public string? SubscriptionLinkError => _subscriptionLinks.StatusMessage;
|
||||
|
||||
[ObservableProperty]
|
||||
public partial ResourceUsageSummary? ResourceUsage { get; set; }
|
||||
|
|
@ -158,6 +161,8 @@ public partial class UserProfilePageViewModel : ViewModelBase
|
|||
_api = api;
|
||||
_sessionStatus = sessionStatus;
|
||||
_usageClient = usageClient;
|
||||
_subscriptionLinks = new AboutPageViewModel(api?.Settings);
|
||||
_subscriptionLinks.PropertyChanged += (_, _) => OnPropertyChanged(nameof(SubscriptionLinkError));
|
||||
}
|
||||
|
||||
public UserProfilePageViewModel() : this(null, null) { }
|
||||
|
|
@ -167,19 +172,18 @@ public partial class UserProfilePageViewModel : ViewModelBase
|
|||
[RelayCommand]
|
||||
public async Task RefreshAsync()
|
||||
{
|
||||
if (_api is null)
|
||||
{
|
||||
IsProfileLoaded = false;
|
||||
StatusMessage = "Client API de profil indisponible.";
|
||||
return;
|
||||
}
|
||||
|
||||
IsBusy = true;
|
||||
IsProfileLoaded = false;
|
||||
ResourceUsage = null;
|
||||
UsageError = null;
|
||||
try
|
||||
{
|
||||
await LoadUsageAsync();
|
||||
if (_api is null)
|
||||
{
|
||||
StatusMessage = "Client API de profil indisponible.";
|
||||
return;
|
||||
}
|
||||
var me = await _api.CallAsync<Me>(HttpMethod.Get, new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "account/me").ToString()).ConfigureAwait(true);
|
||||
if (me is null)
|
||||
{
|
||||
|
|
@ -218,18 +222,6 @@ public partial class UserProfilePageViewModel : ViewModelBase
|
|||
}
|
||||
IsProfileLoaded = true;
|
||||
StatusMessage = "Profil chargé.";
|
||||
if (_usageClient is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
ResourceUsage = await _usageClient.GetCurrentAsync()
|
||||
?? throw new InvalidOperationException("Le serveur a renvoyé un usage vide.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
UsageError = $"Impossible de charger mon usage : {ex.Message}";
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -264,6 +256,24 @@ public partial class UserProfilePageViewModel : ViewModelBase
|
|||
}
|
||||
}
|
||||
|
||||
private async Task LoadUsageAsync()
|
||||
{
|
||||
if (_usageClient is null)
|
||||
{
|
||||
UsageError = "Client API de consommation indisponible.";
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
ResourceUsage = await _usageClient.GetCurrentAsync()
|
||||
?? throw new InvalidOperationException("Le serveur a renvoyé un usage vide.");
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or JsonException or InvalidOperationException)
|
||||
{
|
||||
UsageError = $"Impossible de charger mon usage : {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
public ProfileUpdateRequest BuildProfileUpdateRequest()
|
||||
{
|
||||
static string NormalizeField(string? value, string placeholder)
|
||||
|
|
|
|||
|
|
@ -44,9 +44,11 @@ public partial class PerformerConfigurationPageViewModel : ViewModelBase
|
|||
[ObservableProperty]
|
||||
public partial string ExerciseCountryCode { get; set; } = "fr";
|
||||
|
||||
[ObservableProperty]
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(IsAmateur))]
|
||||
public partial string SIREN { get; set; } = string.Empty;
|
||||
|
||||
public bool IsAmateur => string.IsNullOrWhiteSpace(SIREN);
|
||||
|
||||
[ObservableProperty]
|
||||
public partial string Website { get; set; } = string.Empty;
|
||||
|
||||
|
|
|
|||
|
|
@ -35,8 +35,30 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
private Control? _capturePreview;
|
||||
private bool _restoringPreferences;
|
||||
private bool _keepScreenOnDuringCapture;
|
||||
private bool _blurPodcastBackground;
|
||||
private Guid? _obsPodcastId;
|
||||
private int _obsVersion;
|
||||
[ObservableProperty] public partial string ObsServerUrl { get; set; } = "";
|
||||
[ObservableProperty] public partial string ObsStreamKey { get; set; } = "";
|
||||
[ObservableProperty] public partial string ObsStatus { get; set; } = "";
|
||||
private IDisposable? _screenAwake;
|
||||
public bool SupportsCaptureScreenAwake => OperatingSystem.IsAndroid();
|
||||
public bool SupportsPodcastBackgroundBlur => Platform.CreateBlurredPodcastCaptureAsync is not null
|
||||
&& Platform.CreateBlurredPodcastPreviewAsync is not null;
|
||||
public bool CanChangePodcastBackgroundBlur => !IsCapturing && !IsBusy;
|
||||
public bool BlurPodcastBackground
|
||||
{
|
||||
get => _blurPodcastBackground;
|
||||
set
|
||||
{
|
||||
if (!SetProperty(ref _blurPodcastBackground, value)) return;
|
||||
if (!_restoringPreferences)
|
||||
{
|
||||
_api.Settings.PodcastBlurBackground = value;
|
||||
SavePreferences();
|
||||
}
|
||||
}
|
||||
}
|
||||
public bool KeepScreenOnDuringCapture
|
||||
{
|
||||
get => _keepScreenOnDuringCapture;
|
||||
|
|
@ -118,6 +140,7 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
{
|
||||
if (!SetProperty(ref _isBroadcasting, value)) return;
|
||||
OnPropertyChanged(nameof(IsCapturing));
|
||||
OnPropertyChanged(nameof(CanChangePodcastBackgroundBlur));
|
||||
UpdateScreenAwake();
|
||||
UpdateCommands();
|
||||
}
|
||||
|
|
@ -126,7 +149,12 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
public bool IsBusy
|
||||
{
|
||||
get => _busy;
|
||||
private set { if (SetProperty(ref _busy, value)) UpdateCommands(); }
|
||||
private set
|
||||
{
|
||||
if (!SetProperty(ref _busy, value)) return;
|
||||
OnPropertyChanged(nameof(CanChangePodcastBackgroundBlur));
|
||||
UpdateCommands();
|
||||
}
|
||||
}
|
||||
|
||||
public CaptureDevice? SelectedCamera
|
||||
|
|
@ -165,6 +193,7 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
set
|
||||
{
|
||||
if (!SetProperty(ref _selected, value)) return;
|
||||
if (_obsPodcastId != value?.Id) ClearObsCredentials();
|
||||
if (value is { State: PodcastState.Planned } && value.OwnerId == _ownerId)
|
||||
{
|
||||
_title = value.Title;
|
||||
|
|
@ -192,6 +221,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
public IAsyncRelayCommand FinishCommand { get; }
|
||||
public IAsyncRelayCommand DeleteCommand { get; }
|
||||
public IAsyncRelayCommand RetryReplayCommand { get; }
|
||||
public IAsyncRelayCommand ActivateObsCommand { get; }
|
||||
public IAsyncRelayCommand DeactivateObsCommand { get; }
|
||||
public override bool CanNavigateNext { get => false; protected set { } }
|
||||
public override bool CanNavigatePrevious { get => !IsBroadcasting; protected set { } }
|
||||
|
||||
|
|
@ -201,6 +232,12 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
_api = api;
|
||||
_session = session;
|
||||
RefreshCommand = new AsyncRelayCommand(RefreshAsync, () => !IsBusy);
|
||||
ActivateObsCommand = new AsyncRelayCommand(ActivateObsAsync,
|
||||
() => !IsBusy && !IsCapturing && _session.IsLoggedIn
|
||||
&& SelectedPodcast is { State: PodcastState.Planned } p && p.OwnerId == _ownerId);
|
||||
DeactivateObsCommand = new AsyncRelayCommand(DeactivateObsAsync,
|
||||
() => !IsBusy && !IsBroadcasting && _session.IsLoggedIn
|
||||
&& SelectedPodcast is { FlowId: not null } p && p.OwnerId == _ownerId);
|
||||
DetectDevicesCommand = new RelayCommand(DetectDevices, () => CanBroadcast && !IsCapturing && !IsBusy);
|
||||
PreviewCommand = new AsyncRelayCommand(StartPreviewAsync,
|
||||
() => CanBroadcast && !IsCapturing && !IsBusy && _session.IsLoggedIn && SelectedCamera is not null);
|
||||
|
|
@ -231,6 +268,7 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
&& p.OwnerId == _ownerId && !IsBroadcasting && !IsBusy);
|
||||
_title = _api.Settings.PodcastDefaultTitle;
|
||||
_keepScreenOnDuringCapture = _api.Settings.PodcastKeepScreenOn;
|
||||
_blurPodcastBackground = _api.Settings.PodcastBlurBackground;
|
||||
_restoringPreferences = true;
|
||||
try
|
||||
{
|
||||
|
|
@ -273,6 +311,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
FinishCommand.NotifyCanExecuteChanged();
|
||||
DeleteCommand.NotifyCanExecuteChanged();
|
||||
RetryReplayCommand.NotifyCanExecuteChanged();
|
||||
ActivateObsCommand.NotifyCanExecuteChanged();
|
||||
DeactivateObsCommand.NotifyCanExecuteChanged();
|
||||
OnPropertyChanged(nameof(CanNavigatePrevious));
|
||||
}
|
||||
|
||||
|
|
@ -282,10 +322,18 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
try
|
||||
{
|
||||
var profileUrl = new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/"), "account/me");
|
||||
_ownerId = (await _api.CallAsync<Me>(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId;
|
||||
var ownerId = (await _api.CallAsync<Me>(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId;
|
||||
if (_ownerId != ownerId) ClearObsCredentials();
|
||||
_ownerId = ownerId;
|
||||
var podcasts = await _client.ListAsync();
|
||||
Podcasts.Clear();
|
||||
foreach (var podcast in podcasts) Podcasts.Add(podcast);
|
||||
if (SelectedPodcast is { FlowId: not null } selected && selected.OwnerId == _ownerId)
|
||||
{
|
||||
var obs = await _client.ObsStatusAsync(selected.Id);
|
||||
ObsStatus = obs.Error ?? (obs.Enabled ? "Entree SRT activee. Le direct commence a la reception des premiers medias." : "Entree OBS desactivee.");
|
||||
if (!obs.Enabled) ClearObsCredentials(clearStatus: false);
|
||||
}
|
||||
Status = "Directs et replays reserves aux utilisateurs connectes.";
|
||||
}
|
||||
catch (Exception ex) { Status = $"Chargement impossible : {ex.Message}"; }
|
||||
|
|
@ -322,10 +370,13 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
|
||||
public async Task ActivateAsync()
|
||||
{
|
||||
_session.LogoutCompleted -= ClearObsOnLogout;
|
||||
_session.LogoutCompleted += ClearObsOnLogout;
|
||||
_restoringPreferences = true;
|
||||
try
|
||||
{
|
||||
KeepScreenOnDuringCapture = _api.Settings.PodcastKeepScreenOn;
|
||||
BlurPodcastBackground = _api.Settings.PodcastBlurBackground;
|
||||
Cameras.Clear();
|
||||
Microphones.Clear();
|
||||
foreach (var device in _api.Settings.PodcastCameras) Cameras.Add(device);
|
||||
|
|
@ -343,11 +394,69 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
|
||||
public async Task DeactivateAsync()
|
||||
{
|
||||
_session.LogoutCompleted -= ClearObsOnLogout;
|
||||
ClearObsCredentials();
|
||||
_pageCancellation.Cancel();
|
||||
await StopPreviewAsync();
|
||||
if (_broadcaster is not null) await StopAsync();
|
||||
}
|
||||
|
||||
private void ClearObsOnLogout()
|
||||
{
|
||||
ClearObsCredentials();
|
||||
_ownerId = null;
|
||||
SelectedPodcast = null;
|
||||
UpdateCommands();
|
||||
}
|
||||
|
||||
private void ClearObsCredentials(bool clearStatus = true)
|
||||
{
|
||||
ObsServerUrl = "";
|
||||
ObsStreamKey = "";
|
||||
_obsPodcastId = null;
|
||||
_obsVersion++;
|
||||
if (clearStatus) ObsStatus = "";
|
||||
}
|
||||
|
||||
private async Task ActivateObsAsync()
|
||||
{
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez une emission programmee.");
|
||||
var owner = _ownerId;
|
||||
ClearObsCredentials();
|
||||
var version = _obsVersion;
|
||||
var token = _pageCancellation.Token;
|
||||
var credentials = await _client.ActivateObsAsync(podcast.Id, token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (_obsVersion != version || !_session.IsLoggedIn || _ownerId != owner || SelectedPodcast?.Id != podcast.Id)
|
||||
throw new InvalidOperationException("La session ou l'emission a change ; les identifiants OBS ne seront pas affiches.");
|
||||
_obsPodcastId = podcast.Id;
|
||||
ObsServerUrl = credentials.ServerUrl;
|
||||
ObsStreamKey = credentials.StreamKey;
|
||||
ObsStatus = $"Copiez l'URL SRT secrete dans OBS avant {credentials.ExpiresAt.ToLocalTime():g}, avec la cle de stream vide. Cette URL remplace la precedente.";
|
||||
}
|
||||
|
||||
catch (Exception ex) { Status = $"Activation OBS impossible : {ex.Message}"; }
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
private async Task DeactivateObsAsync()
|
||||
{
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez une emission.");
|
||||
await _client.DeactivateObsAsync(podcast.Id);
|
||||
ClearObsCredentials();
|
||||
ObsStatus = "Cle revoquee et diffuseur deconnecte. Le replay est finalise apres l'arret de la reception.";
|
||||
await RefreshAsync();
|
||||
}
|
||||
catch (Exception ex) { Status = $"Desactivation OBS impossible : {ex.Message}"; }
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
private void DetectDevices()
|
||||
{
|
||||
_restoringPreferences = true;
|
||||
|
|
@ -393,7 +502,11 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
ct.ThrowIfCancellationRequested();
|
||||
if (_previewCapture is not null) return;
|
||||
var camera = SelectedCamera?.Value ?? throw new InvalidOperationException("Choisissez une camera.");
|
||||
capture = Platform.CreatePodcastPreviewAsync is { } createPreview
|
||||
var previewFactory = BlurPodcastBackground && OperatingSystem.IsAndroid()
|
||||
? Platform.CreateBlurredPodcastPreviewAsync
|
||||
?? throw new InvalidOperationException("Le flou d'arriere-plan n'est pas disponible sur cet appareil.")
|
||||
: Platform.CreatePodcastPreviewAsync;
|
||||
capture = previewFactory is { } createPreview
|
||||
? await createPreview(camera, ct)
|
||||
: new LibVlcPodcastCapture(
|
||||
vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, null), null, preview: true);
|
||||
|
|
@ -422,6 +535,7 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
{
|
||||
OnPropertyChanged(nameof(IsPreviewing));
|
||||
OnPropertyChanged(nameof(IsCapturing));
|
||||
OnPropertyChanged(nameof(CanChangePodcastBackgroundBlur));
|
||||
UpdateScreenAwake();
|
||||
UpdateCommands();
|
||||
}
|
||||
|
|
@ -469,7 +583,11 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
var microphone = string.IsNullOrWhiteSpace(SelectedMicrophone?.Value) ? null : SelectedMicrophone.Value;
|
||||
if (Platform.RequestPodcastPermissionsAsync is { } requestPermissions)
|
||||
await requestPermissions(microphone, _pageCancellation.Token);
|
||||
_broadcaster = Platform.CreatePodcastCaptureAsync is { } createCapture
|
||||
var captureFactory = BlurPodcastBackground && OperatingSystem.IsAndroid()
|
||||
? Platform.CreateBlurredPodcastCaptureAsync
|
||||
?? throw new InvalidOperationException("Le flou d'arriere-plan n'est pas disponible sur cet appareil.")
|
||||
: Platform.CreatePodcastCaptureAsync;
|
||||
_broadcaster = captureFactory is { } createCapture
|
||||
? await PodcastBroadcaster.StartAsync(_client, Title,
|
||||
(directory, ct) => createCapture(camera, microphone, directory, ct), _pageCancellation.Token, SelectedPodcast?.Id)
|
||||
: await PodcastBroadcaster.StartAsync(_client, Title, camera, microphone, _pageCancellation.Token, SelectedPodcast?.Id);
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ public partial class AuthenticationSettings : ObservableObject
|
|||
/// in <c>PostIt.Android/Properties/AndroidManifest.xml</c> must match.
|
||||
/// </summary>
|
||||
public const string AndroidRedirectUri = "android://postit-signin";
|
||||
public const string BrowserRedirectUri = "https://postit.pschneider.fr/callback";
|
||||
|
||||
|
||||
public const string DefaultAuthority = "https://yavsc.pschneider.fr";
|
||||
|
||||
|
|
|
|||
|
|
@ -61,6 +61,8 @@ public partial class Settings : ViewModelBase
|
|||
[ObservableProperty]
|
||||
public partial bool PodcastKeepScreenOn { get; set; }
|
||||
[ObservableProperty]
|
||||
public partial bool PodcastBlurBackground { get; set; }
|
||||
[ObservableProperty]
|
||||
public partial string? LanCallAddress { get; set; }
|
||||
[ObservableProperty]
|
||||
public partial bool AndroidKeepChatConnected { get; set; }
|
||||
|
|
@ -169,6 +171,7 @@ public partial class Settings : ViewModelBase
|
|||
partial void OnPodcastCameraIdChanged(string? value) => MarkDirty();
|
||||
partial void OnPodcastMicrophoneIdChanged(string? value) => MarkDirty();
|
||||
partial void OnPodcastKeepScreenOnChanged(bool value) => MarkDirty();
|
||||
partial void OnPodcastBlurBackgroundChanged(bool value) => MarkDirty();
|
||||
partial void OnLanCallAddressChanged(string? value) => MarkDirty();
|
||||
partial void OnAndroidKeepChatConnectedChanged(bool value) => MarkDirty();
|
||||
partial void OnChatRoomsByAccountChanged(Dictionary<string, string[]> value) => MarkDirty();
|
||||
|
|
@ -435,6 +438,7 @@ public partial class Settings : ViewModelBase
|
|||
PodcastCameraId = settings.PodcastCameraId;
|
||||
PodcastMicrophoneId = settings.PodcastMicrophoneId;
|
||||
PodcastKeepScreenOn = settings.PodcastKeepScreenOn;
|
||||
PodcastBlurBackground = settings.PodcastBlurBackground;
|
||||
LanCallAddress = settings.LanCallAddress;
|
||||
AndroidKeepChatConnected = settings.AndroidKeepChatConnected;
|
||||
ChatRoomsByAccount = settings.ChatRoomsByAccount ?? new();
|
||||
|
|
@ -446,7 +450,7 @@ public partial class Settings : ViewModelBase
|
|||
this.Authentication.ClientId = string.IsNullOrWhiteSpace(settings.Authentication.ClientId) ?
|
||||
AuthenticationSettings.DefaultClientId : settings.Authentication.ClientId;
|
||||
this.Authentication.RedirectUri = string.IsNullOrWhiteSpace(settings.Authentication.RedirectUri) ?
|
||||
AuthenticationSettings.DesktopRedirectUri : settings.Authentication.RedirectUri;
|
||||
AuthenticationSettings.BrowserRedirectUri : settings.Authentication.RedirectUri;
|
||||
if (settings.Authentication.Scopes is null || settings.Authentication.Scopes.Length == 0)
|
||||
{
|
||||
this.Authentication.Scopes = AuthenticationSettings.DefaultScopes;
|
||||
|
|
@ -509,7 +513,7 @@ public partial class Settings : ViewModelBase
|
|||
{
|
||||
Authority = AuthenticationSettings.DefaultAuthority,
|
||||
ClientId = AuthenticationSettings.DefaultClientId,
|
||||
RedirectUri = AuthenticationSettings.DesktopRedirectUri,
|
||||
RedirectUri = AuthenticationSettings.BrowserRedirectUri,
|
||||
Scopes = AuthenticationSettings.DefaultScopes
|
||||
};
|
||||
this.DarkMode = false;
|
||||
|
|
|
|||
|
|
@ -28,11 +28,14 @@
|
|||
Opacity="0.7" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="2"
|
||||
Text="Astuce: sélectionnez une ligne puis ouvrez le détail ou l'édition directe."
|
||||
Opacity="0.65"
|
||||
FontSize="11"
|
||||
Margin="0,0,0,8" />
|
||||
<StackPanel Grid.Row="2" Spacing="3" Margin="0,0,0,8">
|
||||
<TextBlock Text="Astuce: sélectionnez une ligne puis ouvrez le détail ou l'édition directe."
|
||||
Opacity="0.65"
|
||||
FontSize="11" />
|
||||
<TextBlock Text="Profil amateur : l’émission de devis et la facturation sont désactivées tant qu’un identifiant d’entreprise n’est pas renseigné."
|
||||
IsVisible="{Binding !CanIssueEstimates}"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<Grid Grid.Row="3" RowDefinitions="*,Auto">
|
||||
<ListBox Grid.Row="0"
|
||||
|
|
|
|||
|
|
@ -155,7 +155,6 @@
|
|||
</CommandBar.SecondaryCommands>
|
||||
</CommandBar>
|
||||
</NavigationPage.TopCommandBar>
|
||||
<ScrollViewer>
|
||||
<Grid
|
||||
x:Name="MainGrid"
|
||||
Margin="5,5,10,5"
|
||||
|
|
@ -239,7 +238,6 @@
|
|||
IsVisible="{Binding IsEditing}"
|
||||
RowSpacing="10">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
|
|
@ -248,18 +246,15 @@
|
|||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock
|
||||
Grid.Row="0"
|
||||
FontWeight="SemiBold"
|
||||
Text="Post detail" />
|
||||
<TextBox
|
||||
x:Name="DraftTitleTextBox"
|
||||
Grid.Row="1"
|
||||
Grid.Row="0"
|
||||
PlaceholderText="Title"
|
||||
Text="{Binding DraftTitle, Mode=TwoWay}" />
|
||||
|
||||
<postitControls:MarkdownEditorControl
|
||||
Grid.Row="2"
|
||||
x:Name="ArticleEditor"
|
||||
Grid.Row="1"
|
||||
HorizontalAlignment="Stretch"
|
||||
VerticalAlignment="Stretch"
|
||||
Document="{Binding DraftArticleDocument, Mode=TwoWay}"
|
||||
|
|
@ -268,12 +263,13 @@
|
|||
|
||||
<Border
|
||||
x:Name="AttachmentsBorder"
|
||||
Grid.Row="3"
|
||||
Grid.Row="2"
|
||||
Padding="8"
|
||||
HorizontalAlignment="Stretch"
|
||||
VerticalAlignment="Stretch"
|
||||
BorderBrush="LightGray"
|
||||
BorderThickness="1">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock FontWeight="SemiBold" Text="Pièces jointes" />
|
||||
<ItemsControl ItemsSource="{Binding DraftAttachments}">
|
||||
|
|
@ -284,6 +280,7 @@
|
|||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
|
||||
</Grid>
|
||||
|
|
@ -335,5 +332,4 @@
|
|||
Grid.Row="5"
|
||||
DataContext="{Binding ActionStatus}" />
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
</ContentPage>
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@ using Avalonia.Layout;
|
|||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.VisualTree;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Markdown.Avalonia;
|
||||
|
||||
|
|
@ -17,11 +20,14 @@ public partial class BlogsPage : ContentPage
|
|||
private static readonly RelayCommand<string?> DisabledLinkCommand =
|
||||
new(static _ => { }, static _ => false);
|
||||
private bool? _isWideLayout;
|
||||
private bool? _isCompactEditor;
|
||||
private ViewModels.BlogsViewModel? _observedViewModel;
|
||||
|
||||
public BlogsPage()
|
||||
{
|
||||
InitializeComponent();
|
||||
AddHandler(InputElement.GotFocusEvent, (_, _) => QueueLayoutUpdate(), RoutingStrategies.Bubble);
|
||||
AddHandler(InputElement.LostFocusEvent, (_, _) => QueueLayoutUpdate(), RoutingStrategies.Bubble);
|
||||
SizeChanged += (_, _) =>
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
|
|
@ -38,6 +44,9 @@ public partial class BlogsPage : ContentPage
|
|||
UpdateHyperlinkCommand();
|
||||
}
|
||||
|
||||
private void QueueLayoutUpdate()
|
||||
=> Avalonia.Threading.Dispatcher.UIThread.Post(UpdateResponsiveLayout);
|
||||
|
||||
private void UpdateResponsiveLayout()
|
||||
{
|
||||
var size = TopLevel.GetTopLevel(this)?.ClientSize ?? Bounds.Size;
|
||||
|
|
@ -46,6 +55,23 @@ public partial class BlogsPage : ContentPage
|
|||
|
||||
// Use the window size so compacting the navigation bar cannot change the orientation.
|
||||
var isWide = size.Width >= size.Height;
|
||||
var compact = this.FindAncestorOfType<MainView>()?.IsSoftKeyboardOpen == true
|
||||
&& ArticleEditor.IsKeyboardFocusWithin && !ArticleEditor.IsPreviewVisible;
|
||||
var sideBySide = compact && isWide;
|
||||
if (_isCompactEditor != compact || _isWideLayout != isWide)
|
||||
{
|
||||
_isCompactEditor = compact;
|
||||
DraftTitleTextBox.IsVisible = !compact || !System.OperatingSystem.IsAndroid();
|
||||
PostEditor.ColumnDefinitions = new ColumnDefinitions(sideBySide ? "3*,2*" : "*");
|
||||
SetArea(ArticleEditor, sideBySide ? 0 : 1, 0, rowSpan: sideBySide ? 3 : 1);
|
||||
SetArea(DraftTitleTextBox, 0, sideBySide ? 1 : 0);
|
||||
SetArea(AttachmentsBorder, sideBySide ? 1 : 2, sideBySide ? 1 : 0);
|
||||
ArticleEditor.SourceEditor.Padding = compact ? new Thickness(2) : new Thickness(5, 5, 5, 15);
|
||||
PostEditor.Margin = new Thickness(compact ? 4 : 12);
|
||||
PostEditor.RowSpacing = compact ? 2 : 10;
|
||||
}
|
||||
SetArea(StatusBar, sideBySide ? 1 : isWide ? 3 : 5, sideBySide ? 2 : 0,
|
||||
columnSpan: isWide && !sideBySide ? 3 : 1);
|
||||
if (_isWideLayout == isWide)
|
||||
return;
|
||||
_isWideLayout = isWide;
|
||||
|
|
@ -58,7 +84,6 @@ public partial class BlogsPage : ContentPage
|
|||
SetArea(PostsSplitter, isWide ? 0 : 3, isWide ? 1 : 0, isWide ? 3 : 1);
|
||||
SetArea(PostReader, isWide ? 0 : 4, 0, isWide ? 3 : 1);
|
||||
SetArea(PostEditor, isWide ? 0 : 4, 0, isWide ? 3 : 1);
|
||||
SetArea(StatusBar, isWide ? 3 : 5, 0, columnSpan: isWide ? 3 : 1);
|
||||
PostsSplitter.ResizeDirection = isWide ? GridResizeDirection.Columns : GridResizeDirection.Rows;
|
||||
PostsSplitter.HorizontalAlignment = isWide ? HorizontalAlignment.Center : HorizontalAlignment.Stretch;
|
||||
PostsSplitter.VerticalAlignment = isWide ? VerticalAlignment.Stretch : VerticalAlignment.Center;
|
||||
|
|
|
|||
|
|
@ -34,5 +34,12 @@
|
|||
<Button Content="Signaler un problème"
|
||||
Command="{Binding OpenIssuesCommand}"
|
||||
HorizontalAlignment="Center"/>
|
||||
<Button Content="CGU de PostIt et de Yavsc"
|
||||
Command="{Binding OpenTermsCommand}"
|
||||
HorizontalAlignment="Center"/>
|
||||
<Button Content="Abonnements Découverte et Premium"
|
||||
Command="{Binding OpenSubscriptionsCommand}"
|
||||
HorizontalAlignment="Center"/>
|
||||
<TextBlock Text="{Binding StatusMessage}" TextWrapping="Wrap" MaxWidth="420"/>
|
||||
</StackPanel>
|
||||
</ContentPage>
|
||||
|
|
|
|||
|
|
@ -77,6 +77,9 @@
|
|||
TextWrapping="Wrap"/>
|
||||
<CheckBox Content="Je confirme la prochaine suppression, exclusion, régénération ou import."
|
||||
IsChecked="{Binding ConfirmDestructiveAction, Mode=TwoWay}"/>
|
||||
<Button Content="Purger les paiements résiduels des comptes retirés depuis un an"
|
||||
Command="{Binding PurgePaymentResiduesCommand}" IsEnabled="{Binding !IsBusy}"/>
|
||||
<TextBlock Text="{Binding PaymentPurgeReport}" TextWrapping="Wrap"/>
|
||||
</StackPanel>
|
||||
|
||||
<TabControl Grid.Row="2" IsEnabled="{Binding !IsBusy}">
|
||||
|
|
@ -119,8 +122,13 @@
|
|||
<TextBlock Text="Usage des ressources" FontWeight="Bold"/>
|
||||
<TextBlock Text="{Binding ApiCalls, StringFormat='Appels API : {0:F0}'}"/>
|
||||
<TextBlock Text="{Binding CpuSeconds, StringFormat='CPU : {0:F3} s'}"/>
|
||||
<TextBlock Text="{Binding BandwidthMb, StringFormat='Bande passante : {0:F3} Mo'}"/>
|
||||
<TextBlock Text="{Binding StorageMb, StringFormat='Stockage : {0:F3} Mo'}"/>
|
||||
<TextBlock Text="{Binding BandwidthMb, StringFormat='Bande passante : {0:F3} Mio'}"/>
|
||||
<TextBlock Text="{Binding StorageMb, StringFormat='Stockage ajouté : {0:F3} Mio'}"/>
|
||||
<TextBlock Text="{Binding Consumption, StringFormat='Consommation : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding CreditBalance, StringFormat='Crédit reporté : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding ConsumptionLimit, StringFormat='Seuil : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding RemainingConsumption, StringFormat='Solde : {0:F3} points'}"/>
|
||||
<TextBlock Text="Quota atteint" IsVisible="{Binding IsQuotaReached}"/>
|
||||
<TextBlock Text="{Binding EstimatedCompensation, StringFormat='Estimation : {0:F2}'}"/>
|
||||
<TextBlock Text="{Binding Currency}"/>
|
||||
</StackPanel>
|
||||
|
|
@ -141,8 +149,13 @@
|
|||
<TextBlock Text="{Binding UserId}"/>
|
||||
<TextBlock Text="{Binding ApiCalls, StringFormat='Appels API : {0:F0}'}"/>
|
||||
<TextBlock Text="{Binding CpuSeconds, StringFormat='CPU : {0:F3} s'}"/>
|
||||
<TextBlock Text="{Binding BandwidthMb, StringFormat='Bande passante : {0:F3} Mo'}"/>
|
||||
<TextBlock Text="{Binding StorageMb, StringFormat='Stockage : {0:F3} Mo'}"/>
|
||||
<TextBlock Text="{Binding BandwidthMb, StringFormat='Bande passante : {0:F3} Mio'}"/>
|
||||
<TextBlock Text="{Binding StorageMb, StringFormat='Stockage ajouté : {0:F3} Mio'}"/>
|
||||
<TextBlock Text="{Binding Consumption, StringFormat='Consommation : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding CreditBalance, StringFormat='Crédit reporté : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding ConsumptionLimit, StringFormat='Seuil : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding RemainingConsumption, StringFormat='Solde : {0:F3} points'}"/>
|
||||
<TextBlock Text="Quota atteint" IsVisible="{Binding IsQuotaReached}"/>
|
||||
<TextBlock Text="{Binding EstimatedCompensation, StringFormat='Estimation : {0:F2}'}"/>
|
||||
<TextBlock Text="{Binding Currency}"/>
|
||||
</StackPanel>
|
||||
|
|
|
|||
|
|
@ -1,13 +1,75 @@
|
|||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Platform;
|
||||
|
||||
namespace PostIt.Views;
|
||||
|
||||
public partial class MainView : UserControl
|
||||
{
|
||||
private IInputPane? _inputPane;
|
||||
private IInsetsManager? _insetsManager;
|
||||
private Thickness _safeArea;
|
||||
private Rect? _keyboardRect;
|
||||
internal bool IsSoftKeyboardOpen { get; private set; }
|
||||
|
||||
public MainView()
|
||||
{
|
||||
InitializeComponent();
|
||||
TopLevel.SetAutoSafeAreaPadding(this, false);
|
||||
AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
var topLevel = TopLevel.GetTopLevel(this);
|
||||
_inputPane = topLevel?.InputPane;
|
||||
_insetsManager = topLevel?.InsetsManager;
|
||||
if (_insetsManager is not null)
|
||||
{
|
||||
_insetsManager.SafeAreaChanged += SafeAreaChanged;
|
||||
_safeArea = _insetsManager.SafeAreaPadding;
|
||||
}
|
||||
if (_inputPane is not null)
|
||||
{
|
||||
_inputPane.StateChanged += InputPaneStateChanged;
|
||||
ApplyKeyboardOcclusion(_inputPane.State == InputPaneState.Open ? _inputPane.OccludedRect : null);
|
||||
}
|
||||
ApplyKeyboardOcclusion(_keyboardRect);
|
||||
};
|
||||
DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
if (_inputPane is not null)
|
||||
_inputPane.StateChanged -= InputPaneStateChanged;
|
||||
_inputPane = null;
|
||||
if (_insetsManager is not null)
|
||||
_insetsManager.SafeAreaChanged -= SafeAreaChanged;
|
||||
_insetsManager = null;
|
||||
};
|
||||
SizeChanged += (_, _) => ApplyKeyboardOcclusion(_keyboardRect);
|
||||
}
|
||||
|
||||
private void InputPaneStateChanged(object? sender, InputPaneStateEventArgs e)
|
||||
=> ApplyKeyboardOcclusion(e.NewState == InputPaneState.Open ? e.EndRect : null);
|
||||
|
||||
private void SafeAreaChanged(object? sender, SafeAreaChangedArgs e)
|
||||
=> ApplySafeArea(e.SafeAreaPadding);
|
||||
|
||||
internal void ApplySafeArea(Thickness safeArea)
|
||||
{
|
||||
_safeArea = safeArea;
|
||||
ApplyKeyboardOcclusion(_keyboardRect);
|
||||
}
|
||||
|
||||
internal void ApplyKeyboardOcclusion(Rect? keyboardRect)
|
||||
{
|
||||
_keyboardRect = keyboardRect;
|
||||
IsSoftKeyboardOpen = keyboardRect is { Height: > 0 };
|
||||
var topLevel = TopLevel.GetTopLevel(this);
|
||||
var bottom = topLevel is null ? null : this.TranslatePoint(new Point(0, Bounds.Height), topLevel);
|
||||
// Subtract only actual overlap: AdjustResize may already have removed the keyboard area.
|
||||
var overlap = keyboardRect is { Height: > 0 } rect && bottom is { } point
|
||||
? Math.Clamp(point.Y - rect.Top, 0, Bounds.Height)
|
||||
: 0;
|
||||
Padding = new Thickness(_safeArea.Left, _safeArea.Top, _safeArea.Right,
|
||||
Math.Max(_safeArea.Bottom, overlap));
|
||||
}
|
||||
|
||||
protected override void OnDataContextChanged(EventArgs e)
|
||||
|
|
|
|||
|
|
@ -23,7 +23,10 @@
|
|||
<TextBox Text="{Binding ExerciseCountryCode, Mode=TwoWay}"
|
||||
PlaceholderText="Code pays (fr, en...)"/>
|
||||
<TextBox Text="{Binding SIREN, Mode=TwoWay}"
|
||||
PlaceholderText="SIREN"/>
|
||||
PlaceholderText="SIREN / SIRET (facultatif)"/>
|
||||
<TextBlock Text="Sans identifiant d’entreprise, votre profil reste utilisable comme amateur. L’émission de devis et la facturation sont alors désactivées."
|
||||
IsVisible="{Binding IsAmateur}"
|
||||
TextWrapping="Wrap"/>
|
||||
<TextBox Text="{Binding Website, Mode=TwoWay}"
|
||||
PlaceholderText="Site web"/>
|
||||
|
||||
|
|
|
|||
|
|
@ -31,11 +31,22 @@
|
|||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="Mon usage des ressources" FontSize="18" FontWeight="SemiBold"/>
|
||||
<TextBlock Text="{Binding UsageError}" TextWrapping="Wrap"/>
|
||||
<Button Content="Abonnements Découverte et Premium"
|
||||
Command="{Binding OpenSubscriptionsCommand}"/>
|
||||
<TextBlock Text="{Binding SubscriptionLinkError}" TextWrapping="Wrap"/>
|
||||
<StackPanel DataContext="{Binding ResourceUsage}" Spacing="4">
|
||||
<TextBlock Text="{Binding ApiCalls, StringFormat='Appels API : {0:F0}'}"/>
|
||||
<TextBlock Text="{Binding CpuSeconds, StringFormat='CPU : {0:F3} s'}"/>
|
||||
<TextBlock Text="{Binding BandwidthMb, StringFormat='Bande passante : {0:F3} Mo'}"/>
|
||||
<TextBlock Text="{Binding StorageMb, StringFormat='Stockage : {0:F3} Mo'}"/>
|
||||
<TextBlock Text="{Binding BandwidthMb, StringFormat='Bande passante : {0:F3} Mio'}"/>
|
||||
<TextBlock Text="{Binding StorageMb, StringFormat='Stockage ajouté : {0:F3} Mio'}"/>
|
||||
<TextBlock Text="{Binding Consumption, StringFormat='Consommation : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding GrossConsumption, StringFormat='Consommation brute : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding AppliedCredits, StringFormat='Usage effacé : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding CreditBalance, StringFormat='Crédit reporté disponible : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding ConsumptionLimit, StringFormat='Seuil : {0:F3} points'}"/>
|
||||
<TextBlock Text="{Binding RemainingConsumption, StringFormat='Solde : {0:F3} points'}"/>
|
||||
<TextBlock Text="Quota atteint : les opérations consommatrices sont bloquées."
|
||||
IsVisible="{Binding IsQuotaReached}" TextWrapping="Wrap"/>
|
||||
<TextBlock Text="{Binding EstimatedCompensation, StringFormat='Estimation : {0:F2}'}"/>
|
||||
<TextBlock Text="{Binding Currency}"/>
|
||||
</StackPanel>
|
||||
|
|
|
|||
|
|
@ -90,6 +90,12 @@
|
|||
<DataTemplate x:DataType="services:CaptureDevice"><TextBlock Text="{Binding Name}" /></DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<CheckBox Content="Flouter le decor de la camera (Android)"
|
||||
IsVisible="{Binding SupportsPodcastBackgroundBlur}"
|
||||
IsEnabled="{Binding CanChangePodcastBackgroundBlur}"
|
||||
IsChecked="{Binding BlurPodcastBackground, Mode=TwoWay}" />
|
||||
<TextBlock Text="Le masque automatique peut laisser apparaitre des details du decor. Verifiez l'apercu avant de diffuser."
|
||||
IsVisible="{Binding SupportsPodcastBackgroundBlur}" TextWrapping="Wrap" />
|
||||
<WrapPanel>
|
||||
<Button Content="Previsualiser la camera" Command="{Binding PreviewCommand}" Margin="0,0,8,8" />
|
||||
<Button Content="Arreter la previsualisation" Command="{Binding StopPreviewCommand}" Margin="0,0,8,8" />
|
||||
|
|
@ -97,6 +103,20 @@
|
|||
</WrapPanel>
|
||||
</StackPanel>
|
||||
<Button Content="Arreter et publier le replay" Command="{Binding StopCommand}" />
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Diffuser l'emission programmee avec OBS Studio" FontWeight="SemiBold" />
|
||||
<TextBlock Text="Selectionnez votre emission puis activez OBS. Dans OBS : service Personnalise, URL SRT ci-dessous, cle de stream vide, video H.264, audio AAC, images cles toutes les 2 secondes. Le direct commence a la reception des premiers medias, pas a l'heure prevue."
|
||||
TextWrapping="Wrap" />
|
||||
<WrapPanel>
|
||||
<Button Content="Activer OBS / renouveler la cle" Command="{Binding ActivateObsCommand}" Margin="0,0,8,8" />
|
||||
<Button Content="Revoquer OBS et arreter le diffuseur" Command="{Binding DeactivateObsCommand}" />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="URL SRT secrete (ne pas partager)" />
|
||||
<TextBox Text="{Binding ObsServerUrl, Mode=OneWay}" IsReadOnly="True" />
|
||||
<TextBlock Text="{Binding ObsStatus}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="Les identifiants ne sont pas sauvegardes dans PostIt. Quitter la page masque la cle, mais n'arrete pas OBS : utilisez la revocation ou arretez OBS."
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<CheckBox Content="Garder l'ecran allume pendant l'apercu camera et le direct"
|
||||
IsVisible="{Binding SupportsCaptureScreenAwake}"
|
||||
IsChecked="{Binding KeepScreenOnDuringCapture, Mode=TwoWay}" />
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
namespace Yavsc.Abstract.Administration;
|
||||
|
||||
/// <summary>Reports technical subscription records purged for withdrawn accounts.</summary>
|
||||
/// <summary>Counts accounts and technical payment records erased by the retention purge, excluding accounting documents.</summary>
|
||||
public sealed record PaymentResiduePurgeResult(int Users, int Subscriptions, int Payments, int Donations = 0, int LegacyPayments = 0);
|
||||
|
|
@ -2,9 +2,7 @@ namespace Yavsc.Abstract.Resources;
|
|||
|
||||
/// <summary>
|
||||
/// Lightweight usage snapshot for PostIt / Yavsc resource accounting.
|
||||
/// The initial implementation is intentionally intentionally small and
|
||||
/// serialisable so it can be exposed through the API and consumed by the
|
||||
/// PostIt client without requiring a full database model yet.
|
||||
/// Counters are cumulative; consumption is expressed in points, not currency.
|
||||
/// </summary>
|
||||
public sealed class ResourceUsageSummary
|
||||
{
|
||||
|
|
@ -17,6 +15,17 @@ public sealed class ResourceUsageSummary
|
|||
public decimal BandwidthMb { get; set; }
|
||||
public decimal StorageMb { get; set; }
|
||||
|
||||
public decimal Consumption { get; set; }
|
||||
public decimal GrossConsumption { get; set; }
|
||||
public decimal CreditBalance { get; set; }
|
||||
public decimal AppliedCredits { get; set; }
|
||||
public decimal ConsumptionLimit { get; set; }
|
||||
public decimal RemainingConsumption { get; set; }
|
||||
public bool IsQuotaReached { get; set; }
|
||||
public long? DiskQuota { get; set; }
|
||||
public DateTimeOffset? PremiumDiskQuotaUntil { get; set; }
|
||||
public DateTimeOffset? DiscoveryDiskQuotaUntil { get; set; }
|
||||
|
||||
public decimal EstimatedCompensation { get; set; }
|
||||
public string Currency { get; set; } = Constants.ResourceUsageDefaultCurrency;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,3 +57,9 @@ public sealed record PodcastSegmentResponse(int Sequence, double DurationSeconds
|
|||
/// <summary>The ordered, committed segments of a live broadcast or replay.</summary>
|
||||
public sealed record PodcastManifestResponse(
|
||||
PodcastResponse Podcast, IReadOnlyList<PodcastSegmentResponse> Segments);
|
||||
|
||||
/// <summary>One-time OBS connection credentials for an activated planned emission.</summary>
|
||||
public sealed record PodcastObsCredentials(string ServerUrl, string StreamKey, DateTimeOffset ExpiresAt);
|
||||
|
||||
/// <summary>Owner-only state of the external broadcasting activation.</summary>
|
||||
public sealed record PodcastObsStatus(bool Enabled, DateTimeOffset? ExpiresAt, string? Error);
|
||||
|
|
|
|||
|
|
@ -1,15 +1,18 @@
|
|||
#nullable enable
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.RegularExpressions;
|
||||
using Yavsc.Models.Workflow;
|
||||
|
||||
namespace Yavsc.Abstract.Workflow;
|
||||
|
||||
public sealed class PerformerProfileSettings
|
||||
public sealed class PerformerProfileSettings : IValidatableObject
|
||||
{
|
||||
public string PerformerId { get; set; } = string.Empty;
|
||||
public string UserName { get; set; } = string.Empty;
|
||||
public string ExerciseCountryCode { get; set; } = "fr";
|
||||
public string SIREN { get; set; } = string.Empty;
|
||||
public bool CanIssueEstimates => !string.IsNullOrWhiteSpace(SIREN);
|
||||
public string WebSite { get; set; } = string.Empty;
|
||||
/// <summary>Owner-only PayPal recipient. Null preserves the existing setting; empty disables donations.</summary>
|
||||
[MaxLength(127)]
|
||||
|
|
@ -19,4 +22,24 @@ public sealed class PerformerProfileSettings
|
|||
public bool AcceptPublicContact { get; set; }
|
||||
public bool UseGeoLocalizationToReduceDistanceWithClients { get; set; }
|
||||
public List<string> SelectedActivityCodes { get; set; } = new();
|
||||
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
{
|
||||
var countryCode = PerformerCodeInputValidationCatalog.NormalizeCountryCode(
|
||||
string.IsNullOrWhiteSpace(ExerciseCountryCode) ? "fr" : ExerciseCountryCode);
|
||||
var rule = PerformerCodeInputValidationCatalog.GetRule(countryCode);
|
||||
if (rule is null)
|
||||
{
|
||||
yield return new ValidationResult(
|
||||
"Le pays d'exercice doit etre l'un des suivants: fr, en, pt.",
|
||||
new[] { nameof(ExerciseCountryCode) });
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(SIREN)
|
||||
&& !Regex.IsMatch(SIREN.Trim(), rule.RegularExpression, RegexOptions.CultureInvariant))
|
||||
{
|
||||
yield return new ValidationResult(rule.ErrorMessage, new[] { nameof(SIREN) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ public sealed class AdministrationApiClient(IYavscApiClient api, Func<string> ba
|
|||
=> api.CallAsync<List<AdministrationRole>>(HttpMethod.Get, Path("roles"), ct: ct);
|
||||
public Task EnsureRolesAsync(CancellationToken ct = default)
|
||||
=> api.CallAsync(HttpMethod.Post, Path("roles/ensure"), ct: ct);
|
||||
public Task<PaymentResiduePurgeResult> PurgePaymentResiduesAsync(CancellationToken ct = default)
|
||||
=> api.CallAsync<PaymentResiduePurgeResult>(HttpMethod.Post, Path("payment-residues/purge"), ct: ct);
|
||||
public Task<List<RoleMember>> GetRoleMembersAsync(string roleId, CancellationToken ct = default)
|
||||
=> api.CallAsync<List<RoleMember>>(HttpMethod.Get, Path($"roles/{Escape(roleId)}/members"), ct: ct);
|
||||
public Task SetRoleMembershipAsync(string roleId, string userId, bool member, CancellationToken ct = default)
|
||||
|
|
|
|||
|
|
@ -28,6 +28,15 @@ public sealed class PodcastApiClient(IYavscApiClient api, Func<string> baseAddre
|
|||
public Task<PodcastResponse> StartAsync(Guid id, CancellationToken ct = default)
|
||||
=> api.CallAsync<PodcastResponse>(HttpMethod.Post, Absolute($"{Prefix}/{id}/start"), ct: ct);
|
||||
|
||||
public Task<PodcastObsCredentials> ActivateObsAsync(Guid id, CancellationToken ct = default)
|
||||
=> api.CallAsync<PodcastObsCredentials>(HttpMethod.Post, Absolute($"{Prefix}/{id}/obs"), ct: ct);
|
||||
|
||||
public Task<PodcastObsStatus> ObsStatusAsync(Guid id, CancellationToken ct = default)
|
||||
=> api.CallAsync<PodcastObsStatus>(HttpMethod.Get, Absolute($"{Prefix}/{id}/obs"), ct: ct);
|
||||
|
||||
public Task DeactivateObsAsync(Guid id, CancellationToken ct = default)
|
||||
=> api.CallAsync(HttpMethod.Delete, Absolute($"{Prefix}/{id}/obs"), ct: ct);
|
||||
|
||||
public Task<PodcastManifestResponse> GetAsync(Guid id, CancellationToken ct = default)
|
||||
=> api.CallAsync<PodcastManifestResponse>(HttpMethod.Get, Absolute($"{Prefix}/{id}"), ct: ct);
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,12 @@
|
|||
@scopeId = 1
|
||||
@templateId = REPLACE_WITH_MAILING_CRITERION
|
||||
|
||||
### Purge payment residues after the effective withdrawal's one-year anniversary
|
||||
# 200: { users, subscriptions, payments, donations, legacyPayments }
|
||||
# 401: no token; 403: token without Administrator role.
|
||||
POST {{root}}/payment-residues/purge
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Protected OpenAPI document (development only)
|
||||
GET {{baseUrl}}/openapi/administration.json
|
||||
Authorization: Bearer {{token}}
|
||||
|
|
|
|||
|
|
@ -1,96 +1,29 @@
|
|||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Abstract.Resources;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Server.Helpers;
|
||||
|
||||
namespace Yavsc.ApiControllers.Administration;
|
||||
|
||||
[Produces("application/json")]
|
||||
[Authorize]
|
||||
[ResourceUsageExempt]
|
||||
[Route(Constants.APIPrefix + "/" + Constants.ResourceUsagePath)]
|
||||
public sealed class ResourceUsageApiController : Controller
|
||||
public sealed class ResourceUsageApiController(IResourceUsageService usage) : Controller
|
||||
{
|
||||
private readonly ApplicationDbContext _dbContext;
|
||||
|
||||
public ResourceUsageApiController(ApplicationDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
}
|
||||
|
||||
private static ResourceUsageSummary ToSummary(ResourceUsageRecord record)
|
||||
=> new()
|
||||
{
|
||||
UserId = record.UserId,
|
||||
UserName = record.UserName,
|
||||
RecordedAtUtc = new DateTimeOffset(record.RecordedAtUtc, TimeSpan.Zero),
|
||||
ApiCalls = record.ApiCalls,
|
||||
CpuSeconds = record.CpuSeconds,
|
||||
BandwidthMb = record.BandwidthMb,
|
||||
StorageMb = record.StorageMb,
|
||||
EstimatedCompensation = record.EstimatedCompensation,
|
||||
Currency = record.Currency
|
||||
};
|
||||
|
||||
[HttpGet(Constants.ResourceUsageCurrentUserRoute)]
|
||||
public async Task<ActionResult<ResourceUsageSummary>> GetCurrentUserUsage()
|
||||
public async Task<ActionResult<ResourceUsageSummary>> GetCurrentUserUsage(CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = User.GetUserId();
|
||||
if (string.IsNullOrWhiteSpace(userId))
|
||||
{
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
var userName = User.Identity?.Name ?? Constants.ResourceUsageCurrentUserDisplayName;
|
||||
var record = await _dbContext.ResourceUsageRecords
|
||||
.Where(r => r.UserId == userId)
|
||||
.OrderByDescending(r => r.RecordedAtUtc)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (record is null)
|
||||
{
|
||||
var zeroUsage = new ResourceUsageRecord
|
||||
{
|
||||
UserId = userId,
|
||||
UserName = userName,
|
||||
RecordedAtUtc = DateTime.UtcNow,
|
||||
ApiCalls = 0m,
|
||||
CpuSeconds = 0m,
|
||||
BandwidthMb = 0m,
|
||||
StorageMb = 0m,
|
||||
EstimatedCompensation = 0m,
|
||||
Currency = Constants.ResourceUsageDefaultCurrency,
|
||||
UserCreated = userId,
|
||||
UserModified = userId,
|
||||
DateCreated = DateTime.UtcNow,
|
||||
DateModified = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
_dbContext.ResourceUsageRecords.Add(zeroUsage);
|
||||
await _dbContext.SaveChangesAsync(userId);
|
||||
return Ok(ToSummary(zeroUsage));
|
||||
}
|
||||
|
||||
return Ok(ToSummary(record));
|
||||
if (string.IsNullOrWhiteSpace(userId)) return Unauthorized();
|
||||
return Ok(await usage.GetCurrentAsync(userId,
|
||||
User.Identity?.Name ?? Constants.ResourceUsageCurrentUserDisplayName, cancellationToken));
|
||||
}
|
||||
|
||||
[HttpGet(Constants.ResourceUsageAdminRoute)]
|
||||
public async Task<ActionResult<List<ResourceUsageSummary>>> GetAdminOverview()
|
||||
public async Task<ActionResult<List<ResourceUsageSummary>>> GetAdminOverview(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!User.IsInRole(Constants.AdminName))
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var latestByUser = (await _dbContext.ResourceUsageRecords
|
||||
.OrderByDescending(r => r.RecordedAtUtc)
|
||||
.ToListAsync())
|
||||
.GroupBy(r => r.UserId)
|
||||
.Select(g => g.First())
|
||||
.OrderByDescending(r => r.RecordedAtUtc)
|
||||
.ToList();
|
||||
|
||||
return Ok(latestByUser.Select(ToSummary).ToList());
|
||||
if (!User.IsInRole(Constants.AdminName)) return Forbid();
|
||||
return Ok(await usage.GetOverviewAsync(cancellationToken));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,13 @@ namespace Yavsc.ApiControllers.Administration;
|
|||
[ServiceFilter(typeof(AdministrationExceptionFilter))]
|
||||
public sealed class SiteAdministrationApiController(IAdministrationService service) : ControllerBase
|
||||
{
|
||||
[HttpPost("payment-residues/purge"), EndpointSummary("Purger les paiements techniques des comptes retires depuis au moins un an")]
|
||||
[ProducesResponseType<PaymentResiduePurgeResult>(200)]
|
||||
[Yavsc.Server.Helpers.ResourceUsageExempt]
|
||||
public async Task<ActionResult<PaymentResiduePurgeResult>> PurgePaymentResidues(
|
||||
[FromServices] Yavsc.Server.Helpers.IPaymentResidueService residues, CancellationToken ct)
|
||||
=> Ok(await residues.PurgeAsync(ct));
|
||||
|
||||
[HttpGet("summary"), EndpointSummary("Statistiques du site et informations du logiciel")]
|
||||
[ProducesResponseType<AdministrationSummary>(200)]
|
||||
public async Task<ActionResult<AdministrationSummary>> Summary(CancellationToken ct)
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ namespace Yavsc.Controllers
|
|||
|
||||
// PUT: api/Estimate/5
|
||||
[HttpPut("{id}"), Produces("application/json")]
|
||||
public IActionResult PutEstimate(long id, [FromBody] Estimate estimate)
|
||||
public async Task<IActionResult> PutEstimate(long id, [FromBody] Estimate estimate)
|
||||
{
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
|
|
@ -88,6 +88,11 @@ namespace Yavsc.Controllers
|
|||
}
|
||||
}
|
||||
|
||||
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
|
||||
{
|
||||
return Conflict(new { Error = "A business registration is required to issue or edit estimates." });
|
||||
}
|
||||
|
||||
var entry = _context.Attach(estimate);
|
||||
try
|
||||
{
|
||||
|
|
@ -110,7 +115,7 @@ namespace Yavsc.Controllers
|
|||
|
||||
// POST: api/Estimate
|
||||
[HttpPost, Produces("application/json")]
|
||||
public IActionResult PostEstimate([FromBody] Estimate estimate)
|
||||
public async Task<IActionResult> PostEstimate([FromBody] Estimate estimate)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
if (estimate.OwnerId == null) estimate.OwnerId = uid;
|
||||
|
|
@ -124,6 +129,11 @@ namespace Yavsc.Controllers
|
|||
}
|
||||
}
|
||||
|
||||
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
|
||||
{
|
||||
return Conflict(new { Error = "A business registration is required to issue estimates." });
|
||||
}
|
||||
|
||||
if (estimate.CommandId != null)
|
||||
{
|
||||
var query = _context.NominativeServiceCommands
|
||||
|
|
@ -334,5 +344,19 @@ namespace Yavsc.Controllers
|
|||
{
|
||||
return _context.Estimates.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
|
||||
private Task<bool> CanIssueEstimatesAsync(string? performerId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(performerId))
|
||||
{
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
|
||||
return _context.Performers
|
||||
.AsNoTracking()
|
||||
.AnyAsync(profile => profile.PerformerId == performerId
|
||||
&& profile.SIREN != null
|
||||
&& profile.SIREN.Trim() != "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -159,7 +159,6 @@ namespace Yavsc.ApiControllers
|
|||
uid,
|
||||
User.Identity?.Name ?? uid,
|
||||
cpuSeconds: (decimal)stopwatch.Elapsed.TotalSeconds,
|
||||
storageBytes: fo.Length,
|
||||
actorUserId: uid);
|
||||
|
||||
return File(fo.OpenRead(), "application/pdf");
|
||||
|
|
@ -185,12 +184,21 @@ namespace Yavsc.ApiControllers
|
|||
uid,
|
||||
User.Identity?.Name ?? uid,
|
||||
cpuSeconds: (decimal)stopwatch.Elapsed.TotalSeconds,
|
||||
storageBytes: renderedPdf?.Length ?? 0,
|
||||
actorUserId: uid);
|
||||
|
||||
logger.LogError(ex, "estimate {QueryId}: TeX/PDF render failed", queryId);
|
||||
return Problem("TeX render failed: " + ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (renderedPdf is not null)
|
||||
{
|
||||
renderedPdf.Refresh();
|
||||
if (renderedPdf.Exists)
|
||||
await ResourceUsageTracker.RecordStorageAsync(dbContext, uid, User.Identity?.Name ?? uid,
|
||||
"pdf/" + renderedPdf.FullName, renderedPdf.Length, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Loads the estimate linked to a query with the navigation the
|
||||
|
|
|
|||
|
|
@ -90,10 +90,14 @@ public sealed class PodcastController(ILiveProcessor processor, IPodcastSchedule
|
|||
/// <summary>Ends the broadcast and schedules preparation of its MP4 replay.</summary>
|
||||
[HttpPost("{id:guid}/complete")]
|
||||
[ProducesResponseType<PodcastResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<ActionResult<PodcastResponse>> Complete(Guid id, CancellationToken ct)
|
||||
public async Task<ActionResult<PodcastResponse>> Complete(Guid id,
|
||||
[FromServices] IPodcastObsService obs, CancellationToken ct)
|
||||
{
|
||||
var ownerId = User.GetUserId();
|
||||
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
|
||||
if ((await schedule.GetAsync(id, ownerId, ct)).Podcast.FlowId is not null
|
||||
&& (await obs.StatusAsync(id, ownerId, ct)).Enabled)
|
||||
await obs.DeactivateAsync(id, ownerId, ct);
|
||||
await processor.CompleteAsync(id, ownerId, ct);
|
||||
return Ok((await schedule.GetAsync(id, ownerId, ct)).Podcast);
|
||||
}
|
||||
|
|
|
|||
47
src/Yavsc.Api/Controllers/Musical/PodcastObsController.cs
Normal file
47
src/Yavsc.Api/Controllers/Musical/PodcastObsController.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Yavsc.Abstract.Streaming;
|
||||
using Yavsc.Api.Middleware;
|
||||
using Yavsc.Api.Services;
|
||||
using Yavsc.Server.Helpers;
|
||||
|
||||
namespace Yavsc.ApiControllers;
|
||||
|
||||
[ApiController, ApiExplorerSettings(GroupName = "podcasts")]
|
||||
[Authorize(Policy = "ApiScope")]
|
||||
[Route(Constants.APIPrefix + "/podcasts")]
|
||||
[TypeFilter(typeof(PodcastExceptionFilter))]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class PodcastObsController(IPodcastObsService obs) : ControllerBase
|
||||
{
|
||||
[HttpPost("{id:guid}/obs"), EndpointSummary("Activer OBS pour une emission programmee et obtenir une cle a usage limite")]
|
||||
[ProducesResponseType<PodcastObsCredentials>(200)]
|
||||
[ProducesResponseType<ProblemDetails>(403)]
|
||||
[ProducesResponseType<ProblemDetails>(404)]
|
||||
[ProducesResponseType<ProblemDetails>(409)]
|
||||
[ProducesResponseType<ProblemDetails>(429)]
|
||||
[ProducesResponseType<ProblemDetails>(413)]
|
||||
[ProducesResponseType<ProblemDetails>(503)]
|
||||
public async Task<ActionResult<PodcastObsCredentials>> Activate(Guid id, CancellationToken ct)
|
||||
=> Ok(await obs.ActivateAsync(id, User.GetUserId(), ct));
|
||||
|
||||
[HttpGet("{id:guid}/obs"), EndpointSummary("Consulter l'activation OBS et les erreurs de reception, sans exposer la cle")]
|
||||
[ProducesResponseType<PodcastObsStatus>(200)]
|
||||
[ProducesResponseType<ProblemDetails>(403)]
|
||||
[ProducesResponseType<ProblemDetails>(404)]
|
||||
public async Task<ActionResult<PodcastObsStatus>> Status(Guid id, CancellationToken ct)
|
||||
=> Ok(await obs.StatusAsync(id, User.GetUserId(), ct));
|
||||
|
||||
[HttpDelete("{id:guid}/obs"), EndpointSummary("Revoquer la cle OBS et deconnecter le diffuseur")]
|
||||
[ProducesResponseType(204)]
|
||||
[ProducesResponseType<ProblemDetails>(403)]
|
||||
[ProducesResponseType<ProblemDetails>(404)]
|
||||
[ProducesResponseType<ProblemDetails>(503)]
|
||||
[ResourceUsageRelief]
|
||||
public async Task<IActionResult> Deactivate(Guid id, CancellationToken ct)
|
||||
{
|
||||
await obs.DeactivateAsync(id, User.GetUserId(), ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -119,7 +119,7 @@ namespace Yavsc.WebApi.Controllers
|
|||
}).ToArray();
|
||||
user.PostsCounter = await _dbContext.BlogSpot.LongCountAsync(x => x.AuthorId == uid);
|
||||
user.DiskUsage = userData.DiskUsage;
|
||||
user.DiskQuota = userData.DiskQuota;
|
||||
user.DiskQuota = userData.GetEffectiveDiskQuota(DateTimeOffset.UtcNow);
|
||||
user.Credits = userData.AccountBalance?.Credits ?? 0;
|
||||
user.BankAccounts = (userData.BankInfo ?? [])
|
||||
.Select(bank => new BankAccountInfo
|
||||
|
|
@ -616,6 +616,12 @@ namespace Yavsc.WebApi.Controllers
|
|||
return BadRequest(new { error = "Payload is required." });
|
||||
}
|
||||
|
||||
model.SIREN = model.SIREN?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(model.ExerciseCountryCode))
|
||||
{
|
||||
model.ExerciseCountryCode = "fr";
|
||||
}
|
||||
|
||||
var uid = User.GetUserId();
|
||||
if (string.IsNullOrWhiteSpace(uid))
|
||||
{
|
||||
|
|
@ -652,11 +658,6 @@ namespace Yavsc.WebApi.Controllers
|
|||
return NotFound();
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(model.ExerciseCountryCode))
|
||||
{
|
||||
model.ExerciseCountryCode = "fr";
|
||||
}
|
||||
|
||||
var profile = await _dbContext.Performers.FirstOrDefaultAsync(p => p.PerformerId == uid);
|
||||
if (profile is null)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -81,3 +81,18 @@ Authorization: Bearer {{token}}
|
|||
### OpenAPI in development (requires an Administrator token)
|
||||
GET {{baseUrl}}/openapi/podcasts.json
|
||||
Authorization: Bearer {{token}}
|
||||
### Activate OBS for an owned planned podcast (secret SRT ServerUrl; StreamKey is empty)
|
||||
POST {{baseUrl}}/api/v1/podcasts/{{id}}/obs
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### OBS activation status (never returns the stream key)
|
||||
GET {{baseUrl}}/api/v1/podcasts/{{id}}/obs
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Revoke OBS and disconnect its publisher (allowed at consumption limit)
|
||||
DELETE {{baseUrl}}/api/v1/podcasts/{{id}}/obs
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
# Activation: 403 other owner/closed account, 404 missing emission,
|
||||
# 409 already started, 413 disk full, 429 consumption limit,
|
||||
# 503 OBS disabled, FFmpeg unavailable or listener/UDP port capacity reached.
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ internal class Program
|
|||
|
||||
var services = builder.Services;
|
||||
services.AddSiteAdministration();
|
||||
services.AddResourceUsage(builder.Configuration);
|
||||
|
||||
// Anthropic client
|
||||
builder.Services.AddSingleton<AnthropicClient>(_ =>
|
||||
|
|
@ -151,9 +152,10 @@ internal class Program
|
|||
app
|
||||
.UseRouting()
|
||||
.UseAuthentication()
|
||||
.UseCors("default")
|
||||
.UseMiddleware<WithdrawnAccountMiddleware>()
|
||||
.UseAuthorization()
|
||||
.UseMiddleware<ResourceUsageTelemetryMiddleware>()
|
||||
.UseCors("default");
|
||||
.UseMiddleware<ResourceUsageTelemetryMiddleware>();
|
||||
app.MapIdentityApi<ApplicationUser>().RequireAuthorization("ApiScope");
|
||||
app.MapDefaultControllerRoute();
|
||||
app.UseSession();
|
||||
|
|
|
|||
14
src/Yavsc.Api/ResourceUsage.http
Normal file
14
src/Yavsc.Api/ResourceUsage.http
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
@baseUrl = https://localhost:5104
|
||||
@token = replace-with-access-token
|
||||
|
||||
### Current user's cumulative counters, indicator and effective quota (also accessible at the limit)
|
||||
GET {{baseUrl}}/api/v1/resource-usage/me
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Latest snapshot per user (administrator role required)
|
||||
GET {{baseUrl}}/api/v1/resource-usage/admin
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Consuming operation: returns 429 Problem Details when quota is exhausted
|
||||
GET {{baseUrl}}/api/v1/notifications/me
|
||||
Authorization: Bearer {{token}}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
using Yavsc.ApiControllers.Administration;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace Yavsc.Api.Services;
|
||||
|
||||
|
|
@ -9,6 +10,8 @@ public static class AdministrationServiceCollectionExtensions
|
|||
services.AddHttpContextAccessor();
|
||||
services.AddScoped<IAdministrationService, AdministrationService>();
|
||||
services.AddScoped<AdministrationExceptionFilter>();
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.AddScoped<Yavsc.Server.Helpers.IPaymentResidueService, Yavsc.Server.Helpers.PaymentResidueService>();
|
||||
services.AddOpenApi(Constants.Administration, options =>
|
||||
options.ShouldInclude = description => description.GroupName == Constants.Administration);
|
||||
return services;
|
||||
|
|
|
|||
28
src/Yavsc.Api/Services/PodcastObsOptions.cs
Normal file
28
src/Yavsc.Api/Services/PodcastObsOptions.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
namespace Yavsc.Api.Services;
|
||||
|
||||
public sealed class PodcastObsOptions
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
public string ServerUrl { get; set; } = "";
|
||||
public string ListenAddress { get; set; } = "0.0.0.0";
|
||||
public int FirstPort { get; set; } = 10000;
|
||||
public int PortCount { get; set; } = 16;
|
||||
public int ActivationMinutes { get; set; } = 30;
|
||||
public int MaxDurationMinutes { get; set; } = 120;
|
||||
public int MaxConcurrentBroadcasts { get; set; } = 2;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (!Enabled) return;
|
||||
if (!Uri.TryCreate(ServerUrl, UriKind.Absolute, out var server)
|
||||
|| server.Scheme != "srt" || !server.IsDefaultPort
|
||||
|| server.UserInfo.Length != 0 || server.Query.Length != 0 || server.Fragment.Length != 0
|
||||
|| server.AbsolutePath is not ("" or "/")
|
||||
|| !System.Net.IPAddress.TryParse(ListenAddress, out _)
|
||||
|| FirstPort is < 1024 or > 65535 || PortCount is < 1 or > 128
|
||||
|| (long)FirstPort + PortCount - 1 > 65535
|
||||
|| ActivationMinutes is < 1 or > 1440 || MaxDurationMinutes is < 1 or > 1440
|
||||
|| MaxConcurrentBroadcasts is < 1 or > 16 || MaxConcurrentBroadcasts > PortCount)
|
||||
throw new InvalidOperationException("Invalid Podcast:Obs configuration. Use an SRT host without a port or query, a literal listen address and a bounded UDP port range.");
|
||||
}
|
||||
}
|
||||
141
src/Yavsc.Api/Services/PodcastObsService.cs
Normal file
141
src/Yavsc.Api/Services/PodcastObsService.cs
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
#nullable enable
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Abstract.Streaming;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Streaming;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.Settings;
|
||||
|
||||
namespace Yavsc.Api.Services;
|
||||
|
||||
public interface IPodcastObsService
|
||||
{
|
||||
Task<PodcastObsCredentials> ActivateAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
Task<PodcastObsStatus> StatusAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
Task DeactivateAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class PodcastObsService(ApplicationDbContext db, IOptions<PodcastObsOptions> options,
|
||||
IOptions<ResourceUsageOptions> usageOptions, PodcastObsWorker worker, TimeProvider clock,
|
||||
ILogger<PodcastObsService> logger) : IPodcastObsService
|
||||
{
|
||||
public async Task<PodcastObsCredentials> ActivateAsync(Guid id, string ownerId, CancellationToken ct)
|
||||
{
|
||||
var settings = options.Value;
|
||||
if (!settings.Enabled) throw new PodcastException(503, "L'entree OBS n'est pas configuree sur cette instance.");
|
||||
settings.Validate();
|
||||
await worker.WaitUntilReadyAsync(ct);
|
||||
await worker.Lifecycle.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
|
||||
{
|
||||
var flow = await EligibleAsync(id, ownerId, ct);
|
||||
flow.ObsKeyHash = null;
|
||||
flow.ObsEnabledUntil = null;
|
||||
flow.ObsConnectionId = null;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return true;
|
||||
}, ct);
|
||||
await worker.StopCaptureAsync(id, ct);
|
||||
return await ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
|
||||
{
|
||||
var flow = await EligibleAsync(id, ownerId, ct);
|
||||
var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
|
||||
var connectionId = Guid.NewGuid();
|
||||
var expires = clock.GetUtcNow().AddMinutes(settings.ActivationMinutes);
|
||||
flow.ObsKeyHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key)));
|
||||
flow.ObsEnabledUntil = expires;
|
||||
flow.ObsConnectionId = connectionId;
|
||||
flow.ObsLastError = null;
|
||||
await db.SaveChangesAsync(ct);
|
||||
try
|
||||
{
|
||||
var port = await worker.ArmAsync(id, ownerId, connectionId, key, expires, ct);
|
||||
var url = new UriBuilder(settings.ServerUrl)
|
||||
{
|
||||
Port = port,
|
||||
Query = $"mode=caller&passphrase={key}&pbkeylen=32&enforced_encryption=1&latency=200000"
|
||||
};
|
||||
return new PodcastObsCredentials(url.Uri.AbsoluteUri, "", expires);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
flow.ObsKeyHash = null;
|
||||
flow.ObsEnabledUntil = null;
|
||||
flow.ObsConnectionId = null;
|
||||
flow.ObsLastError = "Activation SRT impossible. Verifiez FFmpeg, les ports UDP et la capacite disponible.";
|
||||
await db.SaveChangesAsync(CancellationToken.None);
|
||||
logger.LogError("OBS listener activation failed ({ErrorType})", ex.GetType().Name);
|
||||
if (ex is OperationCanceledException or PodcastException) throw;
|
||||
throw new PodcastException(503, flow.ObsLastError);
|
||||
}
|
||||
}, ct);
|
||||
}
|
||||
finally { worker.Lifecycle.Release(); }
|
||||
}
|
||||
|
||||
public async Task<PodcastObsStatus> StatusAsync(Guid id, string ownerId, CancellationToken ct)
|
||||
{
|
||||
var flow = await OwnedAsync(id, ownerId, ct, tracking: false);
|
||||
return new(flow.ObsKeyHash is not null &&
|
||||
(flow.StartedAt is not null || flow.ObsEnabledUntil > clock.GetUtcNow()),
|
||||
flow.ObsEnabledUntil, flow.ObsLastError);
|
||||
}
|
||||
|
||||
public async Task DeactivateAsync(Guid id, string ownerId, CancellationToken ct)
|
||||
{
|
||||
await worker.Lifecycle.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
|
||||
{
|
||||
var flow = await OwnedAsync(id, ownerId, ct);
|
||||
flow.ObsKeyHash = null;
|
||||
flow.ObsEnabledUntil = null;
|
||||
flow.ObsConnectionId = null;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return true;
|
||||
}, ct);
|
||||
await worker.StopCaptureAsync(id, ct);
|
||||
}
|
||||
finally { worker.Lifecycle.Release(); }
|
||||
}
|
||||
|
||||
private async Task<LiveFlow> EligibleAsync(Guid id, string ownerId, CancellationToken ct)
|
||||
{
|
||||
var flow = await OwnedAsync(id, ownerId, ct);
|
||||
if (flow.StartedAt is not null)
|
||||
throw new PodcastException(409, "Cette emission a deja demarre. Preparez une nouvelle emission.");
|
||||
if (flow.Owner.WithdrawalRequestedAt is not null)
|
||||
throw new PodcastException(403, "Le compte est ferme.");
|
||||
var record = await db.ResourceUsageRecords.AsNoTracking().Where(r => r.UserId == ownerId)
|
||||
.OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id).FirstOrDefaultAsync(ct);
|
||||
var policy = usageOptions.Value;
|
||||
var gross = record is null ? 0m : policy.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb);
|
||||
if (ResourceUsageCredit.NetConsumption(gross, record?.CreditPoints ?? 0m) >= policy.GetLimit(ownerId))
|
||||
throw new PodcastException(429, "Le seuil de consommation est atteint.");
|
||||
if (flow.Owner.DiskUsage >= flow.Owner.GetEffectiveDiskQuota(clock.GetUtcNow()))
|
||||
throw new PodcastException(413, "Le quota disque est atteint.");
|
||||
return flow;
|
||||
}
|
||||
|
||||
private async Task<LiveFlow> OwnedAsync(Guid id, string ownerId, CancellationToken ct, bool tracking = true)
|
||||
{
|
||||
var query = db.LiveFlow.Include(f => f.Owner).AsQueryable();
|
||||
if (!tracking) query = query.AsNoTracking();
|
||||
var flow = await query.SingleOrDefaultAsync(f => f.PodcastId == id && !f.PodcastDeleted, ct)
|
||||
?? throw new PodcastException(404, "Emission introuvable.");
|
||||
if (tracking)
|
||||
{
|
||||
await db.Entry(flow).ReloadAsync(ct);
|
||||
await db.Entry(flow.Owner).ReloadAsync(ct);
|
||||
}
|
||||
if (flow.OwnerId != ownerId) throw new PodcastException(403, "Seul l'auteur peut activer OBS.");
|
||||
return flow;
|
||||
}
|
||||
}
|
||||
396
src/Yavsc.Api/Services/PodcastObsWorker.cs
Normal file
396
src/Yavsc.Api/Services/PodcastObsWorker.cs
Normal file
|
|
@ -0,0 +1,396 @@
|
|||
#nullable enable
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using FFmpeg.NET;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.Settings;
|
||||
|
||||
namespace Yavsc.Api.Services;
|
||||
|
||||
public sealed class PodcastObsWorker(IServiceScopeFactory scopes, IOptions<PodcastObsOptions> options,
|
||||
IOptions<PodcastOptions> mediaOptions, TimeProvider clock, ILogger<PodcastObsWorker> logger) : BackgroundService
|
||||
{
|
||||
private sealed class Capture(Guid id, string ownerId, Guid connectionId, int port,
|
||||
DateTimeOffset expires, CancellationTokenSource cancellation)
|
||||
{
|
||||
public Guid Id { get; } = id;
|
||||
public string OwnerId { get; } = ownerId;
|
||||
public Guid ConnectionId { get; } = connectionId;
|
||||
public int Port { get; } = port;
|
||||
public DateTimeOffset Expires { get; } = expires;
|
||||
public CancellationTokenSource Cancellation { get; } = cancellation;
|
||||
public TaskCompletionSource Completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public DateTimeOffset? Started { get; set; }
|
||||
public string? Error { get; set; }
|
||||
}
|
||||
|
||||
internal SemaphoreSlim Lifecycle { get; } = new(1, 1);
|
||||
private readonly object gate = new();
|
||||
private readonly Dictionary<Guid, Capture> captures = new();
|
||||
private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private CancellationToken stopping;
|
||||
|
||||
internal Task WaitUntilReadyAsync(CancellationToken ct) => ready.Task.WaitAsync(ct);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
stopping = stoppingToken;
|
||||
try
|
||||
{
|
||||
options.Value.Validate();
|
||||
using (var scope = scopes.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var stale = await db.LiveFlow.Where(f => f.ObsKeyHash != null).ToListAsync(stoppingToken);
|
||||
foreach (var flow in stale)
|
||||
await ResourceUsageTracker.WithUserLockAsync(db, flow.OwnerId, async () =>
|
||||
{
|
||||
flow.ObsKeyHash = null;
|
||||
flow.ObsConnectionId = null;
|
||||
flow.ObsEnabledUntil = null;
|
||||
flow.ObsLastError = "L'API a redemarre ; reactivez OBS pour obtenir une nouvelle URL SRT.";
|
||||
await db.SaveChangesAsync(stoppingToken);
|
||||
return true;
|
||||
}, stoppingToken);
|
||||
}
|
||||
ready.TrySetResult();
|
||||
if (!options.Value.Enabled) return;
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
Capture[] active;
|
||||
lock (gate) active = captures.Values.ToArray();
|
||||
foreach (var capture in active)
|
||||
{
|
||||
var flow = await db.LiveFlow.AsNoTracking().Include(f => f.Owner)
|
||||
.SingleOrDefaultAsync(f => f.PodcastId == capture.Id, stoppingToken);
|
||||
lock (gate)
|
||||
{
|
||||
if (!captures.ContainsKey(capture.Id)) continue;
|
||||
if (capture.Completion.Task.IsCompleted)
|
||||
{
|
||||
captures.Remove(capture.Id);
|
||||
capture.Cancellation.Dispose();
|
||||
}
|
||||
else if (flow is null || flow.PodcastDeleted || flow.ObsConnectionId != capture.ConnectionId
|
||||
|| flow.ObsKeyHash is null || flow.Owner.WithdrawalRequestedAt is not null)
|
||||
capture.Cancellation.Cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
catch (Exception ex) { logger.LogError(ex, "OBS listener state check failed; retrying"); }
|
||||
await Task.Delay(250, stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
|
||||
catch (Exception ex) { ready.TrySetException(ex); throw; }
|
||||
finally
|
||||
{
|
||||
Capture[] active;
|
||||
lock (gate)
|
||||
{
|
||||
active = captures.Values.ToArray();
|
||||
foreach (var capture in active) capture.Cancellation.Cancel();
|
||||
}
|
||||
await Task.WhenAll(active.Select(c => c.Completion.Task));
|
||||
lock (gate)
|
||||
{
|
||||
foreach (var capture in captures.Values) capture.Cancellation.Dispose();
|
||||
captures.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task<int> ArmAsync(Guid id, string ownerId, Guid connectionId, string key,
|
||||
DateTimeOffset expires, CancellationToken ct)
|
||||
{
|
||||
stopping.ThrowIfCancellationRequested();
|
||||
Capture capture;
|
||||
lock (gate)
|
||||
{
|
||||
foreach (var ended in captures.Values.Where(c => c.Completion.Task.IsCompleted).ToArray())
|
||||
{
|
||||
captures.Remove(ended.Id);
|
||||
ended.Cancellation.Dispose();
|
||||
}
|
||||
if (captures.Count >= options.Value.MaxConcurrentBroadcasts)
|
||||
throw new PodcastException(503, "Capacite OBS atteinte ; revoquez une activation inutilisee ou reessayez plus tard.");
|
||||
var port = Enumerable.Range(options.Value.FirstPort, options.Value.PortCount)
|
||||
.FirstOrDefault(p => captures.Values.All(c => c.Port != p) && !PortBound(p));
|
||||
if (port == 0) throw new PodcastException(503, "Aucun port UDP OBS disponible.");
|
||||
capture = new(id, ownerId, connectionId, port, expires,
|
||||
CancellationTokenSource.CreateLinkedTokenSource(stopping));
|
||||
captures.Add(id, capture);
|
||||
}
|
||||
_ = CaptureAsync(capture, key);
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct, stopping);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
while (!PortBound(capture.Port))
|
||||
{
|
||||
if (capture.Error is not null || capture.Completion.Task.IsCompleted)
|
||||
throw new PodcastException(503, capture.Error ?? "L'ecoute SRT n'a pas demarre.");
|
||||
await Task.Delay(50, timeout.Token);
|
||||
}
|
||||
return capture.Port;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Do not wait here: activation owns the accounting lock needed by capture cleanup.
|
||||
lock (gate) capture.Cancellation.Cancel();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task StopCaptureAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
Capture? capture;
|
||||
lock (gate)
|
||||
{
|
||||
if (!captures.TryGetValue(id, out capture)) return;
|
||||
capture.Cancellation.Cancel();
|
||||
}
|
||||
await capture.Completion.Task.WaitAsync(ct);
|
||||
if (PortBound(capture.Port))
|
||||
throw new PodcastException(503, "L'ecoute SRT ne s'est pas arretee ; intervention de l'administration requise.");
|
||||
lock (gate)
|
||||
if (captures.Remove(id)) capture.Cancellation.Dispose();
|
||||
}
|
||||
|
||||
private bool PortBound(int port)
|
||||
{
|
||||
var address = IPAddress.Parse(options.Value.ListenAddress);
|
||||
using var socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
|
||||
try { socket.Bind(new IPEndPoint(address, port)); return false; }
|
||||
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.AddressAlreadyInUse) { return true; }
|
||||
}
|
||||
|
||||
private async Task CaptureAsync(Capture capture, string key)
|
||||
{
|
||||
var media = mediaOptions.Value;
|
||||
var directory = Path.Combine(media.RootPath, $"obs-capture-{capture.Id:N}-{capture.ConnectionId:N}");
|
||||
string? error = null;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
using var scope = scopes.CreateScope();
|
||||
using var receive = CancellationTokenSource.CreateLinkedTokenSource(capture.Cancellation.Token);
|
||||
var guard = GuardBufferAsync(directory, media.MaxSegmentBytes, receive.Token);
|
||||
var ingest = ReceiveAsync(capture, key, directory, scope.ServiceProvider, receive.Token);
|
||||
try
|
||||
{
|
||||
if (await Task.WhenAny(ingest, guard) == guard) await guard;
|
||||
await ingest;
|
||||
}
|
||||
finally
|
||||
{
|
||||
receive.Cancel();
|
||||
try { await ingest; }
|
||||
catch (OperationCanceledException) when (receive.IsCancellationRequested) { }
|
||||
try { await guard; }
|
||||
catch (OperationCanceledException) when (receive.IsCancellationRequested) { }
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
logger.LogInformation("OBS capture {PodcastId} stopped", capture.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex is PodcastException or ResourceUsageLimitException ? ex.Message
|
||||
: "Reception SRT impossible. Verifiez FFmpeg, la connexion et l'encodage H.264/AAC.";
|
||||
logger.LogError("OBS capture {PodcastId} failed ({ErrorType})", capture.Id, ex.GetType().Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
capture.Error = error;
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
|
||||
await ResourceUsageTracker.WithUserLockAsync(db, capture.OwnerId, async () =>
|
||||
{
|
||||
var flow = await db.LiveFlow.Include(f => f.Owner)
|
||||
.SingleOrDefaultAsync(f => f.PodcastId == capture.Id, timeout.Token);
|
||||
if (flow is not null)
|
||||
{
|
||||
if (capture.Started is not null && flow.Owner.WithdrawalRequestedAt is null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await scope.ServiceProvider.GetRequiredService<ILiveProcessor>()
|
||||
.CompleteAsync(capture.Id, capture.OwnerId, timeout.Token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = "Finalisation OBS impossible ; intervention de l'administration requise.";
|
||||
capture.Error = error;
|
||||
logger.LogError("OBS replay finalization failed for {PodcastId} ({ErrorType})",
|
||||
capture.Id, ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
if (flow.ObsConnectionId == capture.ConnectionId)
|
||||
{
|
||||
flow.ObsKeyHash = null;
|
||||
flow.ObsEnabledUntil = null;
|
||||
flow.ObsConnectionId = null;
|
||||
flow.ObsLastError = error;
|
||||
await db.SaveChangesAsync(timeout.Token);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}, timeout.Token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError("OBS capture {PodcastId} finalization failed ({ErrorType}); operator intervention required",
|
||||
capture.Id, ex.GetType().Name);
|
||||
capture.Error = "Finalisation OBS impossible ; intervention de l'administration requise.";
|
||||
}
|
||||
try { if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError("OBS temporary files cleanup failed for {PodcastId} ({ErrorType})",
|
||||
capture.Id, ex.GetType().Name);
|
||||
}
|
||||
capture.Completion.TrySetResult();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReceiveAsync(Capture capture, string key, string directory, IServiceProvider services, CancellationToken ct)
|
||||
{
|
||||
var input = new UriBuilder("srt", options.Value.ListenAddress, capture.Port)
|
||||
{
|
||||
Query = $"mode=listener&passphrase={key}&pbkeylen=32&enforced_encryption=1"
|
||||
+ $"&listen_timeout={options.Value.ActivationMinutes * 60000000L}&timeout=20000000&latency=200000"
|
||||
};
|
||||
var engine = new Engine(mediaOptions.Value.FfmpegPath);
|
||||
var failed = false;
|
||||
engine.Error += (_, _) => Volatile.Write(ref failed, true);
|
||||
using var processCancellation = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var process = engine.ExecuteAsync(
|
||||
$"-nostdin -hide_banner -loglevel error -i \"{input.Uri.AbsoluteUri}\" -map 0:v:0 -map 0:a:0? -c copy"
|
||||
+ " -f segment -segment_format mpegts -segment_time 2 -segment_list segments.csv"
|
||||
+ " -segment_list_type csv segment-%08d.ts", directory, processCancellation.Token);
|
||||
var db = services.GetRequiredService<ApplicationDbContext>();
|
||||
var processor = services.GetRequiredService<ILiveProcessor>();
|
||||
var next = 0;
|
||||
var total = 0L;
|
||||
var lastSegment = clock.GetUtcNow();
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var now = clock.GetUtcNow();
|
||||
if (capture.Started is null && now >= capture.Expires)
|
||||
throw new PodcastException(408, "Activation OBS expiree ; obtenez une nouvelle URL SRT.");
|
||||
if (capture.Started is not null)
|
||||
{
|
||||
if (now - capture.Started >= TimeSpan.FromMinutes(options.Value.MaxDurationMinutes))
|
||||
break;
|
||||
if (now - lastSegment > TimeSpan.FromSeconds(20))
|
||||
throw new PodcastException(408, "Aucun segment OBS recu depuis vingt secondes ; verifiez la connexion.");
|
||||
}
|
||||
var playlist = Path.Combine(directory, "segments.csv");
|
||||
var text = File.Exists(playlist) ? await File.ReadAllTextAsync(playlist, ct) : "";
|
||||
var lines = text.Split('\n');
|
||||
for (; next < lines.Length - 1; next++)
|
||||
{
|
||||
if (next >= mediaOptions.Value.MaxSegments) throw new PodcastException(413, "Nombre maximal de segments atteint.");
|
||||
var fields = lines[next].TrimEnd('\r').Split(',');
|
||||
if (fields.Length != 3 || fields[0] != $"segment-{next:D8}.ts"
|
||||
|| !double.TryParse(fields[1], CultureInfo.InvariantCulture, out var begin)
|
||||
|| !double.TryParse(fields[2], CultureInfo.InvariantCulture, out var end)
|
||||
|| !double.IsFinite(end - begin) || end - begin <= 0 || end - begin > 15)
|
||||
throw new PodcastException(400, "Segments OBS invalides ; configurez H.264/AAC et des images cles toutes les deux secondes.");
|
||||
if (capture.Started is null)
|
||||
{
|
||||
var podcast = await services.GetRequiredService<IPodcastScheduleService>()
|
||||
.StartAsync(capture.Id, capture.OwnerId, ct, capture.ConnectionId);
|
||||
capture.Started = now;
|
||||
processCancellation.CancelAfter(TimeSpan.FromMinutes(
|
||||
Math.Min(podcast.PlannedDurationMinutes ?? 1, options.Value.MaxDurationMinutes)));
|
||||
}
|
||||
var path = Path.Combine(directory, fields[0]);
|
||||
var bytes = new FileInfo(path).Length;
|
||||
if (bytes == 0 || bytes > mediaOptions.Value.MaxSegmentBytes)
|
||||
throw new PodcastException(413, "Segment OBS trop volumineux ; reduisez le debit.");
|
||||
total = checked(total + bytes);
|
||||
await ResourceUsageTracker.RecordStorageAsync(db, capture.OwnerId, capture.OwnerId,
|
||||
$"podcast/{capture.Id:N}", total, ct, write: async () =>
|
||||
{
|
||||
var user = await db.Users.SingleAsync(u => u.Id == capture.OwnerId, ct);
|
||||
await db.Entry(user).ReloadAsync(ct);
|
||||
var flow = await db.LiveFlow.SingleAsync(f => f.PodcastId == capture.Id, ct);
|
||||
await db.Entry(flow).ReloadAsync(ct);
|
||||
if (user.WithdrawalRequestedAt is not null || flow.ObsKeyHash is null
|
||||
|| flow.ObsConnectionId != capture.ConnectionId || flow.PodcastDeleted)
|
||||
throw new OperationCanceledException("OBS activation revoked or account closed.", ct);
|
||||
if (bytes > user.GetEffectiveDiskQuota(now) - user.DiskUsage)
|
||||
throw new PodcastException(413, "Quota disque atteint.");
|
||||
await using var stream = File.OpenRead(path);
|
||||
await processor.AppendAsync(capture.Id, capture.OwnerId, next, end - begin, stream, ct);
|
||||
user.DiskUsage = checked(user.DiskUsage + bytes);
|
||||
}, policy: services.GetRequiredService<IOptions<ResourceUsageOptions>>().Value,
|
||||
bandwidthMb: (decimal)bytes / (1024m * 1024m));
|
||||
File.Delete(path);
|
||||
lastSegment = now;
|
||||
}
|
||||
if (process.IsCompleted)
|
||||
{
|
||||
await process;
|
||||
if (Volatile.Read(ref failed) || next == 0)
|
||||
throw new IOException("FFmpeg SRT listener failed or produced no media.");
|
||||
break;
|
||||
}
|
||||
await Task.Delay(100, ct);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
processCancellation.Cancel();
|
||||
try { await process; }
|
||||
catch (OperationCanceledException) when (processCancellation.IsCancellationRequested) { }
|
||||
// FFmpeg.NET cancels/kills without waiting for OS socket teardown.
|
||||
using var released = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
try
|
||||
{
|
||||
while (PortBound(capture.Port))
|
||||
await Task.Delay(25, released.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (released.IsCancellationRequested)
|
||||
{
|
||||
throw new IOException("SRT listener did not release its UDP port after cancellation.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task GuardBufferAsync(string directory, int maxSegmentBytes, CancellationToken ct)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var pending = 0L;
|
||||
foreach (var path in Directory.EnumerateFiles(directory, "*.ts"))
|
||||
{
|
||||
var file = new FileInfo(path);
|
||||
if (!file.Exists) continue;
|
||||
var bytes = file.Length;
|
||||
if (bytes > maxSegmentBytes || (pending += bytes) > 64L * 1024 * 1024)
|
||||
throw new PodcastException(413, "Capture OBS trop volumineuse ou stockage trop lent ; reduisez le debit.");
|
||||
}
|
||||
await Task.Delay(100, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -12,7 +12,7 @@ namespace Yavsc.Api.Services;
|
|||
public interface IPodcastScheduleService
|
||||
{
|
||||
Task<PodcastResponse> PrepareAsync(string ownerId, PreparePodcastRequest request, Guid? id, CancellationToken ct);
|
||||
Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct, Guid? obsConnectionId = null);
|
||||
Task<IReadOnlyList<PodcastResponse>> ListAsync(string ownerId, CancellationToken ct);
|
||||
Task<PodcastManifestResponse> GetAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
Task<IReadOnlyList<PodcastAnnouncementResponse>> AnnouncementsAsync(CancellationToken ct);
|
||||
|
|
@ -35,6 +35,8 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
|
|||
try
|
||||
{
|
||||
var flow = id.HasValue ? await OwnedAsync(id.Value, ownerId, ct) : null;
|
||||
if (flow?.ObsKeyHash is not null)
|
||||
throw new PodcastException(409, "Desactivez l'entree OBS avant de modifier l'emission.");
|
||||
if (flow != null && (flow.StartedAt != null
|
||||
|| (await processor.ListAsync(ct)).Any(p => p.Id == id)))
|
||||
throw new PodcastException(409, "Une emission demarree ne peut plus etre reprogrammee.");
|
||||
|
|
@ -63,21 +65,33 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
|
|||
finally { Gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct)
|
||||
public async Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct, Guid? obsConnectionId = null)
|
||||
{
|
||||
await Gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
var flow = await OwnedAsync(id, ownerId, ct);
|
||||
var existing = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
|
||||
if (existing != null && existing.State != PodcastState.Live)
|
||||
throw new PodcastException(409, "Cette emission est terminee. Preparez une nouvelle emission.");
|
||||
if (flow.StartedAt != null && existing == null)
|
||||
throw new PodcastException(404, "Les medias de cette emission sont introuvables.");
|
||||
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id);
|
||||
flow.StartedAt ??= podcast.CreatedAt;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Enrich(podcast, flow);
|
||||
return await Yavsc.Server.Helpers.ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
|
||||
{
|
||||
var flow = await OwnedAsync(id, ownerId, ct);
|
||||
await db.Entry(flow).ReloadAsync(ct);
|
||||
await db.Entry(flow.Owner).ReloadAsync(ct);
|
||||
if (flow.Owner.WithdrawalRequestedAt is not null)
|
||||
throw new PodcastException(403, "Le compte est ferme.");
|
||||
if (obsConnectionId.HasValue && (flow.ObsConnectionId != obsConnectionId
|
||||
|| flow.ObsKeyHash is null || flow.ObsEnabledUntil <= DateTimeOffset.UtcNow))
|
||||
throw new OperationCanceledException("OBS connection revoked or activation expired.", ct);
|
||||
if (!obsConnectionId.HasValue && flow.ObsKeyHash is not null)
|
||||
throw new PodcastException(409, "Desactivez OBS avant de demarrer une capture PostIt.");
|
||||
var existing = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
|
||||
if (existing != null && existing.State != PodcastState.Live)
|
||||
throw new PodcastException(409, "Cette emission est terminee. Preparez une nouvelle emission.");
|
||||
if (flow.StartedAt != null && existing == null)
|
||||
throw new PodcastException(404, "Les medias de cette emission sont introuvables.");
|
||||
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id);
|
||||
flow.StartedAt ??= podcast.CreatedAt;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Enrich(podcast, flow);
|
||||
}, ct);
|
||||
}
|
||||
finally { Gate.Release(); }
|
||||
}
|
||||
|
|
@ -130,10 +144,24 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
|
|||
var flow = await db.LiveFlow.SingleOrDefaultAsync(f => f.PodcastId == id, ct);
|
||||
if (flow == null) { await processor.DeleteAsync(id, ownerId, ct); return; }
|
||||
if (flow.OwnerId != ownerId) throw new PodcastException(403, "Seul l'auteur peut supprimer ce podcast.");
|
||||
if (flow.ObsKeyHash is not null)
|
||||
throw new PodcastException(409, "Desactivez l'entree OBS avant de supprimer l'emission.");
|
||||
var podcast = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
|
||||
if (podcast?.State == PodcastState.Live)
|
||||
throw new PodcastException(409, "Terminez le direct avant de le supprimer.");
|
||||
if (podcast != null) await processor.DeleteAsync(id, ownerId, ct);
|
||||
var storage = await db.ResourceStorageRecords.AsNoTracking()
|
||||
.SingleOrDefaultAsync(r => r.UserId == ownerId && r.Path == $"podcast/{id:N}", ct);
|
||||
if (storage is not null)
|
||||
{
|
||||
await Yavsc.Server.Helpers.ResourceUsageTracker.RecordStorageAsync(db, ownerId,
|
||||
flow.OwnerId, storage.Path, 0, ct, write: async () =>
|
||||
{
|
||||
var owner = await db.Users.SingleAsync(u => u.Id == ownerId, ct);
|
||||
await db.Entry(owner).ReloadAsync(ct);
|
||||
owner.DiskUsage = Math.Max(0, owner.DiskUsage - storage.Bytes);
|
||||
});
|
||||
}
|
||||
flow.PodcastDeleted = true;
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,10 @@ public static class PodcastServiceCollectionExtensions
|
|||
public static IServiceCollection AddPodcasts(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.Configure<PodcastOptions>(configuration.GetSection("Podcast"));
|
||||
services.Configure<PodcastObsOptions>(configuration.GetSection("Podcast:Obs"));
|
||||
services.AddScoped<IPodcastObsService, PodcastObsService>();
|
||||
services.AddSingleton<PodcastObsWorker>();
|
||||
services.AddHostedService(provider => provider.GetRequiredService<PodcastObsWorker>());
|
||||
services.AddSingleton<ILiveProcessor, LiveProcessor>();
|
||||
services.AddScoped<IPodcastScheduleService, PodcastScheduleService>();
|
||||
services.AddSingleton<IPodcastReplayRemuxer, FfmpegPodcastReplayRemuxer>();
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
|
||||
<PackageReference Include="xFFmpeg.NET" />
|
||||
<ProjectReference Include="../Yavsc.Server/Yavsc.Server.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
@ -1,4 +1,7 @@
|
|||
{
|
||||
"ResourceUsage": {
|
||||
"UserLimits": {}
|
||||
},
|
||||
"Site": {
|
||||
"Authority": "https://yavsc.pschneider.fr",
|
||||
"Audience": ["api"],
|
||||
|
|
|
|||
|
|
@ -98,10 +98,36 @@ namespace Yavsc.Blogs.Controllers
|
|||
return $"{subdir.TrimStart('/')}/{fileName}";
|
||||
}
|
||||
|
||||
static string StoragePath(string relativePath)
|
||||
{
|
||||
var root = Path.GetPathRoot(Path.GetFullPath("."))!;
|
||||
return "personal/" + Path.GetRelativePath(root,
|
||||
Path.GetFullPath(Path.Combine(root, relativePath.TrimStart('/', '\\')))).Replace('\\', '/');
|
||||
}
|
||||
|
||||
[HttpPost("{*subdir}")]
|
||||
public async Task<IActionResult> Post([ValidRemoteUserFilePath] string subdir="")
|
||||
public async Task<IActionResult> Post([FromServices] IResourceUsageService usage,
|
||||
[ValidRemoteUserFilePath] string subdir="", CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
|
||||
var uid = User.GetUserId();
|
||||
var form = await Request.ReadFormAsync(cancellationToken);
|
||||
var anticipatedBytes = 0L;
|
||||
foreach (var file in form.Files)
|
||||
{
|
||||
var path = StoragePath(RelPath(subdir, AbstractFileSystemHelpers.FilterFileName(file.FileName)));
|
||||
var previous = await dbContext.ResourceStorageRecords.AsNoTracking()
|
||||
.Where(r => r.UserId == uid && r.Path == path)
|
||||
.Select(r => r.Bytes).SingleOrDefaultAsync(cancellationToken);
|
||||
anticipatedBytes = checked(anticipatedBytes + Math.Max(0L, file.Length - previous));
|
||||
}
|
||||
if (!await usage.TryAdmitAsync(uid, User.Identity?.Name ?? uid, 0m, 0m,
|
||||
anticipatedBytes, cancellationToken))
|
||||
{
|
||||
_logger.LogWarning("Resource quota refused file storage for user {UserId}", uid);
|
||||
await ResourceUsageTelemetryMiddleware.WriteQuotaProblemAsync(HttpContext);
|
||||
return new EmptyResult();
|
||||
}
|
||||
string destDir = null;
|
||||
List<FileReceivedInfo> received = new List<FileReceivedInfo>();
|
||||
InvalidPathException pathex = null;
|
||||
|
|
@ -117,15 +143,16 @@ namespace Yavsc.Blogs.Controllers
|
|||
}
|
||||
_logger.LogInformation($"Receiving files, saved in '{destDir}' (specified as '{subdir}').");
|
||||
|
||||
var uid = User.GetUserId();
|
||||
var user = dbContext.Users.Single(
|
||||
u => u.Id == uid
|
||||
);
|
||||
int i=0;
|
||||
_logger.LogInformation($"Receiving {Request.Form.Files.Count} files.");
|
||||
_logger.LogInformation($"Receiving {form.Files.Count} files.");
|
||||
|
||||
foreach (var f in Request.Form.Files)
|
||||
foreach (var f in form.Files)
|
||||
{
|
||||
var path = Path.Combine(destDir, AbstractFileSystemHelpers.FilterFileName(f.FileName));
|
||||
var oldLength = System.IO.File.Exists(path) ? new FileInfo(path).Length : 0L;
|
||||
var item = user.ReceiveUserFile(destDir, f);
|
||||
if (!item.QuotaOffense)
|
||||
{
|
||||
|
|
@ -160,12 +187,10 @@ namespace Yavsc.Blogs.Controllers
|
|||
item.ContentType = f.ContentType;
|
||||
}
|
||||
|
||||
await ResourceUsageTracker.RecordAsync(
|
||||
dbContext,
|
||||
uid,
|
||||
user.UserName,
|
||||
storageBytes: item.Length,
|
||||
actorUserId: uid);
|
||||
var newLength = System.IO.File.Exists(path) ? new FileInfo(path).Length : 0L;
|
||||
if (!item.QuotaOffense || newLength != oldLength)
|
||||
await ResourceUsageTracker.RecordStorageAsync(dbContext, uid, user.UserName,
|
||||
StoragePath(RelPath(subdir, item.FileName)), newLength, CancellationToken.None);
|
||||
|
||||
received.Add(item);
|
||||
_logger.LogInformation($"Received '{item.FileName}'.");
|
||||
|
|
@ -249,22 +274,24 @@ namespace Yavsc.Blogs.Controllers
|
|||
[HttpPost]
|
||||
[Route("/api/fsc/mvftd")]
|
||||
[Authorize()]
|
||||
public IActionResult MoveFile([FromBody] RenameFileQuery query)
|
||||
public async Task<IActionResult> MoveFile([FromBody] RenameFileQuery query)
|
||||
{
|
||||
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
|
||||
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
var uid = User.GetUserId();
|
||||
var user = dbContext.Users.Single(
|
||||
u => u.Id == uid
|
||||
);
|
||||
var info = user.MoveUserFileToDir(query.Id, query.To, siteSettings);
|
||||
if (!info.Done) return new BadRequestObjectResult(info);
|
||||
await ResourceUsageTracker.MoveStorageAsync(dbContext, uid, StoragePath(query.Id),
|
||||
StoragePath(Path.Combine(query.To ?? "", Path.GetFileName(query.Id))), CancellationToken.None);
|
||||
return Ok(new { moved = query.Id });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Route("/api/fsc/mvf")]
|
||||
[Authorize()]
|
||||
public IActionResult RenameFile([FromBody] RenameFileQuery query)
|
||||
public async Task<IActionResult> RenameFile([FromBody] RenameFileQuery query)
|
||||
{
|
||||
if (!ModelState.IsValid) {
|
||||
var idvr = new ValidRemoteUserFilePathAttribute();
|
||||
|
|
@ -272,23 +299,30 @@ namespace Yavsc.Blogs.Controllers
|
|||
return this.BadRequest(new { id = idvr.IsValid(query.Id), to = idvr.IsValid(query.To), errors = ModelState });
|
||||
}
|
||||
_logger.LogInformation($"Valid move query: {query.Id} => {query.To}");
|
||||
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
var uid = User.GetUserId();
|
||||
var user = dbContext.Users.Single(
|
||||
u => u.Id == uid
|
||||
);
|
||||
try {
|
||||
if (Config.UserFilesOptions.FileProvider.GetFileInfo(Path.Combine(user.UserName, query.Id)).Exists)
|
||||
var destination = query.To;
|
||||
var root = Path.Combine(siteSettings.UserFilesRoot, user.UserName);
|
||||
if (System.IO.File.Exists(Path.Combine(root, query.Id)))
|
||||
{
|
||||
var result = user.MoveUserFile(query.Id, query.To, siteSettings);
|
||||
if (!result.Done) return new BadRequestObjectResult(result);
|
||||
}
|
||||
else {
|
||||
var dir = new DirectoryInfo(Path.Combine(root, query.To));
|
||||
if (dir.Exists) destination = Path.Combine(query.To, dir.Name);
|
||||
var result = user.MoveUserDir(query.Id, query.To, siteSettings);
|
||||
if (!result.Done) return new BadRequestObjectResult(result);
|
||||
}
|
||||
await ResourceUsageTracker.MoveStorageAsync(dbContext, uid, StoragePath(query.Id),
|
||||
StoragePath(destination), CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to rename user file {Path} for {UserId}", query.Id, uid);
|
||||
return new BadRequestObjectResult(
|
||||
new FsOperationInfo {
|
||||
Done = false,
|
||||
|
|
@ -300,7 +334,8 @@ namespace Yavsc.Blogs.Controllers
|
|||
}
|
||||
|
||||
[HttpDelete("{*id}")]
|
||||
public IActionResult RemoveDirOrFile ([ValidRemoteUserFilePath] string id)
|
||||
[ResourceUsageRelief]
|
||||
public async Task<IActionResult> RemoveDirOrFile ([ValidRemoteUserFilePath] string id)
|
||||
{
|
||||
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
|
||||
|
||||
|
|
@ -312,10 +347,13 @@ namespace Yavsc.Blogs.Controllers
|
|||
var result = user.DeleteUserDirOrFile(id, siteSettings);
|
||||
if (!result.Done)
|
||||
return new BadRequestObjectResult(result);
|
||||
await ResourceUsageTracker.RecordStorageAsync(dbContext, user.Id, user.UserName,
|
||||
StoragePath(id), 0L, CancellationToken.None);
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to delete user file {Path} for {UserId}", id, user.Id);
|
||||
return new BadRequestObjectResult(
|
||||
new FsOperationInfo {
|
||||
Done = false,
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ internal class Program
|
|||
builder.AddConfiguration("blogs");
|
||||
|
||||
var services = builder.Services;
|
||||
services.AddResourceUsage(builder.Configuration);
|
||||
|
||||
var siteSection = builder.Configuration.GetSection("Site");
|
||||
services.Configure<SiteSettings>(siteSection);
|
||||
|
|
@ -100,9 +101,10 @@ internal class Program
|
|||
app
|
||||
.UseRouting()
|
||||
.UseAuthentication()
|
||||
.UseCors("default")
|
||||
.UseMiddleware<WithdrawnAccountMiddleware>()
|
||||
.UseAuthorization()
|
||||
.UseMiddleware<ResourceUsageTelemetryMiddleware>()
|
||||
.UseCors("default")
|
||||
;
|
||||
app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Program")
|
||||
.LogInformation($"Yavsc.Blogs started, Authority is '{authority}''");
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
{
|
||||
"ResourceUsage": {
|
||||
"UserLimits": {}
|
||||
},
|
||||
"Site": {
|
||||
"Title": "Yavsc Blogs",
|
||||
"Description": "A collection of blogs about software development, technology, and programming.",
|
||||
|
|
|
|||
|
|
@ -1049,10 +1049,12 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
|
|||
return View(new UnregisterViewModel { UserId = id, ReturnUrl = returnUrl });
|
||||
}
|
||||
|
||||
[HttpPost, Authorize("AdministratorOnly")]
|
||||
public async Task<IActionResult> AdminDelete(UnregisterViewModel model)
|
||||
[HttpPost, Authorize("AdministratorOnly"), ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> AdminDelete(UnregisterViewModel model,
|
||||
[FromServices] Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
|
||||
{
|
||||
var result = await DeleteUser(model.UserId);
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var result = await DeleteUser(model.UserId, withdrawal);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
|
|
@ -1062,14 +1064,16 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
|
|||
return View();
|
||||
}
|
||||
|
||||
[HttpPost, Authorize]
|
||||
public async Task<IActionResult> Delete(UnregisterViewModel model)
|
||||
[HttpPost, Authorize, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Delete(UnregisterViewModel model,
|
||||
[FromServices] Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
var result = await DeleteUser(model.UserId);
|
||||
if (model.UserId != User.GetUserId()) return Forbid();
|
||||
var result = await DeleteUser(User.GetUserId(), withdrawal);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
|
|
@ -1080,20 +1084,30 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
|
|||
|
||||
return RedirectToAction("Index", "Home");
|
||||
}
|
||||
async Task<IdentityResult> DeleteUser(string userId)
|
||||
async Task<IdentityResult> DeleteUser(string userId, Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
|
||||
{
|
||||
ApplicationUser user = await _userManager.FindByIdAsync(userId);
|
||||
|
||||
_dbContext.DeviceDeclaration.RemoveRange(_dbContext.DeviceDeclaration.Where(g => g.DeviceOwnerId == userId));
|
||||
|
||||
return await _userManager.DeleteAsync(user);
|
||||
try
|
||||
{
|
||||
await withdrawal.WithdrawAsync(userId, HttpContext.RequestAborted);
|
||||
return IdentityResult.Success;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or HttpRequestException
|
||||
or Yavsc.Web.Services.SubscriptionOperationException or DbUpdateException or InvalidOperationException)
|
||||
{
|
||||
_logger.LogError(ex, "Account withdrawal failed for {UserId}", userId);
|
||||
return IdentityResult.Failed(new IdentityError
|
||||
{
|
||||
Code = "WithdrawalFailed",
|
||||
Description = "Le retrait n'a pas pu etre termine. Contactez l'administration pour reprendre l'effacement."
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void AddErrors(IdentityResult result)
|
||||
{
|
||||
foreach (var error in result.Errors)
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, _localizer[error.Code]);
|
||||
ModelState.AddModelError(string.Empty, error.Code == "WithdrawalFailed" ? error.Description : _localizer[error.Code]);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ namespace Yavsc.Controllers
|
|||
Avatar = user.Avatar,
|
||||
BankInfo = user.BankInfo,
|
||||
DiskUsage = user.DiskUsage,
|
||||
DiskQuota = user.DiskQuota,
|
||||
DiskQuota = user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow),
|
||||
DedicatedCalendarId = user.DedicatedGoogleCalendar,
|
||||
EMail = user.Email,
|
||||
EmailConfirmed = await _userManager.IsEmailConfirmedAsync(user),
|
||||
|
|
@ -608,6 +608,7 @@ namespace Yavsc.Controllers
|
|||
var uid = user.Id;
|
||||
var postedCountryCode = model.ExerciseCountryCode;
|
||||
model.ExerciseCountryCode = NormalizeCountryCodeOrDefault(model.ExerciseCountryCode);
|
||||
model.SIREN = model.SIREN?.Trim() ?? string.Empty;
|
||||
|
||||
// Model binding validated the raw posted payload before entering
|
||||
// the action. If country was empty, we fallback to "fr" above,
|
||||
|
|
@ -622,7 +623,7 @@ namespace Yavsc.Controllers
|
|||
if (ModelState.IsValid)
|
||||
{
|
||||
var isFrenchPerformerCode = string.Equals(model.ExerciseCountryCode, "fr", StringComparison.Ordinal);
|
||||
if (isFrenchPerformerCode)
|
||||
if (isFrenchPerformerCode && !string.IsNullOrWhiteSpace(model.SIREN))
|
||||
{
|
||||
var exSiren = await _dbContext.ExceptionsSIREN.FirstOrDefaultAsync(
|
||||
ex => ex.SIREN == model.SIREN
|
||||
|
|
|
|||
|
|
@ -29,9 +29,10 @@ namespace Yavsc.Controllers
|
|||
|
||||
// GET: Estimate
|
||||
|
||||
public IActionResult Index()
|
||||
public async Task<IActionResult> Index()
|
||||
{
|
||||
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
ViewBag.CanIssueEstimates = await CanIssueEstimatesAsync(uid);
|
||||
return View(_context.Estimates.Include(e=>e.Query)
|
||||
.Include(e=>e.Query.PerformerProfile)
|
||||
.Include(e=>e.Query.PerformerProfile.Performer)
|
||||
|
|
@ -73,9 +74,14 @@ namespace Yavsc.Controllers
|
|||
|
||||
// GET: Estimate/Create
|
||||
[Authorize]
|
||||
public IActionResult Create()
|
||||
public async Task<IActionResult> Create()
|
||||
{
|
||||
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (!await CanIssueEstimatesAsync(uid))
|
||||
{
|
||||
return RedirectToAction("SetActivity", "Manage");
|
||||
}
|
||||
|
||||
IQueryable<RdvQuery> queries = _context.RdvQueries.Include(q=>q.Location).Where(bq=>bq.PerformerId == uid);
|
||||
//.Select(bq=>new SelectListItem{ Text = bq.Client.UserName, Value = bq.Client.Id });
|
||||
ViewBag.Clients = queries.Select(q=>q.Client).Distinct();
|
||||
|
|
@ -93,6 +99,11 @@ namespace Yavsc.Controllers
|
|||
)
|
||||
{
|
||||
estimate.OwnerId = User.GetUserId();
|
||||
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
|
||||
{
|
||||
return RedirectToAction("SetActivity", "Manage");
|
||||
}
|
||||
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Estimates
|
||||
|
|
@ -138,7 +149,7 @@ namespace Yavsc.Controllers
|
|||
|
||||
|
||||
// GET: Estimate/Edit/5
|
||||
public IActionResult Edit(long? id)
|
||||
public async Task<IActionResult> Edit(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
|
|
@ -152,6 +163,10 @@ namespace Yavsc.Controllers
|
|||
{
|
||||
return NotFound();
|
||||
}
|
||||
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
|
||||
{
|
||||
return RedirectToAction("SetActivity", "Manage");
|
||||
}
|
||||
|
||||
return View(estimate);
|
||||
}
|
||||
|
|
@ -159,11 +174,15 @@ namespace Yavsc.Controllers
|
|||
// POST: Estimate/Edit/5
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Edit(Estimate estimate)
|
||||
public async Task<IActionResult> Edit(Estimate estimate)
|
||||
{
|
||||
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (estimate.OwnerId!=uid&&estimate.ClientId!=uid
|
||||
) return NotFound();
|
||||
if (!await CanIssueEstimatesAsync(estimate.OwnerId))
|
||||
{
|
||||
return RedirectToAction("SetActivity", "Manage");
|
||||
}
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Update(estimate);
|
||||
|
|
@ -203,5 +222,19 @@ namespace Yavsc.Controllers
|
|||
_context.SaveChanges(User.GetUserId());
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
|
||||
private Task<bool> CanIssueEstimatesAsync(string? performerId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(performerId))
|
||||
{
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
|
||||
return _context.Performers
|
||||
.AsNoTracking()
|
||||
.AnyAsync(profile => profile.PerformerId == performerId
|
||||
&& profile.SIREN != null
|
||||
&& profile.SIREN.Trim() != "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -138,6 +138,10 @@ namespace Yavsc.Controllers
|
|||
{
|
||||
return View();
|
||||
}
|
||||
public IActionResult CGU()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
public IActionResult AboutMarkdown()
|
||||
{
|
||||
return View();
|
||||
|
|
|
|||
167
src/Yavsc.Org/Controllers/ResourceSubscriptionController.cs
Normal file
167
src/Yavsc.Org/Controllers/ResourceSubscriptionController.cs
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
#nullable enable
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Settings;
|
||||
using Yavsc.ViewModels;
|
||||
using Yavsc.Web.Services;
|
||||
|
||||
namespace Yavsc.Controllers;
|
||||
|
||||
[Authorize(Policy = "WebUser")]
|
||||
[ResourceUsageExempt]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class ResourceSubscriptionController(IResourceSubscriptionService subscriptions,
|
||||
IPayPalSubscriptionGateway paypal, IResourceUsageService usage,
|
||||
IOptions<ResourceSubscriptionOptions> options, IOptions<ResourceUsageOptions> usageOptions,
|
||||
IOptions<SiteSettings> site, ILogger<ResourceSubscriptionController> logger) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Index(CancellationToken ct)
|
||||
=> View(new ResourceSubscriptionPage(options.Value, usageOptions.Value.DefaultLimit,
|
||||
await usage.GetCurrentAsync(User.GetUserId(), User.Identity?.Name ?? User.GetUserId(), ct),
|
||||
await subscriptions.GetAllAsync(User.GetUserId(), ct)));
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Create(string pack, CancellationToken ct)
|
||||
{
|
||||
var subscription = await subscriptions.PrepareAsync(User.GetUserId(), pack, ct);
|
||||
PayPalSubscriptionDetails remote;
|
||||
if (subscription.PayPalId is null)
|
||||
{
|
||||
var root = SiteRoot();
|
||||
remote = await paypal.CreateAsync(subscription,
|
||||
root + "ResourceSubscription/Return?id=" + subscription.Id,
|
||||
root + "ResourceSubscription", ct);
|
||||
await subscriptions.BindAsync(subscription, remote, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
remote = await paypal.GetAsync(subscription.PayPalId, ct);
|
||||
await subscriptions.BindAsync(subscription, remote, ct);
|
||||
}
|
||||
if (remote.ApprovalUrl is not null && remote.State == "APPROVAL_PENDING")
|
||||
return Redirect(remote.ApprovalUrl);
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Return(Guid id, CancellationToken ct)
|
||||
{
|
||||
var subscription = await OwnedAsync(id, ct);
|
||||
if (subscription is null) return NotFound();
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Refresh(CancellationToken ct)
|
||||
{
|
||||
foreach (var subscription in await subscriptions.GetAllAsync(User.GetUserId(), ct))
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
|
||||
{
|
||||
var subscription = await OwnedAsync(id, ct);
|
||||
if (subscription is null || subscription.PayPalId is null) return NotFound();
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
if (subscription.State is not ("CANCELLED" or "EXPIRED"))
|
||||
await paypal.CancelAsync(subscription.PayPalId, ct);
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[AllowAnonymous, HttpPost, IgnoreAntiforgeryToken, RawPayPalNotification, RequestSizeLimit(64 * 1024)]
|
||||
public async Task<IActionResult> Notify(CancellationToken ct)
|
||||
{
|
||||
JsonDocument notification;
|
||||
try
|
||||
{
|
||||
notification = await JsonDocument.ParseAsync(Request.Body, cancellationToken: ct);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Malformed PayPal subscription notification");
|
||||
return BadRequest();
|
||||
}
|
||||
using (notification)
|
||||
{
|
||||
var headers = Request.Headers.ToDictionary(pair => pair.Key, pair => pair.Value.ToString(), StringComparer.OrdinalIgnoreCase);
|
||||
await paypal.VerifyWebhookAsync(notification.RootElement, headers, ct);
|
||||
var value = notification.RootElement;
|
||||
if (value.ValueKind != JsonValueKind.Object
|
||||
|| !value.TryGetProperty("event_type", out var type) || type.ValueKind != JsonValueKind.String
|
||||
|| !value.TryGetProperty("resource", out var resource) || resource.ValueKind != JsonValueKind.Object)
|
||||
throw new SubscriptionOperationException(400, "Notification PayPal incomplete.");
|
||||
var eventType = type.GetString()!;
|
||||
if (!eventType.StartsWith("BILLING.SUBSCRIPTION.", StringComparison.Ordinal)
|
||||
&& eventType is not ("PAYMENT.SALE.COMPLETED" or "PAYMENT.SALE.REFUNDED" or "PAYMENT.SALE.REVERSED"))
|
||||
return NoContent();
|
||||
ResourceSubscription? subscription;
|
||||
var key = eventType.StartsWith("BILLING.", StringComparison.Ordinal) ? "id" : "billing_agreement_id";
|
||||
var paypalId = NotificationText(resource, key);
|
||||
if (paypalId is not null)
|
||||
subscription = await subscriptions.FindPayPalAsync(paypalId, ct);
|
||||
else
|
||||
{
|
||||
var transactionId = NotificationText(resource, "sale_id") ?? NotificationText(resource, "id");
|
||||
subscription = transactionId is null ? null : await subscriptions.FindPaymentAsync(transactionId, ct);
|
||||
if (subscription is null && resource.TryGetProperty("links", out var links))
|
||||
{
|
||||
if (links.ValueKind != JsonValueKind.Array)
|
||||
throw new SubscriptionOperationException(400, "Liens de notification PayPal invalides.");
|
||||
foreach (var link in links.EnumerateArray())
|
||||
{
|
||||
if (link.ValueKind != JsonValueKind.Object)
|
||||
throw new SubscriptionOperationException(400, "Lien de notification PayPal invalide.");
|
||||
if (!Uri.TryCreate(NotificationText(link, "href"), UriKind.Absolute, out var uri)
|
||||
|| uri.Scheme != "https" || uri.Host is not ("api.paypal.com" or "api.sandbox.paypal.com" or "api-m.paypal.com" or "api-m.sandbox.paypal.com")
|
||||
|| !uri.AbsolutePath.StartsWith("/v1/payments/sale/", StringComparison.Ordinal)) continue;
|
||||
subscription = await subscriptions.FindPaymentAsync(uri.Segments[^1], ct);
|
||||
if (subscription is not null) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (subscription is null) return NotFound();
|
||||
// The signed notification is a trigger, not the payment authority.
|
||||
// Re-fetch the bound subscription and all transactions from PayPal.
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ResourceSubscription?> OwnedAsync(Guid id, CancellationToken ct)
|
||||
=> (await subscriptions.GetAllAsync(User.GetUserId(), ct)).SingleOrDefault(s => s.Id == id);
|
||||
|
||||
private static string? NotificationText(JsonElement value, string property)
|
||||
{
|
||||
if (!value.TryGetProperty(property, out var found)) return null;
|
||||
return found.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(found.GetString())
|
||||
? found.GetString() : throw new SubscriptionOperationException(400, "Reference de notification PayPal invalide.");
|
||||
}
|
||||
|
||||
private string SiteRoot()
|
||||
{
|
||||
if (!Uri.TryCreate(site.Value.ExternalUrl, UriKind.Absolute, out var uri)
|
||||
|| uri.Scheme != "https" || !string.IsNullOrEmpty(uri.UserInfo))
|
||||
throw new SubscriptionOperationException(503, "L'adresse HTTPS publique du site n'est pas configuree.");
|
||||
return site.Value.ExternalUrl.TrimEnd('/') + "/";
|
||||
}
|
||||
|
||||
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
var executed = await next();
|
||||
if (executed.Exception is not SubscriptionOperationException error || Response.HasStarted) return;
|
||||
logger.LogError(error, "Resource subscription operation failed for {Action}", context.ActionDescriptor.DisplayName);
|
||||
executed.ExceptionHandled = true;
|
||||
executed.Result = Problem(statusCode: error.StatusCode, title: "Abonnement indisponible", detail: error.Message);
|
||||
}
|
||||
}
|
||||
|
|
@ -83,6 +83,23 @@ public static class HostingExtensions
|
|||
builder.Services.AddSwaggerGen();
|
||||
|
||||
IServiceCollection services = LoadConfiguration(builder);
|
||||
services.AddResourceUsage(builder.Configuration);
|
||||
services.AddOptions<ResourceSubscriptionOptions>()
|
||||
.Bind(builder.Configuration.GetSection(ResourceSubscriptionOptions.SectionName))
|
||||
.Validate(o => o.DiscoveryPriceExcludingTax > 0m && o.PremiumPriceExcludingTax > 0m
|
||||
&& decimal.Round(o.DiscoveryPriceExcludingTax, 2) == o.DiscoveryPriceExcludingTax
|
||||
&& decimal.Round(o.PremiumPriceExcludingTax, 2) == o.PremiumPriceExcludingTax
|
||||
&& o.VatPercent >= 0m && o.VatPercent <= 100m,
|
||||
"ResourceSubscriptions prices and VAT are invalid.")
|
||||
.ValidateOnStart();
|
||||
services.AddHttpClient<Yavsc.Web.Services.IPayPalSubscriptionGateway, Yavsc.Web.Services.PayPalSubscriptionGateway>()
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
services.AddScoped<Yavsc.Web.Services.IResourceSubscriptionService, Yavsc.Web.Services.ResourceSubscriptionService>();
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.AddScoped<IPaymentResidueService, PaymentResidueService>();
|
||||
services.AddScoped<Yavsc.Web.Services.IAccountWithdrawalService, Yavsc.Web.Services.AccountWithdrawalService>();
|
||||
services.Configure<Yavsc.Services.PodcastOptions>(builder.Configuration.GetSection("Podcast"));
|
||||
services.AddHostedService<Yavsc.Web.Services.PaymentResiduePurgeWorker>();
|
||||
|
||||
services.AddSession();
|
||||
|
||||
|
|
@ -1053,10 +1070,14 @@ public static class HostingExtensions
|
|||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
app.UseRouting();
|
||||
// CORS must run before IdentityServer/Auth middleware so the discovery
|
||||
// document and token endpoints can emit the required
|
||||
// Access-Control-Allow-Origin headers on cross-origin browser fetches.
|
||||
app.UseCors("default");
|
||||
app.UseAuthentication();
|
||||
app.UseMiddleware<WithdrawnAccountMiddleware>();
|
||||
app.UseIdentityServer();
|
||||
app.UseAuthorization();
|
||||
app.UseCors("default");
|
||||
app.MapDefaultControllerRoute();
|
||||
app.MapStaticAssets(staticAssetsManifestPath);
|
||||
|
||||
|
|
|
|||
5197
src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.Designer.cs
generated
Normal file
5197
src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
107
src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.cs
Normal file
107
src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.cs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ResourceSubscriptions : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<decimal>(
|
||||
name: "CreditPoints",
|
||||
table: "ResourceUsageRecords",
|
||||
type: "numeric(28,8)",
|
||||
precision: 28,
|
||||
scale: 8,
|
||||
nullable: false,
|
||||
defaultValue: 0m);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ResourceSubscriptions",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
UserId = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||
Pack = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
PlanId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
PayPalId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
|
||||
State = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
MonthlyPoints = table.Column<decimal>(type: "numeric(28,8)", precision: 28, scale: 8, nullable: false),
|
||||
PriceExcludingTax = table.Column<decimal>(type: "numeric(18,2)", nullable: false),
|
||||
VatPercent = table.Column<decimal>(type: "numeric", nullable: false),
|
||||
PriceIncludingTax = table.Column<decimal>(type: "numeric(18,2)", nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
StartsAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
NextBillingAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
LastCreditedCycle = table.Column<int>(type: "integer", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ResourceSubscriptions", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_ResourceSubscriptions_AspNetUsers_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ResourceSubscriptionPayments",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
SubscriptionId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Cycle = table.Column<int>(type: "integer", nullable: false),
|
||||
PaidAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
GrantedPoints = table.Column<decimal>(type: "numeric(28,8)", precision: 28, scale: 8, nullable: false),
|
||||
Reversed = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ResourceSubscriptionPayments", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_ResourceSubscriptionPayments_ResourceSubscriptions_Subscrip~",
|
||||
column: x => x.SubscriptionId,
|
||||
principalTable: "ResourceSubscriptions",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ResourceSubscriptionPayments_SubscriptionId_Cycle",
|
||||
table: "ResourceSubscriptionPayments",
|
||||
columns: new[] { "SubscriptionId", "Cycle" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ResourceSubscriptions_PayPalId",
|
||||
table: "ResourceSubscriptions",
|
||||
column: "PayPalId",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ResourceSubscriptions_UserId",
|
||||
table: "ResourceSubscriptions",
|
||||
column: "UserId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "ResourceSubscriptionPayments");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "ResourceSubscriptions");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CreditPoints",
|
||||
table: "ResourceUsageRecords");
|
||||
}
|
||||
}
|
||||
}
|
||||
5200
src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.Designer.cs
generated
Normal file
5200
src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
29
src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.cs
Normal file
29
src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.cs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PremiumDiskQuota : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "PremiumDiskQuotaUntil",
|
||||
table: "AspNetUsers",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PremiumDiskQuotaUntil",
|
||||
table: "AspNetUsers");
|
||||
}
|
||||
}
|
||||
}
|
||||
5203
src/Yavsc.Org/Migrations/20261108045419_DiscoveryDiskQuota.Designer.cs
generated
Normal file
5203
src/Yavsc.Org/Migrations/20261108045419_DiscoveryDiskQuota.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,29 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class DiscoveryDiskQuota : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "DiscoveryDiskQuotaUntil",
|
||||
table: "AspNetUsers",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DiscoveryDiskQuotaUntil",
|
||||
table: "AspNetUsers");
|
||||
}
|
||||
}
|
||||
}
|
||||
5221
src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.Designer.cs
generated
Normal file
5221
src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,34 @@
|
|||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class RefundableResourceStorage : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ResourceStorageRecords",
|
||||
columns: table => new
|
||||
{
|
||||
UserId = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||
Path = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: false),
|
||||
Bytes = table.Column<long>(type: "bigint", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ResourceStorageRecords", x => new { x.UserId, x.Path });
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "ResourceStorageRecords");
|
||||
}
|
||||
}
|
||||
}
|
||||
5228
src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.Designer.cs
generated
Normal file
5228
src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
43
src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.cs
Normal file
43
src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AccountWithdrawal : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropUniqueConstraint(name: "AK_AspNetUsers_Email", table: "AspNetUsers");
|
||||
migrationBuilder.CreateIndex(name: "IX_AspNetUsers_Email", table: "AspNetUsers", column: "Email", unique: true);
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "WithdrawalRequestedAt",
|
||||
table: "AspNetUsers",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "WithdrawnAt",
|
||||
table: "AspNetUsers",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(name: "IX_AspNetUsers_Email", table: "AspNetUsers");
|
||||
migrationBuilder.AddUniqueConstraint(name: "AK_AspNetUsers_Email", table: "AspNetUsers", column: "Email");
|
||||
migrationBuilder.DropColumn(
|
||||
name: "WithdrawalRequestedAt",
|
||||
table: "AspNetUsers");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "WithdrawnAt",
|
||||
table: "AspNetUsers");
|
||||
}
|
||||
}
|
||||
}
|
||||
5242
src/Yavsc.Org/Migrations/20261108073234_PodcastObsIngestion.Designer.cs
generated
Normal file
5242
src/Yavsc.Org/Migrations/20261108073234_PodcastObsIngestion.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue