<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Giulio Pimenoff Verdolin on Medium]]></title>
        <description><![CDATA[Stories by Giulio Pimenoff Verdolin on Medium]]></description>
        <link>https://medium.com/@gpimenoff?source=rss-a79a9e871bc1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Zz714vhYtJBaZKHdaUp4VQ.png</url>
            <title>Stories by Giulio Pimenoff Verdolin on Medium</title>
            <link>https://medium.com/@gpimenoff?source=rss-a79a9e871bc1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:31:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gpimenoff/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Never pass the wrong ID again, typed IDs in Kotlin]]></title>
            <link>https://medium.com/@gpimenoff/never-pass-the-wrong-id-again-typed-ids-in-kotlin-9be9dffdd554?source=rss-a79a9e871bc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9be9dffdd554</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Giulio Pimenoff Verdolin]]></dc:creator>
            <pubDate>Tue, 12 May 2026 00:30:34 GMT</pubDate>
            <atom:updated>2026-05-12T00:30:34.335Z</atom:updated>
            <content:encoded><![CDATA[<p>ever debugged some features in your app, got to query the database or cache only to find out you were passing the wrong ID to some function or logic? <br>well you can drastically reduce the occurrence of this situation with typed IDs, and here is how I implemented them for my app backend in Kotlin.</p><h3>creating the type</h3><p>It’s actually quite symple, we first need a Kotlin type that can identify an ID. <br>In my case I used UUIDs in my app, so I implemented typed IDs with UUID values, but you can modify them to support any kind of ID values (for this I highly suggest <a href="https://brandur.org/nanoglyphs/026-ids">this article</a> by <a href="https://brandur.org/">brandur</a>).</p><p>Let’s jump in the code:</p><pre>// you could technically skip declaring this ID interface<br>interface Id&lt;T&gt; {}<br><br>// this class is our ID type.<br>// it&#39;s called IxId because the app name is Index<br>data class IxId&lt;T&gt;(val id: UUID) : Id&lt;T&gt; {<br>    constructor(id: String) : this(UUID.fromString(id))<br><br>    override fun toString(): String {<br>        return id.toString()<br>    }<br>}</pre><p>this is just a wrapper type at the end, and using it is super straight forward:</p><pre>@Serializable<br>data class TaskData(<br>    @Contextual val id: IxId&lt;TaskData&gt;,<br>    @Contextual val user_id: IxId&lt;UserData&gt;,<br>    @Contextual val item_id: IxId&lt;ItemData&gt;? = null,<br>    val name: String,<br>    ...<br>)</pre><p>this class represent a todo that gets stored in the Postgres database of my app, and you can see how it requires a bunch of different IDs.</p><p>then in my DAO I have methods related to that class that require different IDs depending on the end goal, for example:</p><pre>suspend fun getAllCompleted(userId: IxId&lt;UserData&gt;): List&lt;TaskData&gt; {<br>    return taskDBI.getCompleted(userId)<br>}<br><br>suspend fun getAllConnectedToItem(itemId: IxId&lt;ItemData&gt;): List&lt;TaskData&gt; {<br>    return taskDBI.getConnectedToItem(itemId)<br>}</pre><p>if we were not to use typed IDs, all function arguments would have been String or UUID and it would be super easy to pass the wrong ID to them, while in this way I get type checks by the LSP directly when calling that function:</p><pre>/**<br> * Gets all the tasks of a user with an optional completion filter.<br> *<br> * Tag: tasks<br> *<br> * Security: session<br> */<br>get&lt;TasksRoute&gt; {<br>    val userId = userIdFromSessionOrThrow()<br><br>    val tasks = when (it.completed) {<br>        true -&gt; taskDao.getAllCompleted(userId)<br>        false -&gt; taskDao.getAllUncompleted(userId)<br>        null -&gt; taskDao.getAll(userId)<br>    }<br><br>    call.respond(tasks)<br>}</pre><h3>making a generator</h3><p>we need a way to generate those IDs though, so I made a small utility class for it.</p><pre>class IxIdGenerator : IdGenerator {<br>    // the type of the ID itself<br>    override val idClass: KClass&lt;out Id&lt;*&gt;&gt; = IxId::class<br><br>    // the type of the value that the ID class wraps<br>    override val wrappedIdClass: KClass&lt;out Any&gt; = UUID::class<br><br>    override fun &lt;T&gt; generateNewId(): Id&lt;T&gt; = IxId(UUID.randomUUID())<br>}<br><br>interface IdGenerator {<br>    ...<br><br>    /**<br>     * Create a new id from its String representation.<br>     */<br>    fun create(s: String): Id&lt;*&gt; =<br>        idClass<br>            .constructors<br>            .firstOrNull { it.valueParameters.size == 1 &amp;&amp; it.valueParameters.first().type.classifier == String::class }<br>            ?.call(s)<br>            ?: error(&quot;no constructor with a single string arg found for $idClass}&quot;)<br><br>    ...<br>}</pre><p>you can see that I abstracted it using a generic IdGenerator. <br>I use the create() method later on in the serializer, it might seem complicated at first but it simply:<br>1) gets the constructors of the ID class we provide it with<br>2) finds the first contructor that requires only 1 argument where its type String<br>3) tries to instantiate the class using that constructor</p><p>you can also have utility functions if you want something simpler:</p><pre>fun &lt;T&gt; newIxId() = IxId&lt;T&gt;(UUID.randomUUID())</pre><p>or even a String extension for UUID IDs:</p><pre>/**<br> * @throws IllegalArgumentException if the string is not a valid UUID<br> */<br>fun &lt;T&gt; String.toIxId() = IxId&lt;T&gt;(this)</pre><h3>serialization</h3><p>you might have noticed the @Contextual annotation on the ID fields in the data classes. <br>that’s because we need to serialize and deserialize them, since I’m serving a REST API.</p><p>In my project I use <a href="https://github.com/kotlin/kotlinx.serialization">kotlinx-serialization</a> so I created an extension module for it:</p><pre>val IdKotlinXSerializationModule: SerializersModule by lazy {<br>    SerializersModule {<br>        contextual(IxId::class, IxIdSerializer())<br>    }<br>}<br><br>private class IxIdSerializer&lt;T : IxId&lt;*&gt;&gt; : KSerializer&lt;T&gt; {<br>    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor(&quot;IdSerializer&quot;, PrimitiveKind.STRING)<br><br>    @Suppress(&quot;UNCHECKED_CAST&quot;)<br>    override fun deserialize(decoder: Decoder): T = IxIdGenerator().create(decoder.decodeString()) as T<br><br>    override fun serialize(<br>        encoder: Encoder,<br>        value: T,<br>    ) {<br>        // this works because we override the toString() method in `IxId`<br>        encoder.encodeString(value.toString())<br>    }<br>}</pre><p>I then registered the module in my Ktor plugin:</p><pre>fun Application.configureSerialization() {<br>    install(ContentNegotiation) {<br>        json(<br>            Json {<br>                serializersModule = IdKotlinXSerializationModule<br>                ignoreUnknownKeys = true<br>                encodeDefaults = true<br>            },<br>        )<br>    }<br>}</pre><p>just like that you can serialize and deserialize your ID types by appending a @Contextual annotation to them.</p><p>hope that was useful to you, next up is making them display cleanly in OpenAPI spec and even further I would love to start using prefixed IDs like Stripe does.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9be9dffdd554" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Story and lessons from building a Discord bot that reached 150k servers]]></title>
            <link>https://medium.com/@gpimenoff/story-and-lessons-from-building-a-discord-bot-that-reached-150k-servers-094b6d000c21?source=rss-a79a9e871bc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/094b6d000c21</guid>
            <category><![CDATA[indiedev]]></category>
            <category><![CDATA[discordapp]]></category>
            <category><![CDATA[discord]]></category>
            <category><![CDATA[discord-bot]]></category>
            <dc:creator><![CDATA[Giulio Pimenoff Verdolin]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 17:38:54 GMT</pubDate>
            <atom:updated>2025-11-15T17:38:54.897Z</atom:updated>
            <content:encoded><![CDATA[<p>it was the 27th of March 2020 when I got intrigued by the temporary voice channels system of the Rocket League discord server.<br>so I shot a message to their mods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7v47XOB-vl-WyD_t4OrT4g.jpeg" /></figure><p>and on the 11th of April I created my first Discord bot.</p><p>we are now 5 full years past that, and I went from a coding a basic javascript application which had me and a couple of friends as its users, to multiple microservices deployed on my own non-managed kubernetes cluster, handled via IaC (Infrastructure-as-Code), to manage more than 10k daily active users for a total count of 11M users in my database.</p><p>but wait, you are probably wondering what even are temporary voice channels, and what is a Discord bot in the first place (<a href="https://giuliopime.dev/blog/so-i-built-a-discord-bot#the-first-version">if not good, you can skip this</a>)…<br>basically, Discord is a messaging app (like slack, telegram or whatsapp).<br>you can create groups (which we’ll call guilds for the sake of this post), and in each group you can have multiple text channels, and multiple voice channels, which are like calls but you can have many different ones in a single guild.<br>consider that Discord has been built initially for gaming communities, so the usual case for a guild is a bunch of people (even 100k) just chatting about (very) weird stuff in the text chats of the guild and a bunch of voice channels, each with some people playing a game together and communicating using the voice chat as if it was a group call.</p><p>Discord exposes some APIs so that you can integrate functions to it.<br>usually, you create a Discord application, aka bot, you receive events from Discord (via websockets) and you react by performing some sort of action.</p><p>temporary voice channels is a feature that you can add to your guild, with which you design a voice channel as a “generator”: when a user joins the generator, my bot creates a new voice channel for the user and moves him into it, then once the channel gets empty again, my bot deletes it, keeping the server clean and tidy.<br>you can see what the bot does really quick in this video (well I’m making a demo video so this gif will get replaced soon, but settle with that for the moment):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*5HLVRJfNKg_mar9q55M-rQ.gif" /></figure><h3>the first version</h3><p>it would be untrue to say that I had 0 coding experience when I started, because I was taking informatics classes in high school, but I had no idea of how any real software was built and worked.<br>I just threw myself into it, and got my first bot online using javascript and the discord.js library.<br>of course, initially it was running on my computer, so I had to keep it on 24/7, and to give you an idea of how naive I was, my database was literally a .json file :)</p><p>I soon learned about hosting on a VPS, so I bought one from vultr and copied my code manually with FileZilla onto it (I think the first times I was also copying the node_modules black hole).<br>for a while, every time I had to update the bot, I would copy the files via SFTP on my server, get into the shell and restart the javascript process.</p><p>I do have really nice memories about that period of development, I was in high school and I was coding 24/7, and then when covid hit, I was coding during online classes too.<br>and the good thing is that I was actually using my bot, quite a lot, so it was really cool to tell my friends about new features we could use in our guild and have them play around with the bot.<br>here is a little screenshot of what it looked like (and yes it was called HallMaster at the time, I rebranded to Astro later on)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*sGI_kQIAebTpnu5AA8TlPw.jpeg" /></figure><h3>first mistake and lesson</h3><p>I did make a lot of mistakes (of course… I had no knowledge!), lots of <a href="https://github.com/bot-astro/archived-Hall-Master/">crappy code</a> for sure, but the one that I wanna highlight here is about <em>asking for help</em>.<br>in the beginning, I was asking for <em>lots</em> of help in the top.gg discord guild (top.gg is a web catalog of Discord bots), and because my questions were kinda silly I received a lot of “<a href="https://letmegooglethat.com/?q=have+you+tried+googling+it%3F">have you tried googling it?</a>” which doesn’t feel good when starting out, but is something you 100% <em>need</em> to learn.<br>instead of reading documentation or stack overflow (yes because chatGPT wasn’t a thing back then, crazy right?), I was looking for a shortcut, and while it’s ok to do it sometimes, that should not be your go-to source of help.</p><p>I wanna mention <a href="https://xavin.dev/">Xavin</a> early on the article because he will come up a lot later on.<br>he was the developer of <a href="https://hydra.bot/">Hydra</a>, one of the biggest bots on Discord, which at the time was only used for playing music in your voice channels (now things have changed quite a bit since YouTube lawyered up against these music bots).<br>besides that, he was one of the nicest guys I’ve ever met on the internet, and so much of my knowledge comes from him, I truly do not think I would have made it this far without his help, he introduced me to Redis, InfluxDB, BigQuery, SpringBoot, Java, Kotlin, Kubernetes, CI-CD and so much more, I feel so grateful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*xKYS_m_ejyKyryMVpvFN-Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXupqyv1qsStYYW_fR4Vow.jpeg" /></figure><p>buut… initially I was kinda abusing that too, I was also asking questions about how he did stuff to be able to implement it in my bot, and kinda wanted to be spoon-fed.<br>he was super nice because very early on, he told me, and made me understand that I was approaching things the wrong way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyrAjh5u_xKRfGohyTtooQ.jpeg" /></figure><p>from that point on, I shifted my mentality, tried to come up with my own solutions and figure stuff out by doing my own research.</p><p>on a side note, I do believe that if AI had been there, I would not have learned as much as I did, so to those getting started, use AI as a browser engine, not as a replacement of your brain please, you will thank yourself in the future.</p><h3>growing, feedback and donations</h3><p>at that time, <a href="https://top.gg/">top.gg</a> had a huge amount of traffic, and I managed to get on their front-page for some time, thanks to people voting for my bot.<br>this gave me a lot of visibility, and the bot started to grow.<br>I also managed to set up some statistics using InfluxDB, so I had some very aesthetically pleasing view of how the bot was doing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04PqrUS_YCmUPLiaUIIs8A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4EycsLxcqsxHXsalsGPwg.jpeg" /></figure><p>I started receiving lots of feedback, and you can see some of it <a href="https://top.gg/bot/715621848489918495">on the bot top.gg page</a> in the reviews section.<br>then one day, and I remember it vividly, I received my first donation of $11 from a guy named RedGinor (thank you again ❤).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*WAJZibq22d94v518H6iC7A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcfU2FZKzzD0wOUE8-K05Q.jpeg" /></figure><p>I saw the bot was gaining new users every day but I didn’t really think it would be making money at all, but after that more followed, and I started tracking them in an Excel file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0JoGlLVFbZ-e0kSpJZ7kQ.jpeg" /></figure><p>so in a bunch of days, I set up a premium version of the bot for those who donated, and the activation process for it was all manual on my end, no fancy stripe integrations or anything. I was logging in the excel the donations and modifying a fancy .env file updating the list of premium guilds.</p><p>only after a while I set up a proper Patreon page, which lacked a lot in terms of API at the time, and later on moved to Chargebee, Stripe and PayPal (well Patreon was also my only option because I wasn’t even 18 back then so I literally could not open a PayPal account).</p><h3>first contract and infrastructure bottlenecks</h3><p>everything was going really well, the bot was growing steadily:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sN2nS-Ox5paNg9zjMKiUhw.jpeg" /></figure><p>with the money I was making I was able to pay for the VPS and thanks to people voting for my bot on top.gg, I could participate in ads auctions: I was betting on ads spots and it was really fun, you needed to consider whether the amount of visibility you would be getting was worth the money put into the bet, and I had some cool “fights” with one of my competitors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*LBge-HBSb1gOtoHJg8wMFQ.jpeg" /></figure><p>it was really cool seeing Astro being used in actually big guilds, like the official Overwatch, Elden Ring and Tekken guild, just to name a few.</p><p>I then signed up to a Discord beta program about <em>premium apps</em>, which would allow users to pay for the premium version of the bot directly inside Discord using their payment system.<br>I honestly wasn’t expecting much from it, but I actually got an email from Mason, at the time a Product Manager from Discord, asking for a call to figure whether I would be a great fit for the beta phase.<br>well, a month later that email I signed an actual contract (can’t disclose much about it unfortunately), I really went from making a Discord bot for my friend’s Discord, to signing an NDA, I had no words for it at the time…<br>this also lead me to contribute to the <a href="https://github.com/discord-jda/JDA">JDA</a> project, a library to interact with Discord in Java, which taught me about open source contribution and its best practices (you can find my PR <a href="https://github.com/discord-jda/JDA/pull/2583">here</a>).</p><p>it also seemed that the Discord team really liked my bot, as they decided to showcase it in their new “bots gallery” (aka App Directory)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*mYHzVyap1O1QFZSAoev_bg.jpeg" /></figure><p>and also used it as an example when talking to other developers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*q0IBosx3dYlUHQ7QE0ItcQ.jpeg" /></figure><p>thennn, bottlenecks started arising. I already migrated from javascript to Kotlin, but my bot was still running on a single process, and it was hella painful.<br>each restart for even a small update was taking 10+ minutes (which is 10+ minutes of downtime) and the Java Garbage Collector, started to complain too. this resulted in lots of painful debugging, heck I even tried remote debugging, won’t wish you that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7jAstVreFiG1Gk_mJb_hw.jpeg" /></figure><p>luckily, Xavin was there to help.<br>he was super stoked about the bot features, he even proposed to buy it! we eventually came to a deal to work on it together, me him and <a href="https://rxs.to/">rxsto</a>, who was another super talented front-end dev working on Hydra’s website.<br>so, he got me into kubernetes, and after a while, and some help setting up the k8s cluster using Pulumi (an infrastructure as code tool), I had my bot running in my own Kubernetes cluster, deployed on Hetzner servers.</p><p>one disclaimer: kubernetes has a steep learning curve, and small mistakes can lead to hours upon hours of debugging (lots of sleepless nights). so only use it when you need to.<br>in my case, it was necessary. Discord had a mechanism called sharding, which allowed your bot to run on multiple instances, and you could specify for each instance which shards it was gonna handle aka which pool of guilds it was going to receive events from. this makes it easy to split up the bot on different k8s pods, each handling a bunch of shards. restarting pods singularly results in a much lower downtime compared to restarting a bot that runs on a single process.<br>anyway, this gets explained more in detail in my bot’s README file on GitHub, link to that at the end of the article.</p><h3>the long awaited web dashboard</h3><p>a web dashboard to manage the bot settings was in the plans for a while, but I never did proper frontend development before.<br>the amount of settings available to configure the bot were way too many to handle in Discord with a decent UX.<br>this is the configuration help panel for one of the bot’s feature for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*Dv35B01IEJwYAGT6VSbnSQ.jpeg" /></figure><p>but ngl I really loved the way you could tweak those settings, I did set up a whole system (prior to when slash commands were a thing), in which the bot showed you all the configuration options, and you choose which one to modify by replying to the bot with the name of the setting you wanted to change (or the initials), and then the bot would prompt you for a new value for the setting.<br>it also handled concurrency properly, so you could be modifying the same setting only from one place at a time.<br>unfortunately, I have no videos about it, only a screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*EPmGYd6rt418BoRaEt-s7A.jpeg" /></figure><p>at one point though I just gave it a shot, taking inspiration from the <a href="https://atlas.bot/">atlas.bot</a> one, and honestly it took much less time than expected to build an amazing dashboard.<br>I think the evolution of the website is pretty cool, so here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTcaWMyIwlcSMO070xiL0w.jpeg" /><figcaption>very first version of the astro website, made with `create-react-app`. the ui was meant to replicate the old Discord profile cards!</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYQZ_pS_oWFk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYQZ_pS_oWFk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYQZ_pS_oWFk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4ffc9fefd2072d119137325894fac19/href">https://medium.com/media/c4ffc9fefd2072d119137325894fac19/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSG7HNgOhdhM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSG7HNgOhdhM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSG7HNgOhdhM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/870e217a1e5e09432f476b47ccc36bb3/href">https://medium.com/media/870e217a1e5e09432f476b47ccc36bb3/href</a></iframe><p>still making this one, hold tight</p><h3>fancy analytics and what I’ve learned</h3><p>this project grew much past beyond my expectations, here are some statistics that I gathered through BigQuery over the past year:</p><ul><li>7–15k daily distinct active users</li><li>10–30k voice channels generated daily</li><li>150k+ total guilds</li><li>300k-1M voice channels generated per month</li><li>7M voice channels generated last year</li><li>20M+ voice channels generated in total</li></ul><p>this project taught me most of the things I now know about coding, high school and university helped me with having strong fundamentals sure, but this project was key in learning how to apply them to real world scenarios and also discover a lot of key technologies that school does not prepare you for.</p><p>I won’t dive into the code in this article, because there would really be too much cool stuff to cover, but you can find a technical description of the current status on the GitHub repositories (link at the end of the article!).</p><p>and the best part, is that it taught me so much more than just coding!</p><ul><li>it taught me how to listen to customers, and how to handle support requests, this is the amount of messages I sent in the bot support guild to mainly help people out:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*HFO8xcrjewNTFqlAS-gfEQ.jpeg" /></figure><ul><li>how to grow my product, look at statistics, make partnerships and advertise it</li><li>how to balance free and paywalled features to keep the users happy while still being profitable</li><li>how to balance my time and, most importantly, that you will never <em>be done</em> with development. initially I was always saying, alright I just need to get this one feature out and then it’s completed, but the reality is that there is always room for improvement, and it’s very important that you become able to distinguish what is worth pursuing and improving and what is not.</li></ul><p>these days, I don’t really use Discord because I stopped gaming a while ago, and this took away the drive I had for this project for a long time.<br>I love creating and developing projects that I actually use, and unfortunately this is not the case anymore for Astro.<br>because of that, I decided to stop working on it and don’t plan on adding new features to it anymore, but that doesn’t mean that it’s going offline or anything, the bot will stay alive and serve your amazing guilds for (hopefully) as much as you need it!</p><p>additionally, I decided to open source all the code, in the hope that it can help other developers and be taken as an example or reference for ways to overcome certain technical challenges related to large-scale Discord bots development.</p><p>here are the links for the <a href="https://github.com/bot-astro/astro">backend</a> and the <a href="https://github.com/bot-astro/astro-bot.space">frontend</a> GitHub repositories of Astro :&gt;</p><ul><li><a href="https://github.com/bot-astro/astro">GitHub - bot-astro/astro: The most unique and complete discord bot for temporary voice channels and voice roles!</a></li><li><a href="https://github.com/bot-astro/astro-bot.space">GitHub - bot-astro/astro-bot.space: Website and dashboard for Astro, the Discord bot</a></li></ul><p>I wrote this article mainly for my future self, to remind me about all the challenges I encountered and the exciting times and lessons this project brought me, but I hope you get something meaningful out of it, and that it inspires you to create something yourself, whether it’s a Discord bot or anything else.</p><p>Happy crafting :P</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=094b6d000c21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing user authentication in a Ktor backend]]></title>
            <link>https://medium.com/@gpimenoff/implementing-user-authentication-in-a-ktor-backend-e96a6a2dcddb?source=rss-a79a9e871bc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e96a6a2dcddb</guid>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[user-authentication-api]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Giulio Pimenoff Verdolin]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 17:14:21 GMT</pubDate>
            <atom:updated>2024-11-16T12:55:35.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OR_RyGJG9WhsOlzJ4MxNXA.png" /></figure><p>One of the first challenges I ecountered when building <a href="https://index-it.app/">Index</a> was authentication. I saw lots of different services for it, but since I knew I was building a backend anyway, I choose to implement auth myself.</p><p>After all, it’s pretty simple, and in this article I’m sharing how I coded the following:</p><ul><li>auth session management</li><li>email and password registration</li><li>email verification</li><li>email and password login</li><li>password reset logic</li></ul><h3>Session management: cookies or JWT?</h3><p>After a lot of research, I decided to use cookies to manage the authentication status of my users. Specifically, I use http-only secure cookies and only store a session ID inside them.</p><p>This is the cookie format:</p><pre>@Serializable<br>data class UserSessionCookie(<br>    @Contextual val session_id: DtId&lt;UserAuthSessionData&gt;,<br>    @Contextual val user_id: DtId&lt;UserData&gt;,<br>) : Principal</pre><blockquote><em>where </em><em>DtId is an ID wrapper, it&#39;s a simple string under the hood</em></blockquote><p>The main advantage here is that it allows me to revoke specific sessions based on the criterias relevant to me, and it’s also extremely fast since I store the basic auth info needed on most API calls in Redis, with the session ID as the key. Here is what I store in Redis:</p><pre>@Serializable<br>data class UserAuthSessionData(<br>    @Contextual val id: DtId&lt;UserAuthSessionData&gt;,<br>    @Contextual val userId: DtId&lt;UserData&gt;,<br>    val iat: Long,<br>    val deviceName: String?,<br>    val ip: String,<br>) : Principal</pre><p>The id is the session_id of the cookie, and it&#39;s used as a Redis key in combination with the userId, as follows {userId}:{sessionId}. This is really important because it allows me to delete specific sessions (for example when the user logs out) or to also delete all the sessions of the user, by calling delete in Redis with {userId}:* as key, so &quot;wildcarding&quot; all specific session ids.</p><p>I do store the issued-at timestamp (iat), device name and ip because I plan to allow the user to see all the devices on which he is logged in, and to revoke specific logins.</p><p>Authentication and authorization is made through Ktor. I first needed to configure the Sessions plugin:</p><pre>install(Sessions) {<br>  cookie&lt;UserSessionCookie&gt;(&quot;user_session_id&quot;) {<br>    cookie.path = &quot;/&quot;<br>    cookie.maxAgeInSeconds = ApiConfig.sessionMaxAgeInSeconds<br>    cookie.secure = ApiConfig.cookieSecure<br>    cookie.httpOnly = true<br>    cookie.extensions[&quot;SameSite&quot;] = &quot;None&quot;<br><br>    serializer = KotlinxSessionSerializer(<br>      Json {<br>        serializersModule = IdKotlinXSerializationModule<br>      },<br>    )<br>  }<br>}</pre><blockquote><em>to be able to test locally I have an environment variable for the secure property of the cookie.</em></blockquote><p>Then I created an authentication method for it:</p><pre>session&lt;UserSessionCookie&gt;(AuthenticationMethods.USER_SESSION_AUTH) {<br>    validate { userSessionCookie -&gt;<br>        val session = userSessionDao.get(userSessionCookie.user_id, userSessionCookie.session_id)<br>        // If there is no session or if it has expired<br>        if (session == null || (DatetimeUtils.currentMillis() - session.iat) &gt;= (ApiConfig.sessionMaxAgeInSeconds * 1000)) {<br>            null<br>        } else {<br>            session<br>        }<br>    }<br>    challenge {<br>        call.respond(HttpStatusCode.Unauthorized)<br>    }<br>}</pre><p>Here the session returned is the UserAuthSessionData shown before. I made a simple extention function so we can always access it after the user has been authenticated:</p><pre>fun PipelineContext&lt;Unit, ApplicationCall&gt;.authSessionData(): UserAuthSessionData? = call.principal&lt;UserAuthSessionData&gt;()<br>fun PipelineContext&lt;Unit, ApplicationCall&gt;.authSessionDataOrThrow(): UserAuthSessionData = authSessionData() ?: throw AuthenticationException()</pre><p>Here as an example, the logout route is protected through authentication:</p><pre>fun Route.userRoutes() {<br>    authenticate(AuthenticationMethods.USER_SESSION_AUTH) {<br>        logoutRoutes()<br>    }<br>}<br><br>// where logoutRoutes is defined as<br>fun Route.logoutRoutes() {<br>    val userSessionDao by inject&lt;UserSessionDao&gt;()<br><br>    get&lt;LogoutRoute&gt; {<br>        val session = authSessionDataOrThrow()<br><br>        userSessionDao.delete(session.userId, session.id)<br><br>        call.sessions.clear&lt;UserSessionCookie&gt;()<br>        call.respond(HttpStatusCode.OK)<br>    }<br>}</pre><h3>User registration</h3><p>This is pretty straight forward:</p><ul><li>check if a user with that email already exists</li><li>validate password strength</li><li>create user</li><li>send email verification</li></ul><pre>post&lt;RegisterRoute&gt; {<br>    val signupData = call.receive&lt;RegistrationCredentials&gt;()<br><br>    val existingUser = userDao.getFromEmail(signupData.email)<br>    if(existingUser != null) {<br>        if (UserAuthUseCase.isIncompleteAccountOutdated(existingUser)) {<br>            userDao.delete(existingUser.id)<br>        } else {<br>            call.respond(HttpStatusCode.Forbidden)<br>            return@post<br>        }<br>    }<br><br>    val hashedPassword = passwordEncoder.encode(signupData.password)<br><br>    val user = UserData(<br>        id = newDtId(),<br>        email = signupData.email,<br>        passwordHash = hashedPassword,<br>        emailVerified = false,<br>        creationTimestamp = DatetimeUtils.currentMillis()<br>    )<br><br>    userDao.create(user)<br><br>    val emailSent = EmailVerificationUseCase.createAndSend(user)<br>    if (emailSent) {<br>        // User will need to verify its email<br>        call.respond(HttpStatusCode.OK)<br>    } else {<br>        call.respond(HttpStatusCode.Created)<br>    }<br>}</pre><p>The credentials are validate automatically thanks to our Ktor validation plugin, I use the following email and password regex with a check on the password length (must be between 8–100 chars range):</p><ul><li>email: \w+@\w+\.\w+</li><li>password: (?=.*[a-z])(?=.*[A-Z])(?=.*\d).*</li></ul><p>When checking if a user with that email already exists, me delete the existing user if he didn’t yet verify his email and more than 7 days are passed (this is done inside the isIncompleteAccountOutdated function).</p><p>The most important step here is <strong>password hashing</strong>. We do not wanna store to plain password in our database! We also mark the user email as not-verified so we are able to deny login attempts until it’s verified.</p><p>The passwordEncoder used here is the following:</p><pre>class PasswordEncoder {<br>    private val bcryptPasswordEncoder = BCryptPasswordEncoder()<br>    <br>    fun encode(password: String): String = bcryptPasswordEncoder.encode(password)<br>    <br>    fun matches(<br>        rawPassword: String,<br>        encodedPassword: String,<br>    ) = bcryptPasswordEncoder.matches(rawPassword, encodedPassword)<br>}</pre><p>where BCryptPasswordEncoder is from the <a href="https://mvnrepository.com/artifact/org.springframework.security/spring-security-crypto">Spring Security module</a>.</p><h3>Email verification</h3><p>I decided to use <a href="https://www.brevo.com/">Brevo</a> for this but there are many other transactional email services out there for you to choose. I wont go in details into the API calls needed to send emails via Brevo (which you can still see from the <a href="https://github.com/Giuliopime/do-too">source code on my GitHub</a>), I will instead show the logical flow for the email verification to work.</p><p>We first send an email containing a clickable link to our API with a token, something like https://api.index-it.app/verify-email?token={url_encoded_token}. We must also store that token to be able to perform verification when the user clicks that link, so we hash it and store it in the database, with a couple of other values:</p><pre>object EmailVerificationTable : IntIdTable() {<br>    val token = varchar(&quot;token&quot;, 100).uniqueIndex()<br>    val user = reference(<br>        name = &quot;id_user&quot;,<br>        foreign = UsersTable,<br>        onDelete = ReferenceOption.CASCADE,<br>    ).index()<br>    val created_at = timestamp(&quot;created_at&quot;)<br>    val expires_at = timestamp(&quot;expires_at&quot;)<br>}</pre><p>When the user clicks the link, our API gets called, and we get the token from the URL, hash it and get an entity from our database with that hashed token. Find the user with the id stored along the token, and mark its email as verified. You can see that I have some environment variables used to choose where to redirect the user when the verification is successful or not. This is needed to show a valid html page to the user after he clicks the link in the email (in Index I simply link to a specific page of the web-app that shows them a success / error screen).</p><pre>get&lt;VerifyEmailRoute&gt; { request -&gt;<br>    // here the token gets hashed by the dao<br>    val emailVerificationDto = emailVerificationDao.get(request.token)<br>        ?: return@get call.respondRedirect(BrevoConfig.emailVerificationErrorUrl)<br>    <br>    val userDto = userDao.get(emailVerificationDto.userId)<br>        ?: return@get call.respond(HttpStatusCode.BadRequest)<br><br>    // Check if user is already verified<br>    if (userDto.emailVerified) {<br>        return@get call.respondRedirect(BrevoConfig.emailVerificationSuccessUrl)<br>    }<br><br>    userDao.verifyEmail(userDto.id)<br><br>    emailVerificationDao.deleteAllOfUser(userDto.id)<br>    call.respondRedirect(BrevoConfig.emailVerificationSuccessUrl)<br>}</pre><p>I also have a couple other routes useful for my fronends, one to send a new verification email (which just repeats the process described previously) and another for checking whether the email has been verified. I will show their usage in a following frontend authentication article.</p><h3>User login</h3><p>Here is what my route looks like:</p><pre>post&lt;LoginRoute&gt; {<br>    val loginData = call.receive&lt;LoginCredentialsData&gt;()<br>    val user = userDao.getFromEmail(loginData.email)<br>        ?: throw AuthenticationException()<br><br>    if (!passwordEncoder.matches(loginData.password, user.passwordHash)) {<br>        throw AuthenticationException()<br>    }<br><br>    if (!user.emailVerified) {<br>        return@post call.respond(HttpStatusCode.MethodNotAllowed)<br>    }<br><br>    val userSessionId = userSessionDao.create(<br>        userId = user.id,<br>        device = call.request.userAgent(),<br>        ip = call.request.origin.remoteAddress<br>    )<br><br>    call.sessions.set(userSessionId)<br>    call.respond(user.getResponseDto())<br>}</pre><p>The user provides its email and password in the body of the request, and we get the user matching that email. We compare the hashed password stored in our database with the provided one, by hashing it too. We also make sure the user email has been verified before creating a session for it, which we send to him as a cookie (this is done by sessions.set() in Ktor).</p><h3>Password forgotten</h3><p>The password reset logic is really similar to the email verification, to initiate it the user requests a password reset via a simple API call.</p><p>We then create a token, as we did for the email verification, and send an email with instructions on how to reset the password. I’ve put a clickable link in the email that sends the user to my web-app along with the token. The web-app prompts the user for a new password, and sends it to the backend with the token it received from the email. The backend then simply checks the token, db checks it, and stores the new password for the user.</p><pre>fun Route.passwordOperationRoutes() {<br>    val userDao by inject&lt;UserDao&gt;()<br>    val userSessionDao by inject&lt;UserSessionDao&gt;()<br>    val passwordResetDao by inject&lt;PasswordResetDao&gt;()<br>    val passwordEncoder by inject&lt;PasswordEncoder&gt;()<br>    val brevoClient by inject&lt;BrevoClient&gt;()<br><br>    get&lt;PasswordForgottenRoute&gt; { request -&gt;<br>        val user = userDao.getFromEmail(request.email)<br>            ?: return@get call.respond(HttpStatusCode.NotFound)<br><br>        if (passwordResetDao.isUserRateLimited(user.id)) {<br>            return@get call.respond(HttpStatusCode.TooManyRequests)<br>        }<br><br>        val sentEmail = PasswordResetUseCase.createAndSend(user)<br>        if (sentEmail) {<br>            call.respond(HttpStatusCode.OK)<br>        } else {<br>            call.respond(HttpStatusCode.InternalServerError)<br>        }<br>    }<br><br>    post&lt;ResetPasswordRoute&gt; { request -&gt;<br>        val passwordResetDto = passwordResetDao.get(request.token)<br>            ?: return@post call.respond(HttpStatusCode.NotFound)<br><br>        val user = userDao.get(passwordResetDto.userId)<br>            ?: return@post call.respond(HttpStatusCode.NotFound)<br><br>        val newPassword = call.receive&lt;PasswordResetRequestBody&gt;().password<br>        val newPasswordHashed = passwordEncoder.encode(newPassword)<br>        <br>        // If the user email wasn&#39;t verified before, now it can be considered verified<br>        userDao.resetPassword(<br>            id = passwordResetDto.userId,<br>            newPasswordHashed = newPasswordHashed,<br>            verifyEmail = true<br>        )<br><br>        // Invalidate all other user active sessions<br>        userSessionDao.deleteAllOfUser(passwordResetDto.userId)<br><br>        brevoClient.sendPasswordResetSuccessEmail(user.email)<br><br>        call.respond(HttpStatusCode.OK)<br>    }<br>}</pre><p>A couple of side notes:</p><ul><li>when the user resets the password, we mark its email as verified as it’s assured the user did the whole process by opening the email.</li><li>we send an email indicating the password reset (good practice for security)</li><li>we invalidate all existing auth sessions of the user</li></ul><h3>Conclusions</h3><p>It’s for sure not simple and it takes a bunch of time to implement all of this yourself the first time you do it, but I think it’s extremely useful to know how to implement auth yourself without third-party services. Plus, when you do it once, it’s really simple to duplicate it on future projects.</p><p>I hope this article was useful to you, here is a link at the source code of all of this:</p><p><a href="https://github.com/Giuliopime/do-too">GitHub - Giuliopime/do-too: To-do app showcase I use for writing tech articles. Basically a dumpster of the hardest challenges I encountered in building Index :&gt;</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e96a6a2dcddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing environment variables in Kotlin with ease and type safety]]></title>
            <link>https://medium.com/@gpimenoff/managing-environment-variables-in-kotlin-with-ease-and-type-safety-dotoo-backend-42882a1371ff?source=rss-a79a9e871bc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/42882a1371ff</guid>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Giulio Pimenoff Verdolin]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 08:41:32 GMT</pubDate>
            <atom:updated>2024-11-11T19:11:56.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4fZE3W7W07cUO7-BG72Mw.png" /></figure><p>Environment variables are always needed when developing some sort of api. This is why I built my own small script to manage and retrieve them with ease, while also keeping type safety.</p><h4>Features</h4><p>✅ Configuration variables split across Kotlin objects<br>✅ Automatic type safety by defining your custom parser<br>✅ Support for optional and default values<br>✅ Template .env file generation based on Kotlin defined variables</p><h3>Adding dependencies</h3><ul><li><a href="https://github.com/cdimascio/dotenv-kotlin">dotenv kotlin</a></li><li><a href="https://github.com/ronmamo/reflections">reflections</a></li><li><a href="https://mvnrepository.com/artifact/io.ktor/ktor-utils-jvm">ktor-utils-jvm</a></li><li>[optional] A logger, I recommend <a href="https://github.com/oshai/kotlin-logging">KotlinLogging</a></li></ul><h3>Creating the required annotations</h3><p>We are gonna use reflections to detect the environment variables that need to be read.<br>To make life easier we are gonna create our own annotations for that.</p><p>The first one will be used to annotate the Kotlin objects that contain the variables, it accepts a prefix string which we’ll use later:</p><pre>@Target(AnnotationTarget.CLASS)<br>annotation class Configuration(<br>    val prefix: String,<br>)</pre><p>While the second is for the actual variables, it accepts a name and whether that variable can be considered optional:</p><pre>@Target(AnnotationTarget.PROPERTY)<br>annotation class ConfigurationProperty(<br>    val name: String,<br>    val optional: Boolean = false,<br>)</pre><p>Here are a couple of configuration objects that use those annotations:</p><pre>@Configuration(&quot;api&quot;)<br>object ApiConfig {<br>    @ConfigurationProperty(&quot;port&quot;)<br>    var port: Int = 8080<br><br>    @ConfigurationProperty(&quot;cookie.secure&quot;)<br>    var cookieSecure: Boolean = true<br><br>    @ConfigurationProperty(&quot;session.max.age.in.seconds&quot;)<br>    var sessionMaxAgeInSeconds: Long = 2592000 // 30 days by default<br><br>    @ConfigurationProperty(&quot;admin.key&quot;)<br>    lateinit var adminKey: String<br>}</pre><pre>@Configuration(&quot;application&quot;)<br>object ApplicationConfig {<br>    @ConfigurationProperty(&quot;log.level&quot;)<br>    var logLevel: Level = Level.INFO<br>}</pre><p>As you can see we can use Kotlin types directly and even assign default values to these properties. If you don’t wanna assign a default value you can also make it lateinit.</p><h3>Creating the environment reader</h3><p>We do need to read enviornment variables somehow. In my case I used the dotenv library mentioned in the dependencies, but the good part is that you are free to use anything else.<br>What’s important is that you provide a function that conforms to the required signature, which is the following:</p><pre>val configurationReader: (key: String, clazz: KClass&lt;*&gt;) -&gt; Any?</pre><p>The function we need to create receives a key for the env variable we are looking for and a KClass that indicates the type of the variables we are excepting.</p><p>Let’s fullfil this real quick, first lets create our dotenv instance, which by default looks for a .env file and fallsback to the System env vars:</p><pre>private val dotenv: Dotenv? =<br>    try {<br>        dotenv()<br>    } catch (_: DotenvException) {<br>        log.info { &quot;.env file not found, using System environment variables&quot; }<br>        null<br>    }</pre><p>Now the actual function:</p><pre>/**<br>  * Reads a value with the specified [key] from the environment, according to the [type]<br>  */<br>fun read(key: String, type: KClass&lt;*&gt;, ): Any? {<br>    val value: String? = dotenv?.get(key) ?: System.getenv(key)<br><br>    return try {<br>        when (type) {<br>            String::class -&gt; value<br>            Int::class -&gt; value?.toInt()<br>            Long::class -&gt; value?.toLong()<br>            Boolean::class -&gt; value?.toBoolean()<br>            Level::class -&gt; {<br>                try {<br>                    value?.uppercase()?.let { Level.valueOf(it) }<br>                } catch (_: IllegalArgumentException) {<br>                    throw IllegalArgumentException(<br>                        &quot;Tried to read a value of type &#39;Level&#39; for key &#39;$key&#39; but casting failed, value: $value&quot;,<br>                    )<br>                }<br>            }<br>            else -&gt; throw UnsupportedOperationException(<br>                &quot;Configuration reader required to read a value of type $type for key &#39;$key&#39; but no casting is implemented for that type&quot;,<br>            )<br>        }<br>    } catch (e: NumberFormatException) {<br>        log.error { &quot;Could not cast a value with key &#39;$key&#39; in configuration reader, see following exception&quot; }<br>        throw e<br>    }<br>}</pre><p>As you can see we read the value using dotenv and then parse it depending on the received type parameter!</p><h3>Creating the bridge to our Kotlin objects</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc97a85796492638a6f5a99bc31e4a88/href">https://medium.com/media/bc97a85796492638a6f5a99bc31e4a88/href</a></iframe><p>This class receives two parameters:</p><ul><li>the package that contains out Kotlin configuration objects</li><li>the function used to read values from the environment</li></ul><p>It then provides two functions:</p><ul><li>listConfigurations that gives back all the detected configuration variables and their info</li><li>initialize which actually reads values and loads them into our objects</li></ul><p>The code is commented so I’ll limit the explanation here but the bullet points regarding how it functions are:</p><ul><li>initialize the reflections library using the provided package name</li><li>read all classes (objects in our case) annotated with the Configuration annotation</li><li>validate the object</li><li>read all its properties and for each</li><li>filter only the ones annotated with ConfigurationProperty (warn in case it&#39;s missing)</li><li>throw if any is declared as immutable</li><li>create the key to pass to our reader function by combining the Configurationprefix value and the ConfigurationProperty name.</li><li>detect the KClass of the variable</li><li>pass the ball to our reader function and get back the read value, if that returns null we try to use the default value of the variable if existing</li><li>if we got a null value and the variable isn’t marked as nullable we throw or return depending on the optional property.</li><li>type check</li><li>set the value on the Kotlin object</li></ul><h3>Putting it together</h3><p>Where we start out application we simply need to put the following now:</p><pre>val configInitializer = ConfigurationManager(<br>    packageName = ConfigurationManager.DEFAULT_CONFIG_PACKAGE,<br>    configurationReader = ConfigurationReader::read<br>)<br><br>configInitializer.initialize()</pre><p>(ConfigurationReader is an object that contains my reader function)</p><p>We can now freely use our env variables like so:</p><pre>println(ApiConfig.port)</pre><p>✅ type safety<br>✅ auto completion<br>✅ globally accessible<br>✅ DX happiness</p><h3>Automatically generating our .env file</h3><p>Let’s take this one step further. We don’t wanna double our jobs and have to create both our Kotlin objects and .env file. Let’s generate the .env file automatically!</p><p>Here is a small script (you can put this in a separate module) that does this for us:</p><pre>/**<br> * Script that generates a template .env file based on the declared @Configuration objects<br> */<br>fun main() {<br>    val configs = ConfigurationManager(<br>        packageName = ConfigurationManager.DEFAULT_CONFIG_PACKAGE,<br>        configurationReader = ConfigurationReader::read<br>    ).listConfigurations()<br><br>    val folder = createScriptOutputsFolderIfNotExisting()<br>    val file = File(folder, &quot;.env.template&quot;)<br>    file.writeText(configs.joinToString(&quot;\n&quot;) { it.toString() } )<br>}</pre><p>If we run this we get the following .env.template file:</p><pre># Level<br>APPLICATION_LOG_LEVEL=INFO<br>API_ADMIN_KEY=<br># Boolean<br>API_COOKIE_SECURE=true<br># Int<br>API_PORT=8080<br># Long<br>API_SESSION_MAX_AGE_IN_SECONDS=2592000</pre><h3>Sources and mentions</h3><p>You can find a full sample <a href="https://github.com/Giuliopime/do-too/tree/main/do-too-api/src/main/kotlin/app/dotoo/config">in my repo</a>!</p><p><a href="https://github.com/Giuliopime/do-too/tree/main/do-too-api/src/main/kotlin/app/dotoo/config">do-too/do-too-api/src/main/kotlin/app/dotoo/config at main · Giuliopime/do-too</a></p><p>Feel free to also checkout the new Apple Pkl library which seems quite handy and powerful too <a href="https://pkl-lang.org/index.html">https://pkl-lang.org/index.html</a> ^^</p><p><em>Originally made for </em><a href="https://index-it.app/"><em>Index</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42882a1371ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My experience building a desktop menu bar app with Kotlin multiplatform]]></title>
            <link>https://medium.com/@gpimenoff/my-experience-building-a-desktop-menu-bar-app-with-kotlin-multiplatform-42dbb01dae3e?source=rss-a79a9e871bc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/42dbb01dae3e</guid>
            <category><![CDATA[desktop-app]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[pomodoro-timer]]></category>
            <dc:creator><![CDATA[Giulio Pimenoff Verdolin]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 12:14:47 GMT</pubDate>
            <atom:updated>2023-12-28T12:16:12.667Z</atom:updated>
            <content:encoded><![CDATA[<p>Not so much time ago, Jetbrains announced an interesting <a href="https://kotlinconf.com/contest/">contest for students</a>. The goal was to build a Kotlin multiplatform app and the winners would receive a trip to KotlinConf 2024!<br>I thought that was a fantastic opportunity so here is how my attempt at it went.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_N1hPB0nuWr2HHvbPA7Epg.png" /></figure><h3>The idea</h3><p>I was getting eye strain for coding too much late at night (I later found out I just needed glasses instead), so I looked up some desktop break timer apps and found that most of them were made in Electron, and since my laptop was pretty old I couldn’t afford having a whole Electron app running in the background all the time.</p><p>So here comes my idea: <strong>ZenBreak</strong>, a break timer app.<br>I basically wanted to create a similar app to <a href="https://breaktimer.app/">BreakTimer</a> but native, yet multiplatform!<br>The requirements were:</p><ul><li>having a settings window to edit the various settings, like frequency of the breaks, duration of them, the style of the break popup, etc…</li><li>having a popup window, that would show when the break starts</li></ul><h3><strong>The building process</strong></h3><p>I started off looking trough some examples and tutorials from the <a href="https://github.com/JetBrains/compose-multiplatform">Compose multiplatform</a> library, choose a template, opened AndroidStudio and started coding!<br>I created a shared-core module which would contain my shared logic of the app between all platforms. The most useful libraries that I used there were <a href="https://insert-koin.io/">koin</a> for DI and <a href="https://github.com/russhwolf/multiplatform-settings">multiplatform-settings</a> for storing user settings.</p><p>I initially thought I would be able to build everything with compose multiplatform and started working on the desktop app with that, but after playing around with window management I figured out it wasn’t powerful enough to make great looking popups on macOS.</p><p>So, I split the shared-core module into multiple ones:</p><ul><li>shared-core: shared logic of the app</li><li>shared-compose-core: shared foundations for the compose ui</li><li>shared-compose-settings: compose ui for managing the app settings</li><li>shared-compose-popup: compose ui for the break window that pops up when a break starts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkyYi_c2sGL44DYy97qgMg.png" /></figure><blockquote>I created those separate modules to make it future proof in case I wanted to build an Android app too</blockquote><p>The desktop app now worked perfectly fine, at the end it just consisted of a few dependencies in the Gradle files to make it work.<br>Here is how one of its windows looked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScpwNDejaEIQ_RPk8K8xIQ.png" /></figure><h4>Building the macOS app</h4><p>It was time for the trickier part, using the Kotlin shared-core module from a Swift project.</p><p>I played around with it by building everything locally and developed the ui for the macOS app. One repo that helped me a lot was <a href="https://github.com/ivoronin/TomatoBar">TomatoBar</a>, an open source pomodoro timer app for macOS only, since I had no experience with Swift before this, it really got me going faster when doing window managment logic.</p><p>The first issue I encountered was consuming kotlin state flows from swift, and after reading a bunch of articles from <a href="https://johnoreilly.dev/">John O’Reilly</a> (thank you for those!) I ended up using KMP-NativeCoroutines:</p><p><a href="https://github.com/rickclephas/KMP-NativeCoroutines">GitHub - rickclephas/KMP-NativeCoroutines: Library to use Kotlin Coroutines from Swift code in KMP apps</a></p><p>A thing I had to do unfortunately was to create swift bindings myself for the various settings of the app, since I didn’t find a more concise way to achieve settings binding for the ui</p><pre>private var message: Binding&lt;String&gt; { Binding(<br>    get: {<br>        viewModel.settings.breakMessage<br>    },<br>    set: { message in<br>        viewModel.setBreakMessage(message: message)<br>    }<br>)}</pre><p>Building the user interface with SwiftUI has really been a pleasure though and I finished it pretty quickly, here is what it looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AhkpYXBvkaQsuI2fUxtQg.png" /></figure><h3>CICD</h3><p>This was the hardest part of building the app, and it’s still incomplete.</p><p>The most important thing was being able to publish the shared-core module as a swift package, and I did so using <a href="https://github.com/touchlab/KMMBridge">KMMBridge</a>.<br>Basically I added the following in the build.gradle.kts file of the module after adding the dependency:</p><pre>addGithubPackagesRepository()<br><br>kmmbridge {<br>    frameworkName.set(&quot;ZenBreakCoreKit&quot;)<br>    spm()<br>    mavenPublishArtifacts()<br>}</pre><p>And then created a GitHub action that I could manually trigger to publish the Swift package on GitHub Packages:</p><pre>name: Release ZenBreakCoreKit<br><br>on: [workflow_dispatch]<br><br>jobs:<br>  call-kmmbridge-publish:<br>    permissions:<br>      contents: write<br>      packages: write<br>    uses: touchlab/KMMBridgeGithubWorkflow/.github/workflows/faktorybuildautoversion.yml@v1.0<br>    with:<br>      jvmVersion: 17<br>      versionBaseProperty: LIBRARY_VERSION</pre><p>Touchlab really made a great tool, and thanks to that it was really easy in XCode to import that published package into the project!</p><p>After that, I played around a lot, like… a lot, with fastlane to get a great publishing CICD for the desktop and macOS apps, but I couldn’t figure it out and didn’t have more time to spend on that, so that’s missing still!</p><h3>Publishing</h3><p>It was finally time to publish the app, for the mac app it was pretty easy, I bought the Apple Developer licence, got onto the dashboard, created the store page, uploaded the app and after a few days it was already available in the App Store!</p><p>For the desktop one, things were a little harder, as I wanted the app to be signed so that users didn’t get that annoying popup when installing telling them that the app was dangerous…<br>I found out that the Microsoft Store automatically signed your app and so I went with that, I’ve setup <a href="https://conveyor.hydraulic.dev/">Conveyor</a> which saved my life for packaging the app properly with a simple gradle dependency and a config file, and then hit upload on the Microsoft Store.</p><p>That took much more time and received many rejections, unexpected ones like not being able to publish the app in China ’cause my support link for the app was a <a href="https://discord.gg/MunKMgKAJp">Discord server</a>, which is banned in that country… yikes</p><p>But at the end the app got approved, wrote a <a href="https://zenbreak.app/">small website</a> using SvelteKit for the first time (let’s say I took some inspiration from the Jetbrains websites haha) did a few Reddit and X posts and… that was it!<br>I built my first multiplatform desktop menu bar app using Kotlin multiplatform, and it felt like a big achievement!</p><h3>Considerations</h3><p>It has been a bit though building the app with Kotlin multiplatform, not because of the tooling or libraries, but because of the documentation. Docs were basically missing and that made me spend a lot of time figuring things out by myself, attempt after attempt, and lets say that having a kotlin module <a href="https://x.com/giuliopime/status/1700636171263475904?s=20">taking 15 minutes to compile</a> to native didn’t really help xD but I blame my old laptop for that :/</p><p>I do love the modularity that kotlin offers though, being able to build exactly what you need in Kotlin and leaving the rest to native frameworks. That’s what makes Kotlin multiplatform shine to me!</p><p>If you are interested in the app you can find it on <a href="https://zenbreak.app/">zenbreak.app</a>, the repo is the following:</p><p><a href="https://github.com/Giuliopime/ZenBreak">GitHub - Giuliopime/ZenBreak: Your desktop oasis from screen fatigue. Reclaim your focus and well-being.</a></p><p>Unfortunately I wont be able to participate to the contest prize because Italy is excluded as a country :/<br>I hope that in a future contest this will not be the case anymore as I would have loved to meet other Kotlin fans from all around the world!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42dbb01dae3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bottom Navigation Bar with nested Scaffolds]]></title>
            <link>https://medium.com/@gpimenoff/bottom-navigation-bar-with-nested-scaffolds-e7db3a0a1656?source=rss-a79a9e871bc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7db3a0a1656</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Giulio Pimenoff Verdolin]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 15:40:15 GMT</pubDate>
            <atom:updated>2023-08-21T12:40:15.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFsEY1kYN3cvyrlrLAEQuA.png" /><figcaption>Navigation bar image from <a href="https://m3.material.io/components/navigation-bar/overview">https://m3.material.io/components/navigation-bar/overview</a></figcaption></figure><p>On the Android developer documentation there is a guide on <a href="https://developer.android.com/jetpack/compose/navigation#bottom-nav">how to integrate the bottom navigation bar into your app</a>, which uses a top level Scaffold and a NavHost as its content.</p><h4>The problem</h4><p>The issue I encountered with this setup is the fact that it’s hard to nest material 3 scaffolds in the NavHost as they might end up with weird paddings around the edges, especially when managing insets yourself with WindowCompat.setDecorFitsSystemWindows(window, false) in your activity.</p><p>Nesting scaffolds is often necessary when you need to add different top app bars or floation action buttons depending on the screen, and moving that conditional logic to the main scaffold often requires view models filled with ui properties that shouldn’t be there.</p><h4>My approach</h4><p>I’ve tried multiple solutions, and the one that worked best for me was to replace to top level Scaffold with a simple Column and add the NavHost and BottomAppBar to it!</p><p>Here is the code:</p><pre>@Composable<br>fun BottomAppBarScreen() {<br>    val navController = rememberNavController()<br>    val pages = listOf(BottomAppBarPage.Feed, BottomAppBarPage.Account, BottomAppBarPage.Settings)<br>    var selectedPage by remember { mutableStateOf(BottomAppBarPage.Account.route) }<br><br>    Column(<br>        verticalArrangement = Arrangement.Bottom,<br>        modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)<br>    ) {<br>        NavHost(<br>            navController = navController,<br>            startDestination = BottomAppBarPage.Account.route,<br>            modifier = Modifier.weight(1f)<br>        ) {<br>            composable(BottomAppBarPage.Feed.route) {<br>                Text(text = &quot;Feed&quot;)<br>            }<br><br>            composable(BottomAppBarPage.Account.route) {<br>                AccountPage()<br>            }<br><br>            composable(BottomAppBarPage.Settings.route) {<br>                Text(text = &quot;Settings&quot;)<br>            }<br>        }<br><br>        CustomBottomAppBar(<br>            pages = pages,<br>            selectedPage = selectedPage,<br>            onPageClicked = {<br>                selectedPage = it<br>                navController.navigate(it) {<br>                    popUpTo(navController.graph.findStartDestination().id) {<br>                        saveState = true<br>                    }<br>                    launchSingleTop = true<br>                    restoreState = true<br>                }<br>            }<br>        )<br>    }<br>}</pre><p>The BottomAppBarPage is a simple sealed class which code you can find <a href="https://github.com/Giuliopime/jetpack-demos/blob/main/app/src/main/java/dev/giuliopime/jetpackdemos/demos/bottomAppBar/BottomAppBarPage.kt">here</a>, while the CustomBottomAppBar code is <a href="https://github.com/Giuliopime/jetpack-demos/blob/main/app/src/main/java/dev/giuliopime/jetpackdemos/demos/bottomAppBar/CustomBottomAppBar.kt">here</a>.</p><p>Then, a possible page could look like this:</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun AccountPage() {<br>    Scaffold(<br>        topBar = {}, // a custom top app bar...<br>        floatingActionButton = {}, // a custom fab...<br>        // This removes the system navigation bar padding which we have already handled in the top level screen<br>        contentWindowInsets = ScaffoldDefaults.contentWindowInsets.exclude(NavigationBarDefaults.windowInsets)<br>    ) { paddingValues -&gt;  <br>        LazyColumn(<br>            modifier = Modifier.fillMaxWidth().padding(paddingValues),<br>            verticalArrangement = Arrangement.spacedBy(<br>                space = 4.dp<br>            )<br>        ) {<br>            items(50) {<br>                Text(text = &quot;Item $it&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>The trick here is <strong>telling the Scaffold to ignore the navigation bar window insets</strong>, these do not refer to the bottom app bar but to the system navigation bar.<br>If we don’t tell that to the Scaffold, it will think that we didn’t handle those insets and will add a bottom padding as high as the system navigation bar.</p><p>You can see that I preserved the default Scaffold insets and removed just the ones we don’t need, the navigation bar insets.</p><pre>contentWindowInsets = ScaffoldDefaults.contentWindowInsets.exclude(NavigationBarDefaults.windowInsets)</pre><h4>Demo &amp; code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*GgDRycvJ2xz4aUF8afH70g.gif" /></figure><p><a href="https://github.com/Giuliopime/jetpack-demos/tree/main">GitHub - Giuliopime/jetpack-demos: Jetpack Compose demos</a></p><h4>Bonus - animations</h4><p>After publishing this article I realised animations were missing, or didn’t work well with the default settings.</p><p>The NavHost now has animations support, so I changed each composable enter and exit animations to match its position in the Bottom Navigation Bar.</p><p>Here is the updated NavHost</p><pre>NavHost(<br>    navController = navController,<br>    startDestination = BottomAppBarPage.Account.route,<br>    modifier = Modifier.weight(1f)<br>) {<br>    composable(<br>        route = BottomAppBarPage.Feed.route,<br>        enterTransition = {<br>            slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Right)<br>        },<br>        exitTransition = {<br>            slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Left)<br>        }<br>    ) {<br>        Text(text = &quot;Feed&quot;)<br>    }<br><br>    composable(<br>        route = BottomAppBarPage.Account.route,<br>        enterTransition = {<br>            if (initialState.destination.route == BottomAppBarPage.Settings.route) {<br>                slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Right)<br>            } else {<br>                slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Left)<br>            }<br>        },<br>        exitTransition = {<br>            if (targetState.destination.route == BottomAppBarPage.Settings.route) {<br>                slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Left)<br>            } else {<br>                slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Right)<br>            }<br>        }<br>    ) {<br>        AccountPage()<br>    }<br><br>    composable(<br>        route = BottomAppBarPage.Settings.route,<br>        enterTransition = {<br>            slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Left)<br>        },<br>        exitTransition = {<br>            slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Right)<br>        }<br>    ) {<br>        Text(text = &quot;Settings&quot;)<br>    }<br>}</pre><p>Happy coding ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7db3a0a1656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose color picker with hex values]]></title>
            <link>https://medium.com/@gpimenoff/jetpack-compose-color-picker-with-hex-values-f1ca2f5e9087?source=rss-a79a9e871bc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1ca2f5e9087</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <dc:creator><![CDATA[Giulio Pimenoff Verdolin]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 22:36:35 GMT</pubDate>
            <atom:updated>2023-08-19T07:34:47.130Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAJm9aMmWkZtsZ_c8qn7mw.png" /></figure><p>A very common component needed for an app is a simple yet powerful color picker.</p><p>Android unfortunately doesn’t offer one out of the box and that’s why I made my own.<br>It’s implemented with a simple AlertDialog and it allows both some pre-made options and the input from the user via hex values.</p><blockquote>This obviously isn’t the most user friendly design, but it’s great for a user base of developers or designers.</blockquote><p>Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15c576efe315449d02e12496cf6aafa2/href">https://medium.com/media/15c576efe315449d02e12496cf6aafa2/href</a></iframe><p>The picker receives:</p><ul><li>an initial color to display</li><li>a list of colors (strings in the hex format) that renders and displays to the user</li><li>a function which will be called when a <strong>valid</strong> color gets choosen by the user</li></ul><p>It requires some utility functions too: some simple ones that transform strings to color objects and a trickier one, the Color.contrastColor() which, based on a given color, determines if a text placed above it should be White or Black.</p><p>Here is a demo of the picker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*G61AVLPtf-Gt5sDvCQqOCg.gif" /></figure><p>The full demo application code is available on my GitHub repo<br>(<a href="https://github.com/Giuliopime/jetpack-demos/blob/main/app/src/main/java/dev/giuliopime/jetpackdemos/demos/colorpicker/ColorPickerScreen.kt">link to the exact file</a>)</p><p><a href="https://github.com/Giuliopime/jetpack-demos/tree/main">GitHub - Giuliopime/jetpack-demos: Jetpack Compose demos</a></p><p>Peace ✌🏼</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1ca2f5e9087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ModalBottomSheet and the system navigation bar — Jetpack Compose]]></title>
            <link>https://medium.com/@gpimenoff/modalbottomsheet-and-the-system-navigation-bar-jetpack-compose-6e9bf58e8317?source=rss-a79a9e871bc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e9bf58e8317</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <category><![CDATA[material3]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Giulio Pimenoff Verdolin]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 22:03:42 GMT</pubDate>
            <atom:updated>2023-08-30T17:01:06.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>ModalBottomSheet and the system navigation bar — Jetpack Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k882HxrS6avtipLmUDAcyA.png" /></figure><p>The material 3 version of the ModalBottomSheet is quite simple to use in Jetpack Compose (<em>see </em><a href="https://developer.android.com/jetpack/compose/layouts/material#bottom-sheets"><em>this guide</em></a>), but the default version isn’t pixel perfect.<br>It might end up behind the system navigation bar or lag behind it when closing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Nbii915yFrwczbmjqcBZ8g.gif" /></figure><p>As you can see from this simple demo, the default sheet lags behind the navigation bar when closing, while our custom one feels a bit better.</p><h3>The fix</h3><p>First, make sure you tell compose that you are going to handle insets yourself, by adding this piece of code in your activity</p><pre>WindowCompat.setDecorFitsSystemWindows(window, false)</pre><p>Here is an example of a full activity for reference</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5293c1eb95d5ce1170b61fd9a26afbb6/href">https://medium.com/media/5293c1eb95d5ce1170b61fd9a26afbb6/href</a></iframe><p>Now we just need the the sheet to <strong>ignore the system navigation bar insets</strong>, we can do this by passing a WindowInsetsthat doesn’t take count of that, for example WindowInsets.displayCutout (<em>those probably aren’t the best WindowInsets to use but they get the job done for this demo</em>).</p><p>If you don’t do anything else, the sheet content will go behind the navigation bar, because it doesn’t take count of its insets, so we <strong>wrap the content in a </strong><strong>Column and apply the </strong><strong>Modifier.padding(bottom = bottomPadding) to it</strong>.</p><p>The bottomPaddingis calculated outside of the Column scope via WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() .</p><p>If we were to call this method inside the ModalBottomSheet we would not get a valid padding since those insets have already been consumed.</p><p>Here is the improved ModalBottomSheet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3786e7d63f0118da18a186e6eb085677/href">https://medium.com/media/3786e7d63f0118da18a186e6eb085677/href</a></iframe><p>You can find the full code for the demo in this article on my GitHub repo (<a href="https://github.com/Giuliopime/jetpack-demos/blob/main/app/src/main/java/dev/giuliopime/jetpackdemos/demos/bottomsheet/ModalBottomSheetScreen.kt">link to the exact file</a>)</p><p><a href="https://github.com/Giuliopime/jetpack-demos">GitHub - Giuliopime/jetpack-demos: Jetpack Compose demos</a></p><p>Hope this helped ^^</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e9bf58e8317" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>