Manicraft1001
Manicraft1001
Explore posts from servers
CC#
Created by Manicraft1001 on 4/23/2025 in #help
Handle DbContext and IDbContextFactory<T> lifetime in Blazor InteractiveServer
Hi, I have some trouble getting EfCore to run properly with Blazor components and pages. I scaffolded a project using the Identity UI template and implemented business logic. I wanted to deploy a first version on production but I'm stuck with flaky instances of the DbContext. For example, the autogenerated Components/Account/Pages/Manage/Index.razor page contains the following initialization method:
protected override async Task OnInitializedAsync()
{
_user = await UserAccessor.GetRequiredUserAsync(HttpContextAccessor.HttpContext!);
_username = await UserManager.GetUserNameAsync(_user);
_phoneNumber = await UserManager.GetPhoneNumberAsync(_user);

Input.PhoneNumber ??= _phoneNumber;
Input.IsAdult = _user.IsAdult;
}
protected override async Task OnInitializedAsync()
{
_user = await UserAccessor.GetRequiredUserAsync(HttpContextAccessor.HttpContext!);
_username = await UserManager.GetUserNameAsync(_user);
_phoneNumber = await UserManager.GetPhoneNumberAsync(_user);

Input.PhoneNumber ??= _phoneNumber;
Input.IsAdult = _user.IsAdult;
}
In the same razor file, I inject the factory for the DB context at the top;
@inject IDbContextFactory<ApplicationDbContext> DbContextFactory
@inject IDbContextFactory<ApplicationDbContext> DbContextFactory
I then update some properties in a method below:
if (Input.IsAdult != _user.IsAdult)
{
await using (ApplicationDbContext dbContext = DbContextFactory.CreateDbContext())
{
ApplicationUser dbUser = await dbContext.Users.SingleAsync(dbUser => dbUser.Id == _user.Id);
dbUser.IsAdult = Input.IsAdult;
await dbContext.SaveChangesAsync();
}
}
if (Input.IsAdult != _user.IsAdult)
{
await using (ApplicationDbContext dbContext = DbContextFactory.CreateDbContext())
{
ApplicationUser dbUser = await dbContext.Users.SingleAsync(dbUser => dbUser.Id == _user.Id);
dbUser.IsAdult = Input.IsAdult;
await dbContext.SaveChangesAsync();
}
}
This results in the following stacktrace:
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usuall
y caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
at Microsoft.EntityFrameworkCore.Infrastructure.Internal.ConcurrencyDetector.EnterCriticalSection()
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at XXXXXXXXXXXXX.Components.Account.IdentityUserAccessor.GetRequiredUserAsync(HttpContext context) in C:\XXXXXXXXXXXXX\Components\Account\IdentityUserAccessor.cs:line 12
at XXXXXXXXXXXXX.Components.Account.Pages.Manage.Index.OnInitializedAsync() in C:\XXXXXXXXXXXXX\Components\Account\Pages\Manage\Index.razor:line 63
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usuall
y caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
at Microsoft.EntityFrameworkCore.Infrastructure.Internal.ConcurrencyDetector.EnterCriticalSection()
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at XXXXXXXXXXXXX.Components.Account.IdentityUserAccessor.GetRequiredUserAsync(HttpContext context) in C:\XXXXXXXXXXXXX\Components\Account\IdentityUserAccessor.cs:line 12
at XXXXXXXXXXXXX.Components.Account.Pages.Manage.Index.OnInitializedAsync() in C:\XXXXXXXXXXXXX\Components\Account\Pages\Manage\Index.razor:line 63
I've read and understood this official guide to work with EfCore in Blazor apps, but even though I never use DbContext directly and always create an instance on the fly using IDbContextFactory<AppDbContext>, I still get this error. Here is the content of the IdentityUserAccessor:
internal sealed class IdentityUserAccessor(
UserManager<ApplicationUser> userManager,
IdentityRedirectManager redirectManager)
{
public async Task<ApplicationUser> GetRequiredUserAsync(HttpContext context)
{
var user = await userManager.GetUserAsync(context.User);

if (user is null)
{
redirectManager.RedirectToWithStatus("Account/InvalidUser",
$"Error: Unable to load user with ID '{userManager.GetUserId(context.User)}'.", context);
}

return user;
}
}
internal sealed class IdentityUserAccessor(
UserManager<ApplicationUser> userManager,
IdentityRedirectManager redirectManager)
{
public async Task<ApplicationUser> GetRequiredUserAsync(HttpContext context)
{
var user = await userManager.GetUserAsync(context.User);

if (user is null)
{
redirectManager.RedirectToWithStatus("Account/InvalidUser",
$"Error: Unable to load user with ID '{userManager.GetUserId(context.User)}'.", context);
}

return user;
}
}
Why is this happening? What am I doing wrong? Thanks for your help in advance! 🚀🙌
2 replies
DIAdiscord.js - Imagine an app
Created by Manicraft1001 on 10/16/2024 in #djs-voice
AudioPlayer goes from buffering -> playing -> idle and warns that resource is not playable
Hi, I have troubles for the last months with playback of resources. The source is available at https://github.com/manuel-rw/jellyfin-discord-music-bot Even though the stream URL seems correct to me, the bot goes into idle after a few milliseconds and it stays silent in Discord. I have tried different variations of the stream URL but they dont' seem to change anything. It used to work fine - I did not make an update of discord.js in the mean time. The code playing for resources is distributed, but let me summarise it shortly:
playResource(resource: AudioResource<unknown>) {
this.logger.debug(
`Playing audio resource with volume ${resource.volume?.volume} (${resource.playbackDuration}) (readable: ${resource.readable}) (volume: ${resource.volume?.volume} (${resource.volume?.volumeDecibels}dB)) (silence remaining: ${resource.silenceRemaining}) (silence padding frames: ${resource.silencePaddingFrames}) (metadata: ${resource.metadata})`,
);
this.createAndReturnOrGetAudioPlayer().play(resource);
this.audioResource = resource;

const isPlayable = this.audioPlayer?.checkPlayable();
if (isPlayable) {
return;
}
this.logger.warn(
`Current resource is is not playable. This means playback will get stuck. Please report this issue.`,
); // <--- this is where the bot goes into. It seems that the track is never playable
}
playResource(resource: AudioResource<unknown>) {
this.logger.debug(
`Playing audio resource with volume ${resource.volume?.volume} (${resource.playbackDuration}) (readable: ${resource.readable}) (volume: ${resource.volume?.volume} (${resource.volume?.volumeDecibels}dB)) (silence remaining: ${resource.silenceRemaining}) (silence padding frames: ${resource.silencePaddingFrames}) (metadata: ${resource.metadata})`,
);
this.createAndReturnOrGetAudioPlayer().play(resource);
this.audioResource = resource;

const isPlayable = this.audioPlayer?.checkPlayable();
if (isPlayable) {
return;
}
this.logger.warn(
`Current resource is is not playable. This means playback will get stuck. Please report this issue.`,
); // <--- this is where the bot goes into. It seems that the track is never playable
}
@OnEvent('internal.audio.track.announce')
handleOnNewTrack(track: Track) {
const resource = createAudioResource( // <--- builds the stream URL. Seems to build the correct one. Tried with OPUS and AAC
track.getStreamUrl(this.jellyfinStreamBuilder),
{
inlineVolume: true,
},
);
this.playResource(resource); // <-- calls the above function
}
@OnEvent('internal.audio.track.announce')
handleOnNewTrack(track: Track) {
const resource = createAudioResource( // <--- builds the stream URL. Seems to build the correct one. Tried with OPUS and AAC
track.getStreamUrl(this.jellyfinStreamBuilder),
{
inlineVolume: true,
},
);
this.playResource(resource); // <-- calls the above function
}
All relevant code in discord.voice.service.ts Log: https://pastebin.com/ZGyrYzmQ I already added tons of debugging branches & log statements to troubleshoot. Do you have suggestions for the next steps? How can I troubleshoot resources that can't be played? Also, the docs don't go into much detail why resources aren't "playable". I read the following pages and could not find further steps / ideas: https://discordjs.guide/voice/audio-resources.html#cheat-sheet, https://discord.js.org/docs/packages/voice/0.13.0/AudioPlayer:Class#checkPlayable Node: v20.13.1
jellyfin-discord-music-bot@1.0.0 C:\XXXXXX\jellyfin-discord-music-bot
+-- @discord-nestjs/common@5.2.12
| `-- discord.js@14.15.2 deduped
+-- @discord-nestjs/core@5.3.14
| `-- discord.js@14.15.2 deduped
`-- discord.js@14.15.2
jellyfin-discord-music-bot@1.0.0 C:\XXXXXX\jellyfin-discord-music-bot
+-- @discord-nestjs/common@5.2.12
| `-- discord.js@14.15.2 deduped
+-- @discord-nestjs/core@5.3.14
| `-- discord.js@14.15.2 deduped
`-- discord.js@14.15.2
Crosspost from #djs-questions , wrong channel. Sorry.
9 replies
AOAnswer Overflow
Created by Manicraft1001 on 9/5/2023 in #questions
Bot does not post consent prompt automatically
Hello 👋 Our bot does not send the consent prompt automatically. /send-consent-promt does work and the notice about messages being indexed has been added to the server rules and the posts channel. What configurations need to be done, to automatically send the prompt?
26 replies
TTCTheo's Typesafe Cult
Created by Manicraft1001 on 6/21/2023 in #questions
Empty JWT payload, persisting role permissions and "jankiness" with next-auth
Hello lads. I'm struggeling to get next-auth up and running. It has been working decently, but I have several issues that I'm unable to resolve, even after days of trying out different solutions, package versions and more. Here's what I'm trying to do: - Authentication with Discord & credentials - Implement a role system - Protect certain tRPC procedures for logged in users or users with specific roles Currently, the following issues are present: - When authenticating with Discord, a ID in the user table is generated. However, the session does not contain an ID. I am unable to use the ID in any of my tRPC procedures and therefore can't associate data in the DB with a user. - The payload section in the JWT is empty. Yes, completely empty. I'm not even sure why and how this is somewhat working, but it's definitely not secure nor usable. I do return valid data in all callbacks and copied them from the official documentation. - When an admin changes the roles of a user, the token will still be valid and the user still has the permissions of that role. That's obviously very bad, since the JWT only expires after 30 days and I wasn't able to work around this. The source code is available here: https://github.com/manuel-rw/kana Instructions for set up are located in the readme. It seems like there are major configuration issues with next-auth. The documentation is a bit vague and I'm not understanding, what I'm doing wrong. I don't want to treat users from OAuth providers any different than compared to the credentials in my tRPC routes. Please let me know if you have any questions, and I'll make sure to answer them asap! Environment: Node.js 18 Windows & Linux Versions of all dependencies in the package.json
45 replies
DIAdiscord.js - Imagine an app
Created by Manicraft1001 on 1/24/2023 in #djs-questions
What are possible causes for "DiscordAPIError[10062]: Unknown interaction"
Hello 👋 A user of my bot reported that they are getting the following error:
DiscordAPIError[10062]: Unknown interaction
at SequentialHandler.runRequest (/root/jellyfin-discord-music-bot/node_modules/@discordjs/rest/dist/index.js:667:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (/root/jellyfin-discord-music-bot/node_modules/@discordjs/rest/dist/index.js:464:14)
at async REST.request (/root/jellyfin-discord-music-bot/node_modules/@discordjs/rest/dist/index.js:910:22)
at async ChatInputCommandInteraction.reply (/root/jellyfin-discord-music-bot/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:111:5)
at async SummonCommand.handler (/root/jellyfin-discord-music-bot/dist/commands/summon.command.js:41:9)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:251:10)
at processTicksAndRejections (node:internal/process/task_queues:85:21) {
requestBody: {
files: [],
json: {
type: 4,
data: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [ { color: 7828684, author: [Object], footer: [Object] } ],
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined,
thread_name: undefined
}
}
},
rawError: { message: 'Unknown interaction', code: 10062 },
code: 10062,
status: 404,
method: 'POST',
url: 'https://discord.com/api/v10/interactions/callback'
}
DiscordAPIError[10062]: Unknown interaction
at SequentialHandler.runRequest (/root/jellyfin-discord-music-bot/node_modules/@discordjs/rest/dist/index.js:667:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (/root/jellyfin-discord-music-bot/node_modules/@discordjs/rest/dist/index.js:464:14)
at async REST.request (/root/jellyfin-discord-music-bot/node_modules/@discordjs/rest/dist/index.js:910:22)
at async ChatInputCommandInteraction.reply (/root/jellyfin-discord-music-bot/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:111:5)
at async SummonCommand.handler (/root/jellyfin-discord-music-bot/dist/commands/summon.command.js:41:9)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:251:10)
at processTicksAndRejections (node:internal/process/task_queues:85:21) {
requestBody: {
files: [],
json: {
type: 4,
data: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [ { color: 7828684, author: [Object], footer: [Object] } ],
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined,
thread_name: undefined
}
}
},
rawError: { message: 'Unknown interaction', code: 10062 },
code: 10062,
status: 404,
method: 'POST',
url: 'https://discord.com/api/v10/interactions/callback'
}
I instantly expected that Discord was probably not happy with the response time, since the action may take some while. So I refactored to use await deferReply(). This works for me, but the users still has the same error. We already debugged everything around and concluded, that await deferReply() just under a second. deferReply does not seem to be the issue. I call it correctly. This issue has already been reported once, but the thread was locked: https://github.com/discordjs/discord.js/issues/7005 Thus, I decided to ask here, what other possible issues besides the timeout, could cause this issue. I'm happy to provide the source code, but I sadly can't reproduce the error on my machine. I can provide the code, but as the issue already says, the code does not seem to be the problem here.
PS D:\jellyfin-discord-music-bot> npm list discord.js
jellyfin-discord-music-bot@0.0.3 D:\jellyfin-discord-music-bot
├─┬ @discord-nestjs/common@4.0.8
│ └── discord.js@14.7.1 deduped
├─┬ @discord-nestjs/core@4.3.1
│ └── discord.js@14.7.1 deduped
└── discord.js@14.7.1

PS D:\jellyfin-discord-music-bot> node -v
v16.17.1
PS D:\jellyfin-discord-music-bot> npm list discord.js
jellyfin-discord-music-bot@0.0.3 D:\jellyfin-discord-music-bot
├─┬ @discord-nestjs/common@4.0.8
│ └── discord.js@14.7.1 deduped
├─┬ @discord-nestjs/core@4.3.1
│ └── discord.js@14.7.1 deduped
└── discord.js@14.7.1

PS D:\jellyfin-discord-music-bot> node -v
v16.17.1
4 replies
DIAdiscord.js - Imagine an app
Created by Manicraft1001 on 12/25/2022 in #djs-voice
Elapsed audio resource duration
Hello everyone, I'm currently trying to implement a proper progress bar which displays the playback of the current song. According to a few questions online, it seems like discord.js used to have a streamTime property. It looks like this has been removed for some reason in the next release. - Why has this been removed? - Is there any replacement or other way to get the current position in millis? I saw https://discord.js.org/#/docs/voice/main/class/AudioResource?scrollTo=playbackDuration, but this seems to be something different. I am playing the resource using this method: https://github.com/manuel-rw/jellyfin-discord-music-bot/blob/92021dd94e824af91a559d161df11b2898812595/src/clients/discord/discord.voice.service.ts#L87
18 replies
HHomarr
Created by Manicraft1001 on 9/14/2022 in #💬・get-help
Welcome to discussions! 💬 Please follow the guidelines 🙌
We have migrated our "get-help" channel to Discord discussions. If you're having issues, questions or a bug, feel free to ask your question here. Make sure to follow our post guidelines!
4 replies