|
| 1 | +package com.adamratzman.spotify.utils |
| 2 | + |
| 3 | +private fun String.add(type: String, length: Int = 22): String { |
| 4 | + val match = "^(?:$type:)?(.{$length})(?::.*)?$".toRegex().matchEntire(this) |
| 5 | + match?.groupValues?.get(1)?.also { |
| 6 | + return "$type:$it" |
| 7 | + } |
| 8 | + throw IllegalArgumentException("$this isn't convertible to $type uri") |
| 9 | +} |
| 10 | + |
| 11 | +private fun String.remove(type: String, length: Int = 22): String { |
| 12 | + val match = "^(?:$type:)?(.{$length})(?::.*)?$".toRegex().matchEntire(this) |
| 13 | + match?.groupValues?.get(1)?.also { |
| 14 | + return it |
| 15 | + } |
| 16 | + throw IllegalArgumentException("'$this' isn't convertible to '$type' id") |
| 17 | +} |
| 18 | + |
| 19 | + |
| 20 | +inline class AlbumURI(private val input: String) { |
| 21 | + val uri: String |
| 22 | + get() = input.add("spotify:album") |
| 23 | + val id: String |
| 24 | + get() = input.remove("spotify:album") |
| 25 | +} |
| 26 | + |
| 27 | +inline class ArtistURI(private val input: String) { |
| 28 | + val uri: String |
| 29 | + get() = input.add("spotify:artist") |
| 30 | + val id: String |
| 31 | + get() = input.remove("spotify:artist") |
| 32 | +} |
| 33 | + |
| 34 | +inline class TrackURI(private val input: String) { |
| 35 | + val uri: String |
| 36 | + get() = input.add("spotify:track") |
| 37 | + val id: String |
| 38 | + get() = input.remove("spotify:track") |
| 39 | +} |
| 40 | + |
| 41 | +inline class UserURI(private val input: String) { |
| 42 | + val uri: String |
| 43 | + get() = input.add("spotify:user", 25) |
| 44 | + val id: String |
| 45 | + get() = input.remove("spotify:user", 25) |
| 46 | + |
| 47 | + // inline is not supported as non-top-level-class |
| 48 | + inner /*inline*/ class PlaylistURI(private val input: String) { |
| 49 | + val uri: String |
| 50 | + get() = input.add("${this@UserURI.uri}:playlist") |
| 51 | + val id: String |
| 52 | + get() = input.remove("${this@UserURI.uri}:playlist") |
| 53 | + } |
| 54 | + |
| 55 | + companion object { |
| 56 | + @Suppress("FunctionName") // "static" constructor |
| 57 | + fun PlaylistURI(input: String): PlaylistURI { |
| 58 | + return UserURI(input).PlaylistURI(input).also { it.uri /*check format*/ } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments