-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtasks.kt
2291 lines (1967 loc) · 67.4 KB
/
tasks.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package myaa.subkt.tasks
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.JsonParser
import com.jcraft.jsch.*
import com.turn.ttorrent.common.TorrentSerializer
import com.turn.ttorrent.common.creation.MetadataBuilder
import io.ktor.client.HttpClient
import io.ktor.client.call.receive
import io.ktor.client.features.auth.Auth
import io.ktor.client.features.auth.providers.basic
import io.ktor.client.features.json.GsonSerializer
import io.ktor.client.features.json.JsonFeature
import io.ktor.client.request.forms.*
import io.ktor.client.request.request
import io.ktor.client.statement.HttpResponse
import io.ktor.content.ByteArrayContent
import io.ktor.content.TextContent
import io.ktor.http.*
import io.ktor.utils.io.core.writeFully
import kotlinx.coroutines.runBlocking
import myaa.subkt.ass.assTime
import myaa.subkt.tasks.PropertyTask.TaskProperty
import org.apache.commons.net.ftp.FTPClient
import org.apache.commons.net.ftp.FTPSClient
import org.apache.commons.net.io.CopyStreamAdapter
import org.apache.commons.net.util.TrustManagerUtils
import org.apache.velocity.context.AbstractContext
import org.gradle.api.DefaultTask
import org.gradle.api.Task
import org.gradle.api.file.*
import org.gradle.api.internal.file.copy.CopyAction
import org.gradle.api.internal.file.copy.CopySpecInternal
import org.gradle.api.internal.provider.DefaultProvider
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.HasMultipleValues
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.*
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.bundling.AbstractArchiveTask
import org.gradle.api.tasks.bundling.Zip
import org.gradle.internal.logging.progress.ProgressLoggerFactory
import org.gradle.kotlin.dsl.*
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.OutputStream
import java.lang.reflect.Method
import java.net.Socket
import java.time.Duration
import java.util.*
import javax.inject.Inject
import javax.net.ssl.SSLSocket
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.full.declaredMemberProperties
/**
* Context for defining groups of objects such as tasks.
*
* Provides convenience functions for defining tasks and other objects
* for all entries associated with this context.
*/
abstract class ItemGroupContext {
/**
* The [Subs] instance all tasks created in this context should be associated with.
*/
protected abstract val subs: Subs
/**
* A list of entries (episodes or batches) this context should generate tasks for.
*/
protected abstract val entries: Provider<out Iterable<String>>
/**
* True if [entry] corresponds to a batch entry.
*/
protected abstract fun isBatch(entry: String): Boolean
/**
* The episodes associated with [entry].
*/
protected abstract fun episodes(entry: String): List<String>
/**
* Create and/or configure tasks of type [T] for all entries in [entries].
*
* @param action A closure operating on a [Task]. Called once for
* each entry in the current context.
*/
operator fun <T : Task> TaskGroup<T>.invoke(action: T.() -> Unit) {
entries.get().forEach { entry ->
this.registerItemMaybe(entry, isBatch(entry), episodes(entry)).configure(action)
}
}
/**
* The map to store [TaskGroup] objects created in this context.
*/
protected abstract val taskGroups: MutableMap<String, TaskGroup<*>>
/**
* Create a new task group, or returns the task group with the given name if it already exists.
*
* @sample myaa.subkt.tasks.samples.itemGroupContextTaskSample1
* @param name The name of the task group.
* @param klass The type of task associated with the task group.
*/
fun <T : Task> task(name: String, klass: KClass<T>) =
taskGroups.computeIfAbsent(name) { TaskGroup(name, subs, klass) } as TaskGroup<T>
/**
* Creates a new task group, or returns the task group with the given name if it already exists,
* and configures a task for each entry in the current context using the given closure.
*
* @sample myaa.subkt.tasks.samples.itemGroupContextTaskSample2
* @param name The name of the task group.
* @param klass The type of task associated with the task group.
* @param action A closure operating on a [Task]. Called once for
* each entry in the current context.
*/
fun <T : Task> task(name: String, klass: KClass<T>, action: T.() -> Unit) =
task(name, klass).also { it.invoke(action) }
/**
* Creates a new task group, or returns the task group with the given name if it already exists.
*
* @sample myaa.subkt.tasks.samples.itemGroupContextTaskSample3
* @param name The name of the task group.
* @param T The type of task associated with the task group.
*/
inline fun <reified T : Task> task(name: String) = task(name, T::class)
/**
* Creates a new task group, or returns the task group with the given name if it already exists,
* and configures a task for each entry in the current context using the given closure.
*
* @sample myaa.subkt.tasks.samples.itemGroupContextTaskSample4
* @param name The name of the task group.
* @param T The type of task associated with the task group.
* @param action A closure operating on a [Task]. Called once for
* each entry in the current context.
*/
inline fun <reified T : Task> task(name: String, noinline action: T.() -> Unit) =
task(name, T::class, action)
/**
* Returns a delegate that when accessed returns a task group with the same name
* as the property it is bound to. Optionally configures one task for each entry
* in the current context using the given closure.
*
* @sample myaa.subkt.tasks.samples.itemGroupContextTaskDelegateSample
* @param T The type of task associated with the task group.
* @param action A closure operating on a [Task]. Called once for
* each entry in the current context.
*/
inline fun <reified T : Task> task(noinline action: (T.() -> Unit)? = null) =
TaskCreator(this, T::class, action)
/**
* Creates a new task group with the name given by the string the function is invoked on,
* or returns the task group with the given name if it already exists,
* and configures a task for each entry in the current context using the given closure.
*
* @sample myaa.subkt.tasks.samples.itemGroupContextStringTaskSample
* @param T The type of task associated with the task group.
* @param action A closure operating on a [Task]. Called once for
* each entry in the current context.
*/
inline operator fun <reified T : Task> String.invoke(noinline action: T.() -> Unit) =
task(this, T::class, action)
/**
* Returns a delegate that when accessed returns a task group with the same name
* as the property it is bound to. Also configures one task for each entry
* in the current context using the given closure.
*
* @sample myaa.subkt.tasks.samples.itemGroupContextTaskClassDelegateSample
* @param T The type of task associated with the task group.
* @param action A closure operating on a [Task]. Called once for
* each entry in the current context.
*/
operator fun <T : Task> KClass<T>.invoke(action: T.() -> Unit) =
TaskCreator(this@ItemGroupContext, this, action)
/**
* Creates a [ValueGroup], evaluating the given closure immediately for each entry
* in the given context.
*
* @param T The type of the item contained in the [ValueGroup].
* @param action A closure operating on a [ValueClosure]. Called once for
* each entry in the current context.
*/
fun <T> value(action: ValueClosure<*>.() -> T) =
ValueGroup(subs, action).also { group ->
entries.get().forEach {
group.registerItemMaybe(it, isBatch(it), episodes(it))
}
}
/**
* Creates a [ProviderGroup] that evaluates the given closure lazily, returning a
* [Provider] when an item is requested for a given entry.
* The closure is evaluated by running [Provider.get] on the returned provider.
*
* @param T The type of the item contained in the [ProviderGroup].
* @param action A closure operating on a [ValueClosure].
*/
fun <T> provider(action: ValueClosure<*>.() -> T) =
ProviderGroup(subs, action).also { group ->
entries.get().forEach {
group.registerItemMaybe(it, isBatch(it), episodes(it))
}
}
}
/**
* Delegate for creation of tasks using property delegate syntax.
* See [ItemGroupContext.task].
*/
class TaskCreator<T : Task>(
/**
* The context this delegate belongs to.
*/
val context: ItemGroupContext,
/**
* The type of the task to create.
*/
val klass: KClass<T>,
/**
* An optional closure for configuring the task.
*/
val initAction: (T.() -> Unit)? = null
) {
/**
* Delegate which always returns the constant [item].
*/
class WrapperDelegate<T>(val item: T) {
operator fun getValue(receiver: Any?, property: KProperty<*>) = item
}
operator fun provideDelegate(receiver: Any?, prop: KProperty<*>):
WrapperDelegate<TaskGroup<T>> {
val taskGroup = context.task(prop.name, klass)
if (initAction != null) {
with(context) {
taskGroup(initAction)
}
}
return WrapperDelegate(taskGroup)
}
}
/**
* A group of items of type [T]. Has convenience functions
* for getting all items belonging to the same entry as a certain task,
* or all items corresponding to a specified list of entries.
*/
abstract class ItemGroup<T>(
/**
* The [Subs] instance this [ItemGroup] is associated with.
*/
val subs: Subs
) {
private val items = mutableMapOf<String, T>()
/**
* Get all items corresponding to the specified entries.
*
* @param entries A list of entries to get the items for.
* @sample myaa.subkt.tasks.samples.itemGroupItemsSample1
*/
fun batchItems(entries: Iterable<String>) = entries.map { items.getValue(it) }
/**
* Get all items corresponding to the specified entries.
*
* @param entries A provider for a list of entries to get the items for.
* @sample myaa.subkt.tasks.samples.itemGroupItemsSample1
*/
fun batchItems(entries: Provider<out Iterable<String>>) =
entries.get().map(::item)
/**
* Get all items corresponding to the episodes of the given task.
*
* @sample myaa.subkt.tasks.samples.itemGroupItemsSample2
*/
fun batchItems(task: Task) = batchItems(task.episodes)
/**
* Get the item corresponding to the specified entry.
*
* @sample myaa.subkt.tasks.samples.itemGroupItemSample1
*/
fun item(entry: String) = items[entry]
?: error("Attempted to access entry $entry of $this but no such entry existed; " +
"available entries: ${items.keys.sorted().joinToString(", ")}")
/**
* Get the item of the same the entry as the given task.
*
* @sample myaa.subkt.tasks.samples.itemGroupItemSample2
*/
fun item(task: Task) = item(task.entry)
/**
* Register a new item or return the item if it already exists.
*/
fun registerItemMaybe(entry: String, isBatch: Boolean, episodes: List<String>) =
items.computeIfAbsent(entry) { createItem(entry, isBatch, episodes) }
/**
* Returns a new item of type [T].
*/
protected abstract fun createItem(entry: String, isBatch: Boolean, episodes: List<String>): T
}
/**
* A group of tasks of the same type.
*/
class TaskGroup<T : Task>(
/**
* The name of this task group.
*/
val name: String,
subs: Subs,
/**
* The class object of the task type for this group.
*/
val klass: KClass<T>
) : ItemGroup<TaskProvider<T>>(subs) {
/**
* Registers a new task for the given entry, or returns an existing task if it exists.
* The returned task will following the naming scheme [name].[entry].
*
* @param entry The entry for this task, i.e. the episode or the batch identifier.
* @param isBatch True if this corresponds to a batch task.
* @param episodes The episodes that correspond to this entry. Usually a single-element
* list containing [entry] if [isBatch] is false.
*/
override fun createItem(entry: String, isBatch: Boolean, episodes: List<String>):
TaskProvider<T> {
val taskName = "$name.$entry.${subs.release.get()}"
val newTask = subs.project.tasks.register(taskName, klass.java)
newTask.configure {
it.extra["taskGroup"] = this
it.extra["isBatch"] = isBatch
it.extra["episodes"] = episodes
it.extra["release"] = subs.release.get()
it.extra["entry"] = entry
it.extra["currentTask"] = name
if (isBatch) {
it.extra["batch"] = entry
} else {
it.extra["episode"] = entry
}
}
return newTask
}
override fun toString() = "task group '$name'"
}
/**
* True if this task is a batch task.
*/
val Task.isBatch
get() = extra["isBatch"] as Boolean
/**
* The same as [entry] if this is an episode task; error otherwise.
*/
val Task.episode
get() = extra["episode"] as String
/**
* The same as [entry] if this is a batch task; error otherwise.
*/
val Task.batch
get() = extra["batch"] as String
/**
* The entry (batch or episode) this task corresponds to.
*/
val Task.entry
get() = extra["entry"] as String
/**
* The release this task was generated for.
*/
val Task.release
get() = extra["release"] as String
/**
* The name of this task.
*/
val Task.currentTask
get() = extra["currentTask"] as String
/**
* The episodes this task corresponds to. A single-item list containing
* [episode] if this is an episode task; a list of the episodes for
* the batch given by [batch] otherwise.
*/
val Task.episodes
get() = extra["episodes"] as List<String>
/**
* The [TaskGroup] instance this task belongs to.
*/
val <T : Task> T.taskGroup
get() = extra["taskGroup"] as TaskGroup<T>
class ValueClosure<T>(
/**
* The entry this value corresponds to.
*/
val entry: String,
/**
* Whether this entry is a batch entry.
*/
val isBatch: Boolean,
/**
* The episodes corresponding to this entry.
*/
val episodes: List<String>,
/**
* The item group this value belongs to.
*/
val taskGroup: ItemGroup<T>
) {
/**
* The current release.
*/
val release = taskGroup.subs.release.get()
/**
* Alias of [entry].
*/
val batch = entry
/**
* Alias of [entry].
*/
val episode = entry
/**
* Gets the items from the given item group that correspond to [episodes].
*/
fun <U> ItemGroup<U>.batchItems() = batchItems(episodes)
/**
* Gets the item from the given item group that corresponds to [entry].
*/
fun <U> ItemGroup<U>.item() = item(entry)
/**
* [AbstractContext] implementation for getting properties in a [ValueClosure] context.
*
* Will look for variables in the following places:
* 1. The properties of the associated [ValueClosure]
* 2. The loaded [SubProperties] properties, searched using the current entry and release
* 3. All tasks in the current project
*/
inner class ClosureContext : BaseContext() {
private fun findProp(name: String) =
this@ValueClosure::class.declaredMemberProperties
.find { it.name == name }?.getter?.call(this@ValueClosure)
override fun doGet(key: String) =
findProp(key) ?:
try { taskGroup.subs.get(key, entry = entry, context = this).orNull }
catch (e: NoSuchElementException) { null } ?:
taskGroup.subs.project.tasks.findByName(
"$key.$entry.${taskGroup.subs.release.get()}")
}
/**
* Evaluates a string. See [Task.evaluateTemplate].
*/
fun evaluateTemplate(expression: String) =
taskGroup.subs.evaluateTemplate(expression, entry = entry, context = ClosureContext())
/**
* Evaluates a string. See [Task.evaluate].
*/
fun evaluate(expression: String) =
taskGroup.subs.evaluate(expression, entry = entry, context = ClosureContext())
/**
* Searches for the given property. Can return null. See [Task.getRawMaybe].
*/
fun getRawMaybe(propertyName: String) =
taskGroup.subs.getRawMaybe(propertyName, entry = entry)
/**
* Returns true if the given property exists. See [Task.propertyExists].
*/
fun propertyExists(propertyName: String) =
taskGroup.subs.propertyExists(propertyName, entry = entry)
/**
* Searches for the given property. See [Task.getRaw].
*/
fun getRaw(propertyName: String) =
taskGroup.subs.getRaw(propertyName, entry = entry)
/**
* Searches for the given property and returns it as a list. See [Task.getList].
*/
fun getList(propertyName: String) =
taskGroup.subs.getList(propertyName, entry = entry, context = ClosureContext())
/**
* Searches for the given property and returns it as a list of the given type.
* See [Task.getListAs].
*/
inline fun <reified T> getListAs(propertyName: String) =
taskGroup.subs.getListAs<T>(propertyName, entry = entry, context = ClosureContext())
/**
* Searches for the given property and returns it as a single element. See [Task.get].
*/
fun get(propertyName: String) =
taskGroup.subs.get(propertyName, entry = entry, context = ClosureContext())
/**
* Searches for the given property and returns it as a single element of the given type.
* See [Task.getAs].
*/
inline fun <reified T> getAs(propertyName: String) =
taskGroup.subs.getAs<T>(propertyName, entry = entry, context = ClosureContext())
/**
* Processes the given file. See [Task.getFile].
*/
fun getFile(filename: String) =
taskGroup.subs.getFile(filename, entry = entry, context = ClosureContext())
/**
* Processes the given file. See [Task.getFile].
*/
fun getFile(filename: Provider<String>) =
taskGroup.subs.getFile(filename, entry = entry, context = ClosureContext())
}
/**
* [ItemGroup] that keeps track of simple values of type [T].
* The closure is evaluated immediately for each entry.
*/
class ValueGroup<T>(subs: Subs, val action: ValueClosure<T>.() -> T) :
ItemGroup<T>(subs) {
override fun createItem(entry: String, isBatch: Boolean, episodes: List<String>): T =
ValueClosure(entry, isBatch, episodes, this).action()
}
/**
* [ItemGroup] that keeps track of providers for values of type [T].
* A [Provider] is generated for each entry, and the given closure
* is evaluated when the provider's value is requested.
*/
class ProviderGroup<T>(subs: Subs, val action: ValueClosure<*>.() -> T) :
ItemGroup<Provider<T>>(subs) {
override fun createItem(entry: String, isBatch: Boolean, episodes: List<String>): Provider<T> =
subs.project.provider {
ValueClosure(entry, isBatch, episodes, this).action()
}
}
/**
* Returns a [Property] with a default value set.
*/
inline fun <reified T> Task.defaultProperty(default: T): Property<T> =
project.objects.property<T>().convention(default)
/**
* Returns a [ConfigurableFileCollection] containing a single file `taskName.extension`
* located in the build directory.
*/
fun Task.outputFile(extension: String): ConfigurableFileCollection =
project.objects.fileCollection()
.from(project.layout.buildDirectory.file("$name.$extension"))
/**
* Mixin task interface providing convenience functions for accessing [ItemGroup] instances.
*/
interface SubTask : Task {
/**
* Gets the items from the given item group that correspond to [episodes].
*/
fun <T> ItemGroup<T>.batchItems() = batchItems([email protected])
/**
* Gets the item from the given item group that corresponds to [entry].
*/
fun <T> ItemGroup<T>.item() = item([email protected])
}
/**
* Parent task type that automatically keeps track of and stores
* properties in JSON format.
*
* Make use of by declaring a delegated property which delegates to
* a [TaskProperty] instance.
*/
abstract class PropertyTask : DefaultTask(), SubTask {
@get:Internal
protected val propertyFile: File =
project.layout.buildDirectory.file("$name.cache.json").get().asFile
private val properties = try {
Gson().fromJson(propertyFile.reader(), MutableMap::class.java)
as MutableMap<String, Any>?
} catch (e: FileNotFoundException) { null } ?: mutableMapOf()
/**
* Delegate for reading properties from a JSON file associated with this task.
*/
inner class TaskProperty<T : Any>(val default: () -> T) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return properties.computeIfAbsent(property.name) { default() } as T
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
properties[property.name] = value
}
}
protected abstract fun run()
private fun writeProperties() {
propertyFile.parentFile.mkdirs()
propertyFile.writer().use {
Gson().toJson(properties, it)
}
}
@TaskAction
protected fun doTask() {
run()
writeProperties()
}
}
/**
* Task to create a torrent file from a set of files.
* A predefined task instance can be accessed through [Subs.torrent].
*
* Note that if more than one file is added to the torrent,
* a root directory must be specified using the [into] function.
*
* @sample myaa.subkt.tasks.samples.torrentSample
*/
open class Torrent : AbstractArchiveTask(), SubTask {
/**
* A list of trackers to add to the torrent.
*/
@get:Input
val trackers = project.objects.listProperty<String>().convention(listOf())
/**
* If true, mark torrent as private. Optional.
*/
@get:Input
@get:Optional
val private = project.objects.property<Boolean>()
/**
* String identifying the program that created the torrent. Optional.
*/
@get:Input
@get:Optional
val createdBy = project.objects.property<String>()
/**
* Comment to add to the torrent file. Optional.
*/
@get:Input
@get:Optional
val comment = project.objects.property<String>()
/**
* Manually specified piece length. Optional.
*/
@get:Input
@get:Optional
val pieceLength = project.objects.property<Int>()
/**
* The location to save the torrent file.
* Defaults to an automatically generated file in the build directory.
*/
@get:Internal
val out = outputFile("torrent")
init {
val f = out.elements.map { it.single().asFile }
archiveFileName.set(f.map { it.name })
destinationDirectory.set(project.layout.dir(f.map {
project.file(it.parent ?: ".")
}))
}
override fun createCopyAction() = CopyAction { stream ->
val builder = MetadataBuilder()
trackers.get().forEach { tracker ->
builder.newTier().addTracker(tracker)
}
private.orNull?.let {
if (it) {
builder.doPrivate()
} else {
builder.doPublic()
}
}
createdBy.orNull?.let {
builder.setCreatedBy(it)
}
comment.orNull?.let {
builder.setComment(it)
}
pieceLength.orNull?.let {
builder.setPieceLength(it)
}
val files = mutableListOf<Pair<RelativePath, File>>()
stream.process {
if (!it.isDirectory) {
logger.lifecycle("${it.path} [${it.file.path}]")
files.add(it.relativePath to it.file)
}
}
val root = try {
files.map { it.first.segments[0] }.distinct().single()
} catch (e: IllegalArgumentException) {
""
}
if (root == "" && files.size > 1) {
error("more than one file added, but no root set, or conflicting roots. " +
"please specify a root using into()")
}
val processedPaths = files.map { (path, file) ->
val p = when (root) {
"" -> path
else -> RelativePath(path.isFile, *path.segments.drop(1).toTypedArray())
}
p to file
}
builder.setDirectoryName(root)
processedPaths.forEach { (path, file) ->
builder.addFile(file, path.pathString)
}
archiveFile.get().asFile.writeBytes(TorrentSerializer().serialize(builder.build()))
WorkResults.didWork(true)
}
}
/**
* Task for uploading a torrent file to nyaa.si.
* A predefined task instance can be accessed through [Subs.nyaa].
*
* @sample myaa.subkt.tasks.samples.nyaaSample
*/
open class Nyaa : PropertyTask() {
/**
* Torrent categories on Nyaa.
*/
enum class NyaaCategories(val category: String) {
ANIME_AMV("1_1"),
ANIME_ENGLISH("1_2"),
ANIME_NONENGLISH("1_3"),
ANIME_RAW("1_4"),
AUDIO_LOSSLESS("2_1"),
AUDIO_LOSSY("2_2"),
LITERATURE_ENGLISH("3_1"),
LITERATURE_NONENGLISH("3_2"),
LITERATURE_RAW("3_3"),
LIVEACTION_ENGLISH("4_1"),
LIVEACTION_IDOL("4_2"),
LIVEACTION_NONENGLISH("4_3"),
LIVEACTION_RAW("4_4"),
PICTURES_GRAPHICS("5_1"),
PICTURES_PHOTOS("5_2"),
SOFTWARE_APPLICATIONS("6_1"),
SOFTWARE_GAMES("6_2"),
S_ART_ANIME("1_1"),
S_ART_DOUJINSHI("1_2"),
S_ART_GAMES("1_3"),
S_ART_MANGA("1_4"),
S_ART_PICTURES("1_5"),
S_REALLIFE_PHOTOBOOKS("2_1"),
S_REALLIFE_VIDEOS("2_2")
}
private data class NyaaResponse(
val errors: Any?,
val hash: String?,
val id: Int?,
val magnet: String?,
val name: String?,
val url: String?
)
/**
* The API endpoint. Don't change unless you know what you're doing.
* Defaults to `api/upload`.
*/
@get:Input
val endpoint = defaultProperty("api/upload")
/**
* The hostname. Don't change unless you know what you're doing.
* Defaults to `nyaa.si`.
*/
@get:Input
val host = defaultProperty("nyaa.si")
/**
* If true, uses HTTPS to connect; HTTP otherwise.
* Don't change unless you know what you're doing.
* Defaults to `true`.
*/
@get:Input
val https = defaultProperty(true)
/**
* The port to connect to. Don't change unless you know what you're doing.
* Defaults to `443` if [https] is true; `80` otherwise.
*/
@get:Input
@get:Optional
val port = project.objects.property<Int>()
/**
* The username for posting the torrent.
*/
@get:Input
val username = project.objects.property<String>()
/**
* The password for posting the torrent.
*/
@get:Input
val password = project.objects.property<String>()
/**
* What category to post the torrent to.
* Defaults to [NyaaCategories.ANIME_ENGLISH].
*/
@get:Input
val category = defaultProperty(NyaaCategories.ANIME_ENGLISH)
/**
* The name (title) of the torrent. By default lets Nyaa choose a title
* based on the torrent file.
*/
@get:Input
val torrentName = defaultProperty("")
/**
* If true, post the torrent as anonymous.
* Defaults to `false`.
*/
@get:Input
val anonymous = defaultProperty(false)
/**
* If true, post the torrent as hidden.
* Defaults to `true`.
*/
@get:Input
val hidden = defaultProperty(true)
/**
* If true, marks the torrent as a complete release.
* Defaults to `false`.
*/
@get:Input
val complete = defaultProperty(false)
/**
* If true, marks the torrent as a remake.
* Defaults to `false`.
*/
@get:Input
val remake = defaultProperty(false)
/**
* If true, post the torrent as trusted, if using a trusted account.
* Defaults to `true`.
*/
@get:Input
val trusted = defaultProperty(true)
/**
* The torrent information (e.g. website or IRC channel).
* Defaluts to empty.
*/
@get:Input
val information = defaultProperty("")
/**
* The torrent description. Defaults to empty.
*/
@get:Input
val torrentDescription = defaultProperty("")
/**
* The torrent file to upload.
*/
@get:InputFiles
val from = project.objects.fileCollection()
@get:OutputFiles
protected val out = super.propertyFile
/**
* The magnet link of the uploaded torrent.
* Only available if the upload succeeded.
*/
@get:Internal
var nyaaMagnet by TaskProperty { "" }
private set
/**
* The hash of the uploaded torrent.
* Only available if the upload succeeded.
*/
@get:Internal
var nyaaHash by TaskProperty { "" }
private set
/**
* The Nyaa ID of the uploaded torrent.
* Only available if the upload succeeded.
*/
@get:Internal
var nyaaId by TaskProperty { -1 }
private set
/**
* The URL of the uploaded torrent.
* Only available if the upload succeeded.
*/
@get:Internal
var nyaaUrl by TaskProperty { "" }
private set
/**
* The name (title) of the uploaded torrent.
* Only available if the upload succeeded.
*/
@get:Internal
var nyaaName by TaskProperty { "" }
private set
override fun run() {
val torrentFile = from.singleFile
val fields = mapOf(
"name" to torrentName.get(),
"category" to category.get().category,
"anonymous" to anonymous.get(),
"hidden" to hidden.get(),
"complete" to complete.get(),
"remake" to remake.get(),
"trusted" to trusted.get(),
"information" to information.get(),
"description" to torrentDescription.get()
)
val client = HttpClient {
expectSuccess = false
install(JsonFeature) {
serializer = GsonSerializer()
}