How to make antispam in Py-cord bot - pycord

here is my code
It is form my old discord.py bot
I want change it to Py-cord
from core.classes import Core
from discord.ext import commands
import discord
from datetime import timedelta
import time
import json
antispam = {}
class Antispam:
def __init__(self):
self.last_msg_time = time.time()
class antispam(Core):
#commands.Cog.listener()
async def on_message(self, message):
with open(f"./GJ/{str(message.guild.id)}.json", "r", encoding="utf8")as jfile:
gdata = json.load(jfile)
if gdata["antispan"] == "off":
pass
elif gdata["antispan"] == "on":
username = message.author
user = str(message.author)
try:
spam = antispam[user]
if time.time()-spam.last_msg_time <= 1 and user != "Our AfterLife 我們的來世#9472":
timeouttime = timedelta(minutes=3, seconds=30)
await message.author.timeout(timeouttime, reason="洗頻")
embed = discord.Embed(
title="", description=f"{user}因為洗頻被伺服器禁言", color=0x005cb3)
if gdata["antispan-ch"] == "none":
if gdata["antispan-m"] == "msg":
await message.channel.send(f"{user}因為洗頻被伺服器禁言")
elif gdata["antispan-m"] == "embed":
await message.channel.send(embed=embed)
elif gdata["antispan-m"] == "embed+msg":
await message.channel.send(f"{user}因為洗頻被伺服器禁言", embed=embed)
else:
try:
channel = self.bot.get_channel(int(gdata["antispan-ch"]))
if gdata["antispan-m"] == "msg":
await channel.send(f"{user}因為洗頻被伺服器禁言")
elif gdata["antispan-m"] == "embed":
await channel.send(embed=embed)
elif gdata["antispan-m"] == "embed+msg":
await channel.send(f"{user}因為洗頻被伺服器禁言", embed=embed)
except:
pass
except:
spam = antispam[user] = Antispam()
spam.last_msg_time = time.time()
def setup(bot):
bot.add_cog(antispam(bot))
I tried it 20 times,but it still not work.
I hope it can work because I making a discord public bot now.

Related

How to synchronize fields between epics and issues in Jira with Scriptrunner?

Let us assume a typical software project in Jira that uses Issues, Subtasks and Epics, with a custom field called "Customer" that can be set on any issue or the Epic. I want to have this field synchronized, so that its value for any tickets get automatically set to the highest parent of the hierarchy, up to the epics. How to achieve that with ScriptRunner for Jira?
This can be done with the following listener:
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.link.IssueLink
def issue = event.issue as MutableIssue
def customFieldManager = ComponentAccessor.customFieldManager
def issueManager = ComponentAccessor.issueManager
def issueLinkManager = ComponentAccessor.issueLinkManager
def customField = customFieldManager.getCustomFieldObjectsByName('Customer').first()
def epicLink = customFieldManager.getCustomFieldObjectsByName('Epic Link').first()
def EPIC_STORY_LINK = "Epic-Story Link"
def issuesToUpdate = [] as ArrayList<Issue>
def valueFromTop = null
if (issue.issueType.name == 'Epic') {
// The issue is an epic. Propagate the custom field value down
valueFromTop = issue.getCustomFieldValue(customField)
issueLinkManager.getOutwardLinks(issue.id).find {
it.issueLinkType.name == EPIC_STORY_LINK
}.each { IssueLink it1 ->
issuesToUpdate.addAll(it1.destinationObject)
it1.destinationObject.subTaskObjects.findAll { it2 ->
issuesToUpdate.addAll(it2)
}
}
}
else {
// Normal issue. Look up to find the reference issue to get the value from.
def issueIterator = issue
while ( true ) {
def value = issueIterator.getCustomFieldValue(customField)
if ( value ) {
valueFromTop = value
}
issuesToUpdate.addAll(issueIterator)
if ( issueIterator.parentObject ) {
issueIterator = issueIterator.parentObject
}
else {
break
}
}
// Check if the parent issue is an Epic.
issueLinkManager.getInwardLinks(issueIterator.id).find {
it.issueLinkType.name == EPIC_STORY_LINK
}.each { IssueLink epicIssueLink ->
// Get the value from the Epic
valueFromTop = epicIssueLink.sourceObject.getCustomFieldValue(customField)
}
// Add child issues to list
issue.subTaskObjects.findAll {
issuesToUpdate.addAll(it)
}
}
def loggedInUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
issuesToUpdate.each {
def mutableTicket = it as MutableIssue
mutableTicket.setCustomFieldValue(customField, valueFromTop)
ComponentAccessor.issueManager.updateIssue(loggedInUser, mutableTicket, EventDispatchOption.DO_NOT_DISPATCH, false)
}

Active choices reactive parameter doesn't show desired default branch

I want to use Jenkins' active choices reactive parameter to use Groovy script to show all branches in the repository.
I have the following code sample to get all branches of a repository and since that there are hundreds of branches, I want the default to be master branch.
Even though I specifically inserted the defaultBranch variable, it shows the first item as the default and not the branch I written to.
Code:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import jenkins.model.Jenkins
def git_url ="url"
def getAllBranches(url, credentialID, activeChoice = false, defaultBranch = 'master') {
def jenkinsCredentials = CredentialsProvider.lookupCredentials(
com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey,
Jenkins.instance
);
def key = jenkinsCredentials.findResult { it.id == credentialID ? it.privateKey : null }
if( !key ) {
return 'Error: credentials not found'
}
Process process = ['ssh-agent','bash','-c', "echo '" + key + "' | ssh-add - 2> /dev/null && git ls-remote -t -h " + url].execute()
def out = new StringBuilder()
def err = new StringBuilder()
process.consumeProcessOutput( out, err )
process.waitFor()
if( err.size() > 0 ) return err
if( out.size() > 0 ) {
def branches = out.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') }
if( activeChoice ) {
def defaultBranchIndex = branches.indexOf(defaultBranch)
if( defaultBranchIndex >= 0 ) branches.set(defaultBranchIndex, defaultBranch + ':selected')
}
return branches
}
}
return getAllBranches(git_url, "efa7bed9-56a0-42ac-8fa3-a68fe7700801")
You have set default for activeChoice to false in the getAllBranches method and do not set while calling it, thus the if-branch that adds the :selected is never entered.
I changed activeChoice method's value from false to true and it solved my issue:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import jenkins.model.Jenkins
def git_url ="url"
def getAllBranches(url, credentialID, activeChoice = true, defaultBranch = 'master') {
def jenkinsCredentials = CredentialsProvider.lookupCredentials(
com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey,
Jenkins.instance
);
def key = jenkinsCredentials.findResult { it.id == credentialID ? it.privateKey : null }
if( !key ) {
return 'Error: credentials not found'
}
Process process = ['ssh-agent','bash','-c', "echo '" + key + "' | ssh-add - 2> /dev/null && git ls-remote -t -h " + url].execute()
def out = new StringBuilder()
def err = new StringBuilder()
process.consumeProcessOutput( out, err )
process.waitFor()
if( err.size() > 0 ) return err
if( out.size() > 0 ) {
def branches = out.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') }
if( activeChoice ) {
def defaultBranchIndex = branches.indexOf(defaultBranch)
if( defaultBranchIndex >= 0 ) branches.set(defaultBranchIndex, defaultBranch + ':selected')
}
return branches
}
}
return getAllBranches(git_url, "efa7bed9-56a0-42ac-8fa3-a68fe7700801")

How do I dump secret text files to the console?

I use this script to dump credentials in the script console:
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
def showRow = { credentialType, secretId, username = null, password = null, description = null ->
println("${credentialType} : ".padLeft(20) + secretId?.padRight(38)+" | " +username?.padRight(20)+" | " +password?.padRight(40) + " | " +description)
}
domainName = null
credentialsStore = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0]?.getStore()
domain = new Domain(domainName, null, Collections.<DomainSpecification>emptyList())
credentialsStore?.getCredentials(domain).each{
if(it instanceof UsernamePasswordCredentialsImpl)
showRow("user/password", it.id, it.username, it.password?.getPlainText(),it.description)
else if(it instanceof BasicSSHUserPrivateKey)
showRow("ssh priv key", it.id, it.passphrase?.getPlainText(), it.privateKeySource?.getPrivateKey(), it.description )
else if(it instanceof AWSCredentialsImpl)
showRow("aws", it.id, it.accessKey, it.secretKey?.getPlainText(),it.description )
else if(it instanceof StringCredentials)
showRow("secret text", it.id, it.secret?.getPlainText(), it.description, '' )
else
showRow("something else", it.id)
}
return
But it doesnt dump "Secret file" cred types (they fall through to "something else".
How can I also dump the contents of secret files in this script? What is the class for "Secret file"? what instanceof would that be?

Jenkins Script to create a group and add users?

I wrote a DSL Script to create a folder in Jenkins but now I need a script to create a group for that folder and add users into the same group and assign a role to a group.
import com.cloudbees.hudson.plugins.folder.*
import com.cloudbees.hudson.plugins.foldersplus.*
import jenkins.model.Jenkins;
import nectar.plugins.rbac.strategy.*;
import hudson.security.*;
import nectar.plugins.rbac.groups.*;
import nectar.plugins.rbac.roles.*;
String folderName = 'Project-B'
folderItem = Jenkins.instance.getAllItems(Folder.class).find{it.name.equals(folderName)}
String groupName = "membersOfProject-B"
GroupContainer container = GroupContainerLocator.locate(Jenkins.getInstance())
Group group = new Group(container, groupName)
group.doAddMember('mike')
group.doGrantRole('develop', 0, Boolean.TRUE)
container.addGroup(group)
import nectar.plugins.rbac.groups.*
import java.util.*
import com.cloudbees.opscenter.server.model.*
import com.cloudbees.opscenter.server.clusterops.steps.*
import com.cloudbees.hudson.plugins.folder.*
import com.cloudbees.hudson.plugins.foldersplus.*
import jenkins.model.Jenkins;
import nectar.plugins.rbac.strategy.*;
import hudson.security.*;
import nectar.plugins.rbac.groups.*;
import nectar.plugins.rbac.roles.*;
import hudson.model.*;
// Assign request values
def appName = "TestApp";
def devs = ['userid1','userid2','userid3'];
// Begin Script
def instance = Jenkins.getInstance()
// Folder Path ( root dir is 'Jenkins/')
def targetDirectory = 'Jenkins/FolderName_Level_1 » ' + appName;
println("target Directory= ${targetDirectory}");
// Folder's Group Name (which you want to create or update)
def groupName = 'developers';
// Group's Role list that you want to assign e.g['admin','developer']
def groupRole = ['developer'] ;
// Group's Member list which you want to add (by ADID) e.g['xyz','abc']
def addUsers = devs;
//Booleans to detect if function found group or not
Boolean foundGrp = false;
// Container used to handle connected Client masters
class ExploredObject {
GroupContainer groupContainer
Boolean isMaster
Item instance
}
Map containers = new TreeMap();
// Add the root container
def root = new ExploredObject()
root.groupContainer = GroupContainerLocator.locate(Jenkins.instance)
root.isMaster = false
containers.put(Jenkins.instance.displayName, root)
// Add all the items that are be containers
for (i in Jenkins.instance.allItems) {
if (GroupContainerLocator.isGroupContainer(i.getClass())) {
GroupContainer g = GroupContainerLocator.locate(i)
if (g != null) {
def exploredObject = new ExploredObject()
exploredObject.groupContainer = g
exploredObject.instance = i
containers.put("${Jenkins.instance.displayName}/${i.fullDisplayName}", exploredObject)
}
}
}
// Parse throuch all folder in root
for (cont in containers) {
def c = cont.value.groupContainer
// println(cont.key)
if (cont.key == targetDirectory) {
//println(cont.key)
//println("Target Directory found")
if (c.groups.size()){
// Parse through the groups of the folder
for (g in c.groups) {
//If the group exist the add members
if (g.name == groupName){
foundGrp = true;
println(" + ${g.name}")
def currentMembers = g.members
println(" * Current Members : ${currentMembers}")
println(" * Current Roles: ${g.roles.collect {it + (g.doesPropagateToChildren(it) ?' (propagates)':'(pinned)')}}")
if(addUsers.size() > 0){
println(" -- Starting Add(+) / Delete(-) users to ${g.name}")
// adds user to group
for (eachUser in addUsers){
g.doAddMember(eachUser)
println(" + ${eachUser} Added")
}
println(" -- Completed Add / Delete users to ${g.name}")
for (role in groupRole){
g.doGrantRole(role, 0, Boolean.TRUE)
println(" * Role assigned : role")
}
}
}
} //end of for loop g in c.groups
}// end of if loop c.groups.size()
//if the group doesn't exist then Create a group,Add member and assign role
else{ // else of if loop c.groups.size()
if(foundGrp == false){
println("Group '${groupName}' does not exist")
Group group = new Group(c, groupName)
println(" + Start Adding user to ${groupName}")
for (eachUser in addUsers){
group.doAddMember(eachUser)
println(" + ${eachUser} Added")
}
for (role in groupRole){
group.doGrantRole(role, 0, Boolean.TRUE)
println(" * Role assigned : ${role}")
}
c.addGroup(group)
println("Group '${groupName}' is Created Succefully")
}
}
}
else{
}
}
instance.save()

NPE after grails clean

The application works just fine, but after grails clean it starts throwing an error if I execute grails war or grail web-app:
|Loading Grails 2.4.3
|Configuring classpath
.
|Environment set to production
.................................
|Packaging Grails application
..
|Compiling 18 source files
.Error
|
Compilation error: startup failed:
General error during class generation: NPE while processing BcvjobService.groovy
groovy.lang.GroovyRuntimeException: NPE while processing BcvjobService.groovy
at org.codehaus.groovy.classgen.AsmClassGenerator.visitClass(AsmClassGenerator.java:252)
at org.codehaus.groovy.control.CompilationUnit$16.call(CompilationUnit.java:805)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1047)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:583)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:561)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:538)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:517)
at org.codehaus.groovy.tools.FileSystemCompiler.compile(FileSystemCompiler.java:59)
at org.codehaus.groovy.tools.FileSystemCompiler.doCompilation(FileSystemCompiler.java:215)
at org.codehaus.groovy.ant.Groovyc.runCompiler(Groovyc.java:1161)
at org.codehaus.groovy.ant.Groovyc.compile(Groovyc.java:1212)
at org.codehaus.groovy.grails.compiler.Grailsc.compile(Grailsc.java:78)
at org.codehaus.groovy.ant.Groovyc.execute(Groovyc.java:827)
...
Googling didn't help in the least, so I can't even understand where to start, and any help would be greatly appreciated.
Here is BcvjobService.groovy:
package bcvapp
import grails.transaction.Transactional
import groovy.lang.Closure;
import groovy.io.FileType
import groovy.util.AntBuilder
import java.awt.event.ItemEvent;
import java.util.List;
import java.util.regex.Pattern;
import grails.util.Mixin
import grails.util.Holders
import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
#Transactional
#Mixin(ServiceCategory)
class BcvjobService {
def mailService
def holderService
def servletContext = SCH.servletContext
def String absPath = getAbsPath()
def String configPath = servletContext.getRealPath("/pipeline/bcvrun.prj.xml")
def outputMap = [:]
def prepareDirectory(Bcvjob job, String sessionId, List fileList, List directionList, Integer queueSize){
def configFile = new File (configPath)
def defaultConfig = new XmlParser().parse(configFile)
// Create directory structure
def inputLine = defaultConfig.BCV_Input
def input = inputLine.text().replaceAll(Pattern.compile('[\\.\\/\\\\]'), '')
def outputLine = defaultConfig.BCV_Output
def output = outputLine.text().replaceAll(Pattern.compile('[\\.\\/\\\\]'), '')
def folderPath = "${absPath}${sessionId}"
def inputPath = folderPath + "/" + input
def outputPath = folderPath + "/" + output
addResultsPath(sessionId, outputPath)
inputLine[0].value = inputPath
outputLine[0].value = outputPath
def inpath = defaultConfig.InPath // why there are two almost identical lines in bcv config?
inpath[0].value = inputPath
new File (inputPath).mkdirs()
new File (outputPath).mkdir()
new File(outputPath + "/simple_results.html").createNewFile()
File res = new File(outputPath + "/simple_results.html")
if (queueSize > 2 ){
res << ("Your task was submitted at ${new Date()}<p>")
res << ("Waiting in queue..<p>")
res << ("Please, bookmark this page to see the results later. Refresh the page to check if they are ready.")
}
else {
res << ("Your task was submitted at ${new Date()}<p>")
res << ("Running..<p>")
res << ("Please, bookmark this page to see the results later. Refresh the page to check if they are ready.")
}
res << ("<script>")
res << ("var interval = setInterval('location.reload()', '30000');")
res << ("</script>")
for (f in fileList){
new File (outputPath + "/" + f.getOriginalFilename().replaceAll(Pattern.compile('\\..*'), '').replaceAll("\\s+", "_")).mkdir()
}
uploadFiles(inputPath, fileList)
// Write custom configuration file
def vocabulary = defaultConfig.Vocabulary
def vocabularyPath = vocabulary[0].text().substring(0, vocabulary[0].text().lastIndexOf("/")+1)
def vocabularyName = job.vocabulary.replaceAll(/\s+/, "_")
vocabulary[0].value = vocabularyPath + vocabularyName + ".seq.fas"
def reads = defaultConfig.READS.find{'READS'}
reads.children.clear()
def counter = 0
for (f in fileList){
def stringDirection
if (directionList.get(counter) == "r"){
stringDirection = "reverse"
}
else stringDirection = "forward"
reads.appendNode('Read', [name:f.getOriginalFilename().replaceAll("\\s+", "_")]).appendNode('Direction', stringDirection)
counter++
}
def taxdb = defaultConfig.Database
if (job.taxdb == "full"){
taxdb[0].value = "all"
}
else if (job.taxdb == "named isolates"){
taxdb[0].value = "named"
}
def distance = defaultConfig.DistanceThreshold
distance[0].value = job.distance.toFloat()
def email = defaultConfig.Email
email[0].value = job.email
def mode = defaultConfig.Mode
mode[0].value = "PIPELINE"
def writer = new StringWriter()
def printer = new XmlNodePrinter(new PrintWriter(writer))
printer.with {
preserveWhitespace = true
expandEmptyElements = true
}
printer.print(defaultConfig)
def result = writer.toString()
new File(folderPath + "/bcvrun.prj.xml").write(result)
return outputPath
}
def Closure getWaitingPipeline = {Bcvjob job ->
def queueSize = Bcvjob.countByDateCreatedLessThanEquals(job.dateCreated) + Stapjob.countByDateCreatedLessThanEquals(job.dateCreated)
if(queueSize > 2){
println (" bcv waiting in queue; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
while (queueSize > 2){ // 1 running task + our task
sleep(5000)
queueSize = Bcvjob.countByDateCreatedLessThanEquals(job.dateCreated) + Stapjob.countByDateCreatedLessThanEquals(job.dateCreated)
}
println (" bcv finished waiting in queue; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
def res = new File(getResults(job.sessionId)).newWriter()
res.write("Your task was submitted at ${new Date()}<p>")
res.write("Running..<p>")
res.write("Please, bookmark this page to see the results later. Refresh the page to check if they are ready.")
res.close()
}
def returnCode = runPipeline(job.sessionId)
println (" bcv waiting pipeline finished; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
if (returnCode != 143){
zipResults(job.sessionId)
println (" bcv waiting results zipped; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
}
if (returnCode == 0){
if (job.email) {
sendResults(job.email, job.sessionId)
println (" bcv waiting results sent; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
}
}
else {
if (job.email) {
sendLogs(job.email, job.sessionId)
println (" bcv bad news sent; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
}
else if (returnCode != 143) {
sendLogs(job.sessionId) // send to weidewind
}
else {
println (" user left; sessionId ${job.sessionId} ")
}
}
def sessionId = job.sessionId
job.delete(flush:true)
holderService.setDone(sessionId)
}
def Closure getPipeline = {Bcvjob job ->
def returnCode = runPipeline(job.sessionId)
println (" bcv pipeline finished; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
if (returnCode != 143){
zipResults(job.sessionId)
println (" bcv results zipped; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
}
if (returnCode == 0){
if (job.email) {
sendResults(job.email, job.sessionId)
println (" bcv results sent; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
}
}
else {
if (job.email) {
sendLogs(job.email, job.sessionId, returnCode)
println (" bcv bad news sent; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
}
else if (returnCode != 143) {
sendLogs(job.sessionId) // send to weidewind
}
else {
println (" user left; sessionId ${job.sessionId} ")
}
}
def sessionId = job.sessionId
job.delete(flush:true)
holderService.setDone(sessionId)
}
private def addResultsPath(String sessionId, String outputPath){
outputMap.putAt(sessionId, outputPath)
}
def runPipeline(String sessionId){
println (" going to run bcv pipeline, sessionId ${sessionId}")
def command = "perl /store/home/popova/Programs/BCV_pipeline/pipeline.pl ${absPath}${sessionId} bcvrun.prj.xml >${absPath}pipelinelog.txt >2${absPath}pipelinerr.txt"// Create the String
holderService.procs[sessionId] = command.execute() // Call *execute* on the string
holderService.procs[sessionId].consumeProcessOutput( System.out, System.err ) //31.10
holderService.procs[sessionId].waitFor() // Wait for the command to finish
def exitValue = holderService.procs[sessionId].exitValue()
println "return code " + exitValue
holderService.deleteProc(sessionId)
return exitValue
}
def uploadFiles(String uploadPath, List fileList){
for (f in fileList){
if(f instanceof org.springframework.web.multipart.commons.CommonsMultipartFile){
def fileName = f.getOriginalFilename().replaceAll("\\s+", "_")
new FileOutputStream(uploadPath + "/" + fileName).leftShift( f.getInputStream() )
} else {
log.error("wrong attachment type [${f.getClass()}]");
}
}
}
def uploadSequenceFiles(String uploadPath, List fileList){
for (f in fileList){
if(f instanceof org.springframework.web.multipart.commons.CommonsMultipartFile){
def fileName = f.getOriginalFilename().replaceAll("\\s+", "_")
new FileOutputStream(uploadPath + "/" + fileName.replaceAll(Pattern.compile('\\..*'), '') + "/" + fileName).leftShift( f.getInputStream() )
} else {
log.error("wrong attachment type [${f.getClass()}]");
}
}
}
def sendResults(String email, String sessionId) {
def results = getZipResults(sessionId)
println "going to send files, sessionID ${sessionId} resultsPath ${results} time ${System.currentTimeMillis()}"
mailService.sendMail {
multipart true
to email
subject "BCV results"
body "Thanks for using BCV!\n Here are your results. \n Have a nice day!"
attachBytes 'results.zip','application/zip', new File(results).readBytes()
}
}
def sendExampleResults(String email, String folderName){
def results = getStorePath() + folderName + "/results.zip"
println "going to send files, folderName ${folderName} resultsPath ${results} time ${System.currentTimeMillis()}"
mailService.sendMail {
multipart true
to email
subject "Example BCV results"
body "Thanks for using BCV!\n Here are your example results. \n Have a nice day!"
attachBytes 'results.zip','application/zip', new File(results).readBytes()
}
}
def sendLogs(String email, String sessionId) {
//def logs = "${absPath}${sessionId}logfile"
def results = getZipResults(sessionId)
println "going to send logs, sessionID ${sessionId} logPath ${logs} time ${System.currentTimeMillis()}"
mailService.sendMail {
multipart true
to email
subject "BCV failed"
body "We are very sorry, but something has gone amiss. Here are some of your results, though."
attachBytes 'results.zip','application/zip', new File(results).readBytes()
}
//just in case there is no results at all and results.zip does not exist. Todo: catch mailService or zip exception
//else user left, auto-termination
mailService.sendMail {
multipart true
to "weidewind#gmail.com"
subject "BCV failed"
body "Achtung! email: ${email}, sessionId: ${sessionId}"
}
mailService.sendMail {
multipart true
to "weidewind#gmail.com"
subject "BCV failed"
body "Achtung! email: ${email}, sessionId: ${sessionId}"
attachBytes 'results.zip','application/zip', new File(results).readBytes()
}
println (" bcv bad news sent to webmaster; sessionId ${job.sessionId} time ${System.currentTimeMillis()}")
}
def sendLogs(String sessionId){
//just in case there is no results at all and results.zip does not exist. Todo: catch mailService or zip exception
mailService.sendMail {
multipart true
to "weidewind#gmail.com"
subject "BCV failed"
body "Achtung! sessionId: ${sessionId}"
}
println (" bcv bad news sent to webmaster; sessionId ${sessionId} time ${System.currentTimeMillis()}")
}
def zipResults(String sessionId){
def output = getOutput(sessionId)
def results = getZipResults(sessionId)
println "going to zip files, sessionID ${sessionId} time ${System.currentTimeMillis()}"
println (output)
def p = ~/.*\.(svg|html|with_names|cluster\.fasta)/
def filelist = []
def outputDir = new File(output)
outputDir.eachDir { chrom ->
def chromDir = new File(chrom.absolutePath)
chromDir.eachFileMatch(FileType.FILES, p){ tree ->
def splittedPath = tree.absolutePath.split('/')
println ("going to add ${splittedPath[splittedPath.size()-2]}/${splittedPath[splittedPath.size()-1]} from ${output} to zip list; sessionId ${sessionId}")
filelist.add("${splittedPath[splittedPath.size()-2]}/${splittedPath[splittedPath.size()-1]}")
}
}
filelist.add("simple_results.html")
println("results will be placed here ${results}")
def zipFile = new File("${results}")
new AntBuilder().zip( basedir: output,
destFile: zipFile.absolutePath,
includes: filelist.join( ' ' ) )
}
def getResults (String sessionId){
return outputMap.getAt(sessionId) + "/simple_results.html"
}
def getOutput(String sessionId){
return outputMap.getAt(sessionId)
}
def getZipResults(String sessionId){
return outputMap.getAt(sessionId) + "/results.zip"
}
def getExampleFolderName(List fileList){
def exampleFileNames = []
for (f in fileList){
exampleFileNames.add(f.name)
}
exampleFileNames.sort()
def folderName = ""
for (f in exampleFileNames){
folderName = folderName + (f.replaceAll(Pattern.compile('\\..*'), ''))
}
println folderName
return folderName
}
def checkInput(Bcvjob job, List fileList){
String errorMessage = ""
if (!job.validate()) {
errorMessage = "Some errors occured: "
job.errors.each {
errorMessage += "<p>" + it + "</p>"
}
//if (!isFloat(job.distance) || job.distance.toFloat() < 0 || job.distance.toFloat() > 0.1){
if ( job.distance < 0 || job.distance > 0.1){
errorMessage += "<p> Maximum distance must not be less than 0 or more than 0.1 </p>"
}
if (job.errors.hasFieldErrors("email")){
errorMessage += "<p>Your e-mail does not seem valid </p>"
}
if (job.errors.hasFieldErrors("files") || (fileList.size() == 0 & job.isExample == "false")){
errorMessage += "<p>Select at least one file </p>"
}
}
if (fileList.size() > 10){
errorMessage += "<p>Please, do not select more than 10 files at once. </p>"
}
if (job.isExample == "false"){
for (f in fileList) {
def name = f.getOriginalFilename()
int dot= name.lastIndexOf(".");
if (name.substring(dot+1) != "ab1"){
errorMessage += "<p>Unsupported extension: ${name} </p>"
}
def bytes = f.getBytes()
if (bytes[0] != 'A' || bytes[1] != 'B' || bytes[2] != 'I' || bytes[3] != 'F' || !(bytes[4]+bytes[5] >= 101)){
errorMessage += "<p>Not ABI: ${name} </p>"
}
}
}
return errorMessage
}
def isFloat(String value)
{
try
{
Float.parseFloat(value);
return true;
} catch(NumberFormatException nfe)
{
return false;
}
}
def getAbsPath(){
return Holders.config.absPath
}
def getStorePath(){
return Holders.config.storePath
}
def talkWork(){
ServiceCategory.talkWork()
}
def talkQueue(){
ServiceCategory.talkQueue()
}
}

Resources