| import com.squareup.kotlinpoet.FileSpec |
| 6 | import com.squareup.kotlinpoet.FunSpec |
| 7 | import com.squareup.kotlinpoet.KModifier |
| 8 | import com.squareup.kotlinpoet.TypeSpec |
| 9 | import org.gradle.api.DefaultTask |
| 10 | import org.gradle.api.tasks.InputDirectory |
| 11 | import org.gradle.api.tasks.Internal |
| 12 | import org.gradle.api.tasks.OutputDirectory |
| 13 | import org.gradle.api.tasks.TaskAction |
| 14 | import org.telegram.tlrpc.SchemeAllLayersParser |
| 15 | import org.telegram.tlrpc.SchemeCodeGen |
| 16 | import org.telegram.tlrpc.SchemeTlValidator |
| 17 | import org.telegram.tlrpc.models.RULES |
| 18 | import org.telegram.tlrpc.models.TlObjectWithLayer |
| 19 | import org.telegram.tlrpc.schema.TlSchemaJsonParser |
| 20 | import org.telegram.tlrpc.telegram.TelegramCodeParser |
| 21 | import org.telegram.tlrpc.telegram.TelegramTlClass |
| 22 | import java.io.File |
| 23 |
| 24 | abstract class GenerateSchemeTask : DefaultTask() { |
| 25 | companion object { |
| 26 | const val LAYER = 229; |
| 27 | } |
| 28 |
| 29 |
| 30 | @get:InputDirectory |
| 31 | var tlSourcesDir: File = File("") |
| 32 |
| 33 | @get:InputDirectory |
| 34 | var tlSourcesDirectDir: File = File("") |
| 35 |
| 36 | @get:InputDirectory |
| 37 | var resourcesDir: File = File("") |
| 38 |
| 39 | @get:OutputDirectory |
| 40 | var outputDir: File = File("") |
| 41 |
| 42 | @TaskAction |
| 43 | fun generate() { |
| 44 | println("🚀 GenerateSchemeTask started") |
| 45 | println(" rootDir: $tlSourcesDir") |
| 46 | println(" resourcesDir: $resourcesDir") |
| 47 | println(" outputDir: $outputDir") |
| 48 |
| 49 | outputDir.mkdirs() |
| 50 |
| 51 | val tlDirectory = File(tlSourcesDir, "tl/") |
| 52 | val tlrpcFile = File(tlSourcesDir, "TLRPC.java") |
| 53 | val smsjobsFile = File(tlSourcesDirectDir, "TL_smsjobs.java") |
| 54 |
| 55 | // === Парсинг === |
| 56 |
| 57 | val files = tlDirectory.walkTopDown() |
| 58 | .filter { it.isFile && it.extension == "java" } |
| 59 | .toMutableList() |
| 60 | .apply { |
| 61 | add(tlrpcFile) |
| 62 | add(smsjobsFile) |
| 63 | } |
| 64 |
| 65 | val telegramClasses = TelegramCodeParser.parse(files) |
| 66 | val tlSchemaFull = TlSchemaJsonParser.parse(resourcesDir, LAYER) |
| 67 | val tlSchemaFilter = tlSchemaFull.applyRules(RULES.rules) |
| 68 |
| 69 | val undefinedTelegramClasses = telegramClasses.groupedByConstructorAll.filterKeys { |
| 70 | it !in tlSchemaFull.magicsAll |
| 71 | }.values.flatten() |
| 72 |
| 73 | File(outputDir, "not_linked_classes.txt") |
| 74 | .writeText(undefinedTelegramClasses.map { it.toString() }.sorted().joinToString("\n")) |
| 75 |
| 76 | val totalHistory = tlSchemaFull.getAllConstructorsHistory() |
| 77 | val classesByUniqueIds = telegramClasses.groupedByConstructorUnique |
| 78 | val schema = SchemeAllLayersParser.parseAllLayers(resourcesDir) |
| 79 |
| 80 | val dep = RULES.rules.databaseTypes |
| 81 | val legacyConstrKeys = schema.schemes.map { s -> |
| 82 | val types = dep |
| 83 | .mapNotNull { s.dependenciesTransitive[it] } |
| 84 | .flatten() |
| 85 | .toSet() + dep |
| 86 | s.scheme.constructors2 |
| 87 | .filter { it.key.name.type in types } |
| 88 | .map { it.key } |
| 89 | }.flatten().toSet() |
| 90 |
| 91 | val legacyPaths = schema.schemes.map { s -> |
| 92 | val paths = dep.map { SchemeTlValidator.findShortestPaths(s.dependenciesDirect, it) } |
| 93 | paths.map { it.entries }.flatten().toSet() |
| 94 | .map { it.key to it.value } |
| 95 | .groupBy { it.first } |
| 96 | .mapValues { it.value.map { x -> x.second }.toSet().toList() } |
| 97 | } |
| 98 |
| 99 | val allNeededLegacyConstr = schema.constructorsLegacy2 |
| 100 | .filter { it.tl.key in legacyConstrKeys }.toSet() |
| 101 |
| 102 | val allConstructorsDefault = schema.constructorsActual2.toSet() + allNeededLegacyConstr |
| 103 | val allConstructorsDefaultKeys = allConstructorsDefault.map { it.tl.key }.toSet() |
| 104 | val encryptedConstructors = schema.encryptedConstructors |
| 105 | .filter { it.tl.key !in allConstructorsDefaultKeys } |
| 106 |
| 107 | val allConstructors = allConstructorsDefault + encryptedConstructors |
| 108 | val allMethods = (schema.methodsActual2 + schema.methodsLegacy2).toSet() |
| 109 |
| 110 | val constructorTypesMap = allConstructors.groupBy { it.tl.key.name.type } |
| 111 | val enumTypes = constructorTypesMap.filter { entry -> |
| 112 | entry.value.none { it.tl.params.list.isNotEmpty() } |
| 113 | } |
| 114 |
| 115 | val schemaIds = allConstructors.map { it.tl.key.constructorId } + |
| 116 | allMethods.map { it.tl.key.constructorId } |
| 117 | val schemaAllIds = schemaIds.toSet() |
| 118 | val schemaUniqueIds = schemaIds.groupingBy { it }.eachCount().filterValues { it == 1 }.keys |
| 119 | val constructorsByUniqueIds = allConstructors |
| 120 | .filter { it.tl.key.constructorId in schemaUniqueIds } |
| 121 | .associateBy { it.tl.key.constructorId } |
| 122 | val methodsByUniqueIds = allMethods |
| 123 | .filter { it.tl.key.constructorId in schemaUniqueIds } |
| 124 | .associateBy { it.tl.key.constructorId } |
| 125 |
| 126 | // === Линковка === |
| 127 |
| 128 | val linkedObjects = mutableSetOf<Pair<TlObjectWithLayer, TelegramTlClass>>() |
| 129 | linkObjectsByUniqueId(classesByUniqueIds, constructorsByUniqueIds, linkedObjects) |
| 130 |
| 131 | val linkedConstructors = linkedObjects.toSet() |
| 132 | linkObjectsByUniqueId(classesByUniqueIds, methodsByUniqueIds, linkedObjects) |
| 133 |
| 134 | val linkedTypes = mutableSetOf<Pair<String, TelegramTlClass>>() |
| 135 | linkTypesBySinglePredicate(classesByUniqueIds, constructorTypesMap, linkedTypes) |
| 136 | linkTypesByLinkedObjects(telegramClasses.classes, linkedConstructors, linkedTypes) |
| 137 |
| 138 | // === Генерация === |
| 139 |
| 140 | val typesForGen = allConstructors.map { it.tl.key.name.type }.toSet() + |
| 141 | schema.encryptedConstructors.map { it.tl.key.name.type } |
| 142 |
| 143 | for (type in typesForGen) { |
| 144 | if (type == "Vector t") continue |
| 145 | generateSchemeClassForType(type, constructorTypesMap[type]!!, encryptedConstructors.toList()) |
| 146 | } |
| 147 |
| 148 | generateSchemeTestClassForType( |
| 149 | allConstructors.toList(), |
| 150 | encryptedConstructors.toList(), |
| 151 | linkedTypes, |
| 152 | legacyPaths |
| 153 | ) |
| 154 | // println("✅ Generation complete. Output: $outputDir") |
| 155 | } |
| 156 |
| 157 |
| 158 | // ========================================================= |
| 159 | // Генерация — бывшие private fun в main.kt |
| 160 | // ========================================================= |
| 161 |
| 162 | private fun generateSchemeClassForType( |
| 163 | type: String, |
| 164 | constructors: List<TlObjectWithLayer>, |
| 165 | encrypted: List<TlObjectWithLayer> |
| 166 | ) { |
| 167 | val packageName = "org.telegram.tgnet.model.generated" |
| 168 | val x = constructors.groupBy { it.tl.key.name.type } |
| 169 | .filter { it.value.any { c -> c.layerLast == LAYER } }.keys |
| 170 |
| 171 | val sealedClassName = "TlGen_" + type.replace('.', '_') |
| 172 | val sealedClassBuilder = TypeSpec.classBuilder(sealedClassName) |
| 173 | .addModifiers(KModifier.SEALED) |
| 174 | .addSuperinterface(ClassName("org.telegram.tgnet.model", "TlGen_Object")) |
| 175 |
| 176 | for (constructor in constructors) { |
| 177 | var needSuper = true |
| 178 | if (constructor.layerLast != LAYER |
| 179 | && constructor !in encrypted |
| 180 | && constructor.tl.key.name.type in x |
| 181 | ) { |
| 182 | needSuper = false |
| 183 | } |
| 184 | if (!RULES.rules.filterConstructor(constructor.tl.key.name)) continue |
| 185 |
| 186 | sealedClassBuilder.addType( |
| 187 | SchemeCodeGen.generateDataClass( |
| 188 | constructor, |
| 189 | if (needSuper) ClassName(packageName, sealedClassName) else null |
| 190 | ) |
| 191 | ) |
| 192 | } |
| 193 |
| 194 | FileSpec.builder(packageName, sealedClassName) |
| 195 | .addImport("org.telegram.tgnet.model", "TlGen_Object", "TlGen_Vector") |
| 196 | .addType(sealedClassBuilder.build()) |
| 197 | .build() |
| 198 | .writeTo(outputDir) |
| 199 | } |
| 200 |
| 201 | private fun generateSchemeTestClassForType( |
| 202 | constructors: List<TlObjectWithLayer>, |
| 203 | encrypted: List<TlObjectWithLayer>, |
| 204 | linkedTypes: Set<Pair<String, TelegramTlClass>>, |
| 205 | comments: List<Map<String, List<List<String>>>> |
| 206 | ) { |
| 207 | val packageName = "org.telegram.tgnet.test.generated" |
| 208 |
| 209 | val runWithAnnotation = AnnotationSpec.builder( |
| 210 | ClassName("org.junit.runner", "RunWith") |
| 211 | ).addMember("%T::class", ClassName("org.junit.experimental.runners", "Enclosed")) |
| 212 | .build() |
| 213 |
| 214 | val testAllBuilder = TypeSpec.classBuilder("Test_All") |
| 215 | .addAnnotation(runWithAnnotation) |
| 216 | val testActualBuilder = TypeSpec.classBuilder("Test_Actual") |
| 217 | .superclass(ClassName("org.telegram.tgnet.test", "BaseSchemeTest")) |
| 218 | val testLegacyBuilder = TypeSpec.classBuilder("Test_Legacy") |
| 219 | .superclass(ClassName("org.telegram.tgnet.test", "BaseSchemeTest")) |
| 220 | val testEncryptedBuilder = TypeSpec.classBuilder("Test_Encrypred") |
| 221 | .superclass(ClassName("org.telegram.tgnet.test", "BaseSchemeTest")) |
| 222 |
| 223 | val lt = linkedTypes.groupBy { it.first }.mapValues { it.value.map { it.second } } |
| 224 |
| 225 | val constructorsSorted = constructors.sortedWith( |
| 226 | compareByDescending<TlObjectWithLayer> { it.layerLast } |
| 227 | .thenBy { it.tl.key.name.type } |
| 228 | .thenBy { it.tl.key.name.predicate }) |
| 229 |
| 230 | var testIndex = 0; |
| 231 |
| 232 | for (constructor in constructorsSorted) { |
| 233 | if (!RULES.rules.filterConstructor(constructor.tl.key.name)) continue |
| 234 |
| 235 | val isEncrypted = constructor in encrypted |
| 236 | val isLegacy = constructor.layerLast < LAYER |
| 237 | val type = constructor.tl.key.name.type.replace('.', '_') |
| 238 | val name = "test_${(testIndex++).toString().padStart(6, '0')}_${type}_${constructor.codegenDataClassName}" |
| 239 |
| 240 | val lines = lt[constructor.tl.key.name.type]?.map { clz -> |
| 241 | val clz2 = clz.packageName + "." + clz.fullName |
| 242 | "test_TLdeserialize(org.telegram.tgnet.model.generated.TlGen_${type}.${constructor.codegenDataClassName}::class, " + |
| 243 | "${clz2}::TLdeserialize, ${if (isLegacy && !isEncrypted) constructor.layerLast.toString() else "null"})" |
| 244 | } ?: listOf("assumeTrue(\"Test skipped, link error\", false)") |
| 245 |
| 246 | val code = buildString { lines.forEach { appendLine(it) } } |
| 247 |
| 248 | val b = when { |
| 249 | isEncrypted -> testEncryptedBuilder |
| 250 | isLegacy -> testLegacyBuilder |
| 251 | else -> testActualBuilder |
| 252 | } |
| 253 |
| 254 | val fs = FunSpec.builder(name) |
| 255 | .addAnnotation(ClassName("org.junit", "Test")) |
| 256 | .addModifiers(KModifier.PUBLIC) |
| 257 | .addStatement(code) |
| 258 |
| 259 | if (!isEncrypted && isLegacy) { |
| 260 | val l = comments[constructor.layerLast - 1][constructor.tl.key.name.type] ?: emptyList() |
| 261 | val comment = l.map { it.joinToString(separator = "-") }.joinToString(separator = "\n") |
| 262 | fs.addKdoc(comment) |
| 263 | } |
| 264 |
| 265 | b.addFunction(fs.build()) |
| 266 | } |
| 267 |
| 268 | FileSpec.builder(packageName, "Test_All") |
| 269 | .addImport("org.telegram.tgnet.model", "TlGen_Object", "TlGen_Vector") |
| 270 | .addImport("org.junit.Assume", "assumeTrue") |
| 271 | .addType( |
| 272 | testAllBuilder |
| 273 | .addType(testActualBuilder.build()) |
| 274 | .addType(testEncryptedBuilder.build()) |
| 275 | .addType(testLegacyBuilder.build()) |
| 276 | .build() |
| 277 | ) |
| 278 | .build() |
| 279 | .writeTo(outputDir) |
| 280 | } |
| 281 |
| 282 | // ========================================================= |
| 283 | // Линковка — бывшие private fun в main.kt |
| 284 | // ========================================================= |
| 285 |
| 286 | private fun linkObjectsByUniqueId( |
| 287 | classesByUniqueIds: Map<UInt, TelegramTlClass>, |
| 288 | objectsByUniqueIds: Map<UInt, TlObjectWithLayer>, |
| 289 | output: MutableSet<Pair<TlObjectWithLayer, TelegramTlClass>> |
| 290 | ) { |
| 291 | for (entry in objectsByUniqueIds) { |
| 292 | val clazz = classesByUniqueIds[entry.value.tl.key.constructorId] ?: continue |
| 293 | output.add(entry.value to clazz) |
| 294 | } |
| 295 | } |
| 296 |
| 297 | private fun linkTypesBySinglePredicate( |
| 298 | classesByUniqueIds: Map<UInt, TelegramTlClass>, |
| 299 | predicatesByType: Map<String, List<TlObjectWithLayer>>, |
| 300 | output: MutableSet<Pair<String, TelegramTlClass>> |
| 301 | ) { |
| 302 | for (constructor in predicatesByType.filterValues { it.size == 1 }.values.flatten()) { |
| 303 | val clazz = classesByUniqueIds[constructor.tl.key.constructorId] ?: continue |
| 304 | if (!clazz.canStaticDeserialize) continue |
| 305 | output.add(constructor.tl.key.name.type to clazz) |
| 306 | } |
| 307 | } |
| 308 |
| 309 | private fun linkTypesByLinkedObjects( |
| 310 | classes: Set<TelegramTlClass>, |
| 311 | linkedObjects: Set<Pair<TlObjectWithLayer, TelegramTlClass>>, |
| 312 | output: MutableSet<Pair<String, TelegramTlClass>> |
| 313 | ) { |
| 314 | val linkedClassesMap = linkedObjects |
| 315 | .map { it.second to it.first } |
| 316 | .groupBy { it.first } |
| 317 | .mapValues { it.value.map { x -> x.second } } |
| 318 |
| 319 | classes.filter { it.canStaticDeserialize && it.staticDeserializeCreations.isNotEmpty() } |
| 320 | .forEach { clazz -> |
| 321 | val candidates = clazz.staticDeserializeCreations |
| 322 | .map { name -> classes.filter { it.name == name || it.fullName == name } } |
| 323 | .flatten().toSet() |
| 324 | val linkedCandidates = candidates |
| 325 | .mapNotNull { linkedClassesMap[it] }.flatten() |
| 326 | .map { it.tl.key.name.type } |
| 327 | val linkedCandidatesSet = linkedCandidates.toSet() |
| 328 |
| 329 | when { |
| 330 | clazz.name in linkedCandidatesSet -> |
| 331 | output.add(clazz.name to clazz) |
| 332 | linkedCandidatesSet.size == 1 -> |
| 333 | output.add(linkedCandidatesSet.first() to clazz) |
| 334 | linkedCandidatesSet.isNotEmpty() -> { |
| 335 | println("Warning: multiple candidates for ${clazz.name}") |
| 336 | mostFrequentStringOrNull(linkedCandidates)?.let { |
| 337 | output.add(it to clazz) |
| 338 | } |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 |
| 344 | private fun mostFrequentStringOrNull(input: List<String>): String? { |
| 345 | val counts = input.groupingBy { it }.eachCount() |
| 346 | val maxCount = counts.values.maxOrNull() ?: return null |
| 347 | val top = counts.filterValues { it == maxCount } |
| 348 | return if (top.size == 1) top.keys.first() else null |
| 349 | } |
| 350 | } |