id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,900 | go-playground/log | handlers/email/email.go | New | func New(host string, port int, username string, password string, from string, to []string) *Email {
e := &Email{
enabled: true,
timestampFormat: log.DefaultTimeFormat,
host: host,
port: port,
username: username,
password: password,
from: from,
to: to,
formatFunc: defaultFormatFunc,
}
e.SetTemplate(defaultTemplate)
return e
} | go | func New(host string, port int, username string, password string, from string, to []string) *Email {
e := &Email{
enabled: true,
timestampFormat: log.DefaultTimeFormat,
host: host,
port: port,
username: username,
password: password,
from: from,
to: to,
formatFunc: defaultFormatFunc,
}
e.SetTemplate(defaultTemplate)
return e
} | [
"func",
"New",
"(",
"host",
"string",
",",
"port",
"int",
",",
"username",
"string",
",",
"password",
"string",
",",
"from",
"string",
",",
"to",
"[",
"]",
"string",
")",
"*",
"Email",
"{",
"e",
":=",
"&",
"Email",
"{",
"enabled",
":",
"true",
",",
"timestampFormat",
":",
"log",
".",
"DefaultTimeFormat",
",",
"host",
":",
"host",
",",
"port",
":",
"port",
",",
"username",
":",
"username",
",",
"password",
":",
"password",
",",
"from",
":",
"from",
",",
"to",
":",
"to",
",",
"formatFunc",
":",
"defaultFormatFunc",
",",
"}",
"\n",
"e",
".",
"SetTemplate",
"(",
"defaultTemplate",
")",
"\n",
"return",
"e",
"\n",
"}"
] | // New returns a new instance of the email logger | [
"New",
"returns",
"a",
"new",
"instance",
"of",
"the",
"email",
"logger"
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/handlers/email/email.go#L54-L68 |
4,901 | go-playground/log | handlers/email/email.go | SetTemplate | func (email *Email) SetTemplate(htmlTemplate string) {
email.rw.Lock()
defer email.rw.Unlock()
// parse email htmlTemplate, will panic if fails
email.template = template.Must(template.New("email").Funcs(
template.FuncMap{
"ts": func(e log.Entry) (ts string) {
ts = e.Timestamp.Format(email.timestampFormat)
return
},
},
).Parse(htmlTemplate))
} | go | func (email *Email) SetTemplate(htmlTemplate string) {
email.rw.Lock()
defer email.rw.Unlock()
// parse email htmlTemplate, will panic if fails
email.template = template.Must(template.New("email").Funcs(
template.FuncMap{
"ts": func(e log.Entry) (ts string) {
ts = e.Timestamp.Format(email.timestampFormat)
return
},
},
).Parse(htmlTemplate))
} | [
"func",
"(",
"email",
"*",
"Email",
")",
"SetTemplate",
"(",
"htmlTemplate",
"string",
")",
"{",
"email",
".",
"rw",
".",
"Lock",
"(",
")",
"\n",
"defer",
"email",
".",
"rw",
".",
"Unlock",
"(",
")",
"\n\n",
"// parse email htmlTemplate, will panic if fails",
"email",
".",
"template",
"=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Funcs",
"(",
"template",
".",
"FuncMap",
"{",
"\"",
"\"",
":",
"func",
"(",
"e",
"log",
".",
"Entry",
")",
"(",
"ts",
"string",
")",
"{",
"ts",
"=",
"e",
".",
"Timestamp",
".",
"Format",
"(",
"email",
".",
"timestampFormat",
")",
"\n",
"return",
"\n",
"}",
",",
"}",
",",
")",
".",
"Parse",
"(",
"htmlTemplate",
")",
")",
"\n",
"}"
] | // SetTemplate sets Email's html template to be used for email body | [
"SetTemplate",
"sets",
"Email",
"s",
"html",
"template",
"to",
"be",
"used",
"for",
"email",
"body"
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/handlers/email/email.go#L71-L84 |
4,902 | go-playground/log | handlers/email/email.go | SetFormatFunc | func (email *Email) SetFormatFunc(fn FormatFunc) {
email.rw.Lock()
defer email.rw.Unlock()
email.formatFunc = fn
} | go | func (email *Email) SetFormatFunc(fn FormatFunc) {
email.rw.Lock()
defer email.rw.Unlock()
email.formatFunc = fn
} | [
"func",
"(",
"email",
"*",
"Email",
")",
"SetFormatFunc",
"(",
"fn",
"FormatFunc",
")",
"{",
"email",
".",
"rw",
".",
"Lock",
"(",
")",
"\n",
"defer",
"email",
".",
"rw",
".",
"Unlock",
"(",
")",
"\n\n",
"email",
".",
"formatFunc",
"=",
"fn",
"\n",
"}"
] | // SetFormatFunc sets FormatFunc each worker will call to get
// a Formatter func | [
"SetFormatFunc",
"sets",
"FormatFunc",
"each",
"worker",
"will",
"call",
"to",
"get",
"a",
"Formatter",
"func"
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/handlers/email/email.go#L112-L117 |
4,903 | go-playground/log | handlers/email/email.go | SetEmailConfig | func (email *Email) SetEmailConfig(host string, port int, username string, password string, from string, to []string) {
email.rw.Lock()
defer email.rw.Unlock()
email.host = host
email.port = port
email.username = username
email.password = password
email.from = from
email.to = to
email.formatter = email.formatFunc(email)
} | go | func (email *Email) SetEmailConfig(host string, port int, username string, password string, from string, to []string) {
email.rw.Lock()
defer email.rw.Unlock()
email.host = host
email.port = port
email.username = username
email.password = password
email.from = from
email.to = to
email.formatter = email.formatFunc(email)
} | [
"func",
"(",
"email",
"*",
"Email",
")",
"SetEmailConfig",
"(",
"host",
"string",
",",
"port",
"int",
",",
"username",
"string",
",",
"password",
"string",
",",
"from",
"string",
",",
"to",
"[",
"]",
"string",
")",
"{",
"email",
".",
"rw",
".",
"Lock",
"(",
")",
"\n",
"defer",
"email",
".",
"rw",
".",
"Unlock",
"(",
")",
"\n\n",
"email",
".",
"host",
"=",
"host",
"\n",
"email",
".",
"port",
"=",
"port",
"\n",
"email",
".",
"username",
"=",
"username",
"\n",
"email",
".",
"password",
"=",
"password",
"\n",
"email",
".",
"from",
"=",
"from",
"\n",
"email",
".",
"to",
"=",
"to",
"\n",
"email",
".",
"formatter",
"=",
"email",
".",
"formatFunc",
"(",
"email",
")",
"\n",
"}"
] | // SetEmailConfig allows updating of the email config in flight and is thread safe. | [
"SetEmailConfig",
"allows",
"updating",
"of",
"the",
"email",
"config",
"in",
"flight",
"and",
"is",
"thread",
"safe",
"."
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/handlers/email/email.go#L120-L131 |
4,904 | go-playground/log | handlers/email/email.go | SetEnabled | func (email *Email) SetEnabled(enabled bool) {
email.rw.Lock()
defer email.rw.Unlock()
email.enabled = enabled
} | go | func (email *Email) SetEnabled(enabled bool) {
email.rw.Lock()
defer email.rw.Unlock()
email.enabled = enabled
} | [
"func",
"(",
"email",
"*",
"Email",
")",
"SetEnabled",
"(",
"enabled",
"bool",
")",
"{",
"email",
".",
"rw",
".",
"Lock",
"(",
")",
"\n",
"defer",
"email",
".",
"rw",
".",
"Unlock",
"(",
")",
"\n\n",
"email",
".",
"enabled",
"=",
"enabled",
"\n",
"}"
] | // SetEnabled enables or disables the email handler sending emails | [
"SetEnabled",
"enables",
"or",
"disables",
"the",
"email",
"handler",
"sending",
"emails"
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/handlers/email/email.go#L134-L139 |
4,905 | go-playground/log | _examples/custom-handler/main.go | Log | func (c *CustomHandler) Log(e log.Entry) {
// below prints to os.Stderr but could marshal to JSON
// and send to central logging server
// ---------
// |----------> | console |
// | ---------
// i.e. ----------------- ----------------- Unmarshal ------------- --------
// | app log handler | -- json --> | central log app | -- to -> | log handler | --> | syslog |
// ----------------- ----------------- Entry ------------- --------
// | ---------
// |----------> | DataDog |
// ---------
b := new(bytes.Buffer)
b.Reset()
b.WriteString(e.Message)
for _, f := range e.Fields {
fmt.Fprintf(b, " %s=%v", f.Key, f.Value)
}
fmt.Println(b.String())
} | go | func (c *CustomHandler) Log(e log.Entry) {
// below prints to os.Stderr but could marshal to JSON
// and send to central logging server
// ---------
// |----------> | console |
// | ---------
// i.e. ----------------- ----------------- Unmarshal ------------- --------
// | app log handler | -- json --> | central log app | -- to -> | log handler | --> | syslog |
// ----------------- ----------------- Entry ------------- --------
// | ---------
// |----------> | DataDog |
// ---------
b := new(bytes.Buffer)
b.Reset()
b.WriteString(e.Message)
for _, f := range e.Fields {
fmt.Fprintf(b, " %s=%v", f.Key, f.Value)
}
fmt.Println(b.String())
} | [
"func",
"(",
"c",
"*",
"CustomHandler",
")",
"Log",
"(",
"e",
"log",
".",
"Entry",
")",
"{",
"// below prints to os.Stderr but could marshal to JSON",
"// and send to central logging server",
"//\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ---------",
"// \t\t\t\t |----------> | console |",
"// | ---------",
"// i.e. ----------------- ----------------- Unmarshal ------------- --------",
"// | app log handler | -- json --> | central log app | -- to -> | log handler | --> | syslog |",
"// ----------------- ----------------- Entry ------------- --------",
"// \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t | ---------",
"// \t\t\t\t\t\t\t\t\t |----------> | DataDog |",
"// \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t ---------",
"b",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"b",
".",
"Reset",
"(",
")",
"\n",
"b",
".",
"WriteString",
"(",
"e",
".",
"Message",
")",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"e",
".",
"Fields",
"{",
"fmt",
".",
"Fprintf",
"(",
"b",
",",
"\"",
"\"",
",",
"f",
".",
"Key",
",",
"f",
".",
"Value",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"b",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // Log accepts log entries to be processed | [
"Log",
"accepts",
"log",
"entries",
"to",
"be",
"processed"
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/_examples/custom-handler/main.go#L16-L37 |
4,906 | go-playground/log | handlers/http/http.go | New | func New(remoteHost string, method string, header stdhttp.Header) (*HTTP, error) {
if _, err := url.Parse(remoteHost); err != nil {
return nil, err
}
h := &HTTP{
remoteHost: remoteHost,
timestampFormat: log.DefaultTimeFormat,
header: header,
method: method,
client: stdhttp.Client{},
formatFunc: defaultFormatFunc,
}
return h, nil
} | go | func New(remoteHost string, method string, header stdhttp.Header) (*HTTP, error) {
if _, err := url.Parse(remoteHost); err != nil {
return nil, err
}
h := &HTTP{
remoteHost: remoteHost,
timestampFormat: log.DefaultTimeFormat,
header: header,
method: method,
client: stdhttp.Client{},
formatFunc: defaultFormatFunc,
}
return h, nil
} | [
"func",
"New",
"(",
"remoteHost",
"string",
",",
"method",
"string",
",",
"header",
"stdhttp",
".",
"Header",
")",
"(",
"*",
"HTTP",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"remoteHost",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"h",
":=",
"&",
"HTTP",
"{",
"remoteHost",
":",
"remoteHost",
",",
"timestampFormat",
":",
"log",
".",
"DefaultTimeFormat",
",",
"header",
":",
"header",
",",
"method",
":",
"method",
",",
"client",
":",
"stdhttp",
".",
"Client",
"{",
"}",
",",
"formatFunc",
":",
"defaultFormatFunc",
",",
"}",
"\n",
"return",
"h",
",",
"nil",
"\n",
"}"
] | // New returns a new instance of the http logger | [
"New",
"returns",
"a",
"new",
"instance",
"of",
"the",
"http",
"logger"
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/handlers/http/http.go#L43-L57 |
4,907 | go-playground/log | handlers/http/hipchat/hipchat.go | New | func New(api APIVersion, remoteHost string, contentType string, authToken string, application string) (*HipChat, error) {
// test here https://developer.atlassian.com/hipchat/guide/hipchat-rest-api that api token has access
authToken = "Bearer " + authToken
client := &stdhttp.Client{}
req, err := stdhttp.NewRequest("GET", remoteHost+"?auth_test=true", nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", authToken)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != stdhttp.StatusAccepted {
bt, _ := ioutil.ReadAll(resp.Body)
return nil, fmt.Errorf("HipChat authorization failed\n %s", string(bt))
}
header := make(stdhttp.Header)
header.Set("Content-Type", contentType)
header.Set("Authorization", authToken)
hc := &HipChat{
colors: defaultColors,
api: api,
application: application,
}
// not checking error because url.Parse() is the only thin that can fail,
// and we've already checked above that it was OK sending the test request
hc.HTTP, _ = http.New(strings.TrimRight(remoteHost, "/")+"/notification", method, header)
hc.HTTP.SetFormatFunc(formatFunc(hc))
hc.SetTemplate(defaultTemplate)
return hc, nil
} | go | func New(api APIVersion, remoteHost string, contentType string, authToken string, application string) (*HipChat, error) {
// test here https://developer.atlassian.com/hipchat/guide/hipchat-rest-api that api token has access
authToken = "Bearer " + authToken
client := &stdhttp.Client{}
req, err := stdhttp.NewRequest("GET", remoteHost+"?auth_test=true", nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", authToken)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != stdhttp.StatusAccepted {
bt, _ := ioutil.ReadAll(resp.Body)
return nil, fmt.Errorf("HipChat authorization failed\n %s", string(bt))
}
header := make(stdhttp.Header)
header.Set("Content-Type", contentType)
header.Set("Authorization", authToken)
hc := &HipChat{
colors: defaultColors,
api: api,
application: application,
}
// not checking error because url.Parse() is the only thin that can fail,
// and we've already checked above that it was OK sending the test request
hc.HTTP, _ = http.New(strings.TrimRight(remoteHost, "/")+"/notification", method, header)
hc.HTTP.SetFormatFunc(formatFunc(hc))
hc.SetTemplate(defaultTemplate)
return hc, nil
} | [
"func",
"New",
"(",
"api",
"APIVersion",
",",
"remoteHost",
"string",
",",
"contentType",
"string",
",",
"authToken",
"string",
",",
"application",
"string",
")",
"(",
"*",
"HipChat",
",",
"error",
")",
"{",
"// test here https://developer.atlassian.com/hipchat/guide/hipchat-rest-api that api token has access",
"authToken",
"=",
"\"",
"\"",
"+",
"authToken",
"\n\n",
"client",
":=",
"&",
"stdhttp",
".",
"Client",
"{",
"}",
"\n\n",
"req",
",",
"err",
":=",
"stdhttp",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"remoteHost",
"+",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Add",
"(",
"\"",
"\"",
",",
"authToken",
")",
"\n\n",
"resp",
",",
"err",
":=",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"stdhttp",
".",
"StatusAccepted",
"{",
"bt",
",",
"_",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"string",
"(",
"bt",
")",
")",
"\n",
"}",
"\n\n",
"header",
":=",
"make",
"(",
"stdhttp",
".",
"Header",
")",
"\n",
"header",
".",
"Set",
"(",
"\"",
"\"",
",",
"contentType",
")",
"\n",
"header",
".",
"Set",
"(",
"\"",
"\"",
",",
"authToken",
")",
"\n\n",
"hc",
":=",
"&",
"HipChat",
"{",
"colors",
":",
"defaultColors",
",",
"api",
":",
"api",
",",
"application",
":",
"application",
",",
"}",
"\n\n",
"// not checking error because url.Parse() is the only thin that can fail,",
"// and we've already checked above that it was OK sending the test request",
"hc",
".",
"HTTP",
",",
"_",
"=",
"http",
".",
"New",
"(",
"strings",
".",
"TrimRight",
"(",
"remoteHost",
",",
"\"",
"\"",
")",
"+",
"\"",
"\"",
",",
"method",
",",
"header",
")",
"\n",
"hc",
".",
"HTTP",
".",
"SetFormatFunc",
"(",
"formatFunc",
"(",
"hc",
")",
")",
"\n",
"hc",
".",
"SetTemplate",
"(",
"defaultTemplate",
")",
"\n",
"return",
"hc",
",",
"nil",
"\n",
"}"
] | // New returns a new instance of the HipChat logger | [
"New",
"returns",
"a",
"new",
"instance",
"of",
"the",
"HipChat",
"logger"
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/handlers/http/hipchat/hipchat.go#L121-L159 |
4,908 | go-playground/log | handlers/http/hipchat/hipchat.go | SetTemplate | func (hc *HipChat) SetTemplate(htmlTemplate string) {
hc.template = template.Must(template.New("hipchat").Funcs(
template.FuncMap{
"ts": func(e log.Entry) (ts string) {
ts = e.Timestamp.Format(hc.TimestampFormat())
return
},
},
).Parse(htmlTemplate))
} | go | func (hc *HipChat) SetTemplate(htmlTemplate string) {
hc.template = template.Must(template.New("hipchat").Funcs(
template.FuncMap{
"ts": func(e log.Entry) (ts string) {
ts = e.Timestamp.Format(hc.TimestampFormat())
return
},
},
).Parse(htmlTemplate))
} | [
"func",
"(",
"hc",
"*",
"HipChat",
")",
"SetTemplate",
"(",
"htmlTemplate",
"string",
")",
"{",
"hc",
".",
"template",
"=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Funcs",
"(",
"template",
".",
"FuncMap",
"{",
"\"",
"\"",
":",
"func",
"(",
"e",
"log",
".",
"Entry",
")",
"(",
"ts",
"string",
")",
"{",
"ts",
"=",
"e",
".",
"Timestamp",
".",
"Format",
"(",
"hc",
".",
"TimestampFormat",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
",",
"}",
",",
")",
".",
"Parse",
"(",
"htmlTemplate",
")",
")",
"\n",
"}"
] | // SetTemplate sets Hipchats html template to be used for email body | [
"SetTemplate",
"sets",
"Hipchats",
"html",
"template",
"to",
"be",
"used",
"for",
"email",
"body"
] | fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19 | https://github.com/go-playground/log/blob/fdcdf507e3bf20900bc1a44b0cbd73fee5bcbe19/handlers/http/hipchat/hipchat.go#L162-L171 |
4,909 | itsabot/itsabot | core/util.go | RandAlphaNumSeq | func RandAlphaNumSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = alphaNum[rand.Intn(len(alphaNum))]
}
return string(b)
} | go | func RandAlphaNumSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = alphaNum[rand.Intn(len(alphaNum))]
}
return string(b)
} | [
"func",
"RandAlphaNumSeq",
"(",
"n",
"int",
")",
"string",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"n",
")",
"\n",
"for",
"i",
":=",
"range",
"b",
"{",
"b",
"[",
"i",
"]",
"=",
"alphaNum",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"alphaNum",
")",
")",
"]",
"\n",
"}",
"\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] | // RandAlphaNumSeq generates a random sequence of alpha-numeric characters of
// length n. | [
"RandAlphaNumSeq",
"generates",
"a",
"random",
"sequence",
"of",
"alpha",
"-",
"numeric",
"characters",
"of",
"length",
"n",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/util.go#L26-L32 |
4,910 | itsabot/itsabot | shared/datatypes/scheduled_event.go | Send | func (s *ScheduledEvent) Send(c *sms.Conn) error {
switch s.FlexIDType {
case FIDTPhone:
if err := c.Send(s.FlexID, s.Content); err != nil {
return err
}
default:
return fmt.Errorf("unrecognized flexidtype: %d", s.FlexIDType)
}
return nil
} | go | func (s *ScheduledEvent) Send(c *sms.Conn) error {
switch s.FlexIDType {
case FIDTPhone:
if err := c.Send(s.FlexID, s.Content); err != nil {
return err
}
default:
return fmt.Errorf("unrecognized flexidtype: %d", s.FlexIDType)
}
return nil
} | [
"func",
"(",
"s",
"*",
"ScheduledEvent",
")",
"Send",
"(",
"c",
"*",
"sms",
".",
"Conn",
")",
"error",
"{",
"switch",
"s",
".",
"FlexIDType",
"{",
"case",
"FIDTPhone",
":",
"if",
"err",
":=",
"c",
".",
"Send",
"(",
"s",
".",
"FlexID",
",",
"s",
".",
"Content",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"FlexIDType",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Send a scheduled event. Currently only phones are supported. | [
"Send",
"a",
"scheduled",
"event",
".",
"Currently",
"only",
"phones",
"are",
"supported",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/scheduled_event.go#L20-L30 |
4,911 | itsabot/itsabot | core/process.go | preprocess | func preprocess(r *http.Request) (*dt.Msg, error) {
req := &dt.Request{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
log.Info("could not parse empty body", err)
return nil, err
}
sendPostReceiveEvent(&req.CMD)
u, err := dt.GetUser(db, req)
if err != nil {
return nil, err
}
sendPreProcessingEvent(&req.CMD, u)
// TODO trigger training if needed (see buildInput)
return NewMsg(u, req.CMD)
} | go | func preprocess(r *http.Request) (*dt.Msg, error) {
req := &dt.Request{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
log.Info("could not parse empty body", err)
return nil, err
}
sendPostReceiveEvent(&req.CMD)
u, err := dt.GetUser(db, req)
if err != nil {
return nil, err
}
sendPreProcessingEvent(&req.CMD, u)
// TODO trigger training if needed (see buildInput)
return NewMsg(u, req.CMD)
} | [
"func",
"preprocess",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"dt",
".",
"Msg",
",",
"error",
")",
"{",
"req",
":=",
"&",
"dt",
".",
"Request",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sendPostReceiveEvent",
"(",
"&",
"req",
".",
"CMD",
")",
"\n",
"u",
",",
"err",
":=",
"dt",
".",
"GetUser",
"(",
"db",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sendPreProcessingEvent",
"(",
"&",
"req",
".",
"CMD",
",",
"u",
")",
"\n",
"// TODO trigger training if needed (see buildInput)",
"return",
"NewMsg",
"(",
"u",
",",
"req",
".",
"CMD",
")",
"\n",
"}"
] | // preprocess converts a user input into a Msg that's been persisted to the
// database | [
"preprocess",
"converts",
"a",
"user",
"input",
"into",
"a",
"Msg",
"that",
"s",
"been",
"persisted",
"to",
"the",
"database"
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/process.go#L20-L35 |
4,912 | itsabot/itsabot | core/message.go | NewMsg | func NewMsg(u *dt.User, cmd string) (*dt.Msg, error) {
tokens := TokenizeSentence(cmd)
stems := StemTokens(tokens)
si := ner.classifyTokens(tokens)
// Get the intents as determined by each plugin
for pluginID, c := range bClassifiers {
scores, idx, _ := c.ProbScores(stems)
log.Debug("intent score", pluginIntents[pluginID][idx],
scores[idx])
if scores[idx] > 0.7 {
si.Intents = append(si.Intents,
string(pluginIntents[pluginID][idx]))
}
}
m := &dt.Msg{
User: u,
Sentence: cmd,
Tokens: tokens,
Stems: stems,
StructuredInput: si,
}
if err := saveContext(db, m); err != nil {
return nil, err
}
if err := addContext(db, m); err != nil {
return nil, err
}
return m, nil
} | go | func NewMsg(u *dt.User, cmd string) (*dt.Msg, error) {
tokens := TokenizeSentence(cmd)
stems := StemTokens(tokens)
si := ner.classifyTokens(tokens)
// Get the intents as determined by each plugin
for pluginID, c := range bClassifiers {
scores, idx, _ := c.ProbScores(stems)
log.Debug("intent score", pluginIntents[pluginID][idx],
scores[idx])
if scores[idx] > 0.7 {
si.Intents = append(si.Intents,
string(pluginIntents[pluginID][idx]))
}
}
m := &dt.Msg{
User: u,
Sentence: cmd,
Tokens: tokens,
Stems: stems,
StructuredInput: si,
}
if err := saveContext(db, m); err != nil {
return nil, err
}
if err := addContext(db, m); err != nil {
return nil, err
}
return m, nil
} | [
"func",
"NewMsg",
"(",
"u",
"*",
"dt",
".",
"User",
",",
"cmd",
"string",
")",
"(",
"*",
"dt",
".",
"Msg",
",",
"error",
")",
"{",
"tokens",
":=",
"TokenizeSentence",
"(",
"cmd",
")",
"\n",
"stems",
":=",
"StemTokens",
"(",
"tokens",
")",
"\n",
"si",
":=",
"ner",
".",
"classifyTokens",
"(",
"tokens",
")",
"\n\n",
"// Get the intents as determined by each plugin",
"for",
"pluginID",
",",
"c",
":=",
"range",
"bClassifiers",
"{",
"scores",
",",
"idx",
",",
"_",
":=",
"c",
".",
"ProbScores",
"(",
"stems",
")",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"pluginIntents",
"[",
"pluginID",
"]",
"[",
"idx",
"]",
",",
"scores",
"[",
"idx",
"]",
")",
"\n",
"if",
"scores",
"[",
"idx",
"]",
">",
"0.7",
"{",
"si",
".",
"Intents",
"=",
"append",
"(",
"si",
".",
"Intents",
",",
"string",
"(",
"pluginIntents",
"[",
"pluginID",
"]",
"[",
"idx",
"]",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"m",
":=",
"&",
"dt",
".",
"Msg",
"{",
"User",
":",
"u",
",",
"Sentence",
":",
"cmd",
",",
"Tokens",
":",
"tokens",
",",
"Stems",
":",
"stems",
",",
"StructuredInput",
":",
"si",
",",
"}",
"\n",
"if",
"err",
":=",
"saveContext",
"(",
"db",
",",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"addContext",
"(",
"db",
",",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // NewMsg builds a message struct with Tokens, Stems, and a Structured Input. | [
"NewMsg",
"builds",
"a",
"message",
"struct",
"with",
"Tokens",
"Stems",
"and",
"a",
"Structured",
"Input",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/message.go#L9-L39 |
4,913 | itsabot/itsabot | shared/datatypes/message.go | GetMsg | func GetMsg(db *sqlx.DB, id uint64) (*Msg, error) {
q := `SELECT id, sentence, abotsent
FROM messages
WHERE id=$1`
m := &Msg{}
if err := db.Get(m, q, id); err != nil {
return nil, err
}
return m, nil
} | go | func GetMsg(db *sqlx.DB, id uint64) (*Msg, error) {
q := `SELECT id, sentence, abotsent
FROM messages
WHERE id=$1`
m := &Msg{}
if err := db.Get(m, q, id); err != nil {
return nil, err
}
return m, nil
} | [
"func",
"GetMsg",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"id",
"uint64",
")",
"(",
"*",
"Msg",
",",
"error",
")",
"{",
"q",
":=",
"`SELECT id, sentence, abotsent\n\t FROM messages\n\t WHERE id=$1`",
"\n",
"m",
":=",
"&",
"Msg",
"{",
"}",
"\n",
"if",
"err",
":=",
"db",
".",
"Get",
"(",
"m",
",",
"q",
",",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // GetMsg returns a message for a given message ID. | [
"GetMsg",
"returns",
"a",
"message",
"for",
"a",
"given",
"message",
"ID",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/message.go#L35-L44 |
4,914 | itsabot/itsabot | shared/datatypes/message.go | Update | func (m *Msg) Update(db *sqlx.DB) error {
q := `UPDATE messages SET needstraining=$1 WHERE id=$2`
if _, err := db.Exec(q, m.NeedsTraining, m.ID); err != nil {
return err
}
return nil
} | go | func (m *Msg) Update(db *sqlx.DB) error {
q := `UPDATE messages SET needstraining=$1 WHERE id=$2`
if _, err := db.Exec(q, m.NeedsTraining, m.ID); err != nil {
return err
}
return nil
} | [
"func",
"(",
"m",
"*",
"Msg",
")",
"Update",
"(",
"db",
"*",
"sqlx",
".",
"DB",
")",
"error",
"{",
"q",
":=",
"`UPDATE messages SET needstraining=$1 WHERE id=$2`",
"\n",
"if",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"q",
",",
"m",
".",
"NeedsTraining",
",",
"m",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Update a message as needing training. | [
"Update",
"a",
"message",
"as",
"needing",
"training",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/message.go#L47-L53 |
4,915 | itsabot/itsabot | shared/datatypes/message.go | Save | func (m *Msg) Save(db *sqlx.DB) error {
var pluginName string
if m.Plugin != nil {
pluginName = m.Plugin.Config.Name
}
q := `INSERT INTO messages
(userid, sentence, plugin, route, abotsent, needstraining, flexid,
flexidtype, trained)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id`
row := db.QueryRowx(q, m.User.ID, m.Sentence, pluginName, m.Route,
m.AbotSent, m.NeedsTraining, m.User.FlexID, m.User.FlexIDType,
m.Trained)
if err := row.Scan(&m.ID); err != nil {
return err
}
return nil
} | go | func (m *Msg) Save(db *sqlx.DB) error {
var pluginName string
if m.Plugin != nil {
pluginName = m.Plugin.Config.Name
}
q := `INSERT INTO messages
(userid, sentence, plugin, route, abotsent, needstraining, flexid,
flexidtype, trained)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id`
row := db.QueryRowx(q, m.User.ID, m.Sentence, pluginName, m.Route,
m.AbotSent, m.NeedsTraining, m.User.FlexID, m.User.FlexIDType,
m.Trained)
if err := row.Scan(&m.ID); err != nil {
return err
}
return nil
} | [
"func",
"(",
"m",
"*",
"Msg",
")",
"Save",
"(",
"db",
"*",
"sqlx",
".",
"DB",
")",
"error",
"{",
"var",
"pluginName",
"string",
"\n",
"if",
"m",
".",
"Plugin",
"!=",
"nil",
"{",
"pluginName",
"=",
"m",
".",
"Plugin",
".",
"Config",
".",
"Name",
"\n",
"}",
"\n",
"q",
":=",
"`INSERT INTO messages\n\t (userid, sentence, plugin, route, abotsent, needstraining, flexid,\n\t\tflexidtype, trained)\n\t VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id`",
"\n",
"row",
":=",
"db",
".",
"QueryRowx",
"(",
"q",
",",
"m",
".",
"User",
".",
"ID",
",",
"m",
".",
"Sentence",
",",
"pluginName",
",",
"m",
".",
"Route",
",",
"m",
".",
"AbotSent",
",",
"m",
".",
"NeedsTraining",
",",
"m",
".",
"User",
".",
"FlexID",
",",
"m",
".",
"User",
".",
"FlexIDType",
",",
"m",
".",
"Trained",
")",
"\n",
"if",
"err",
":=",
"row",
".",
"Scan",
"(",
"&",
"m",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Save a message to the database, updating the message ID. | [
"Save",
"a",
"message",
"to",
"the",
"database",
"updating",
"the",
"message",
"ID",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/message.go#L56-L72 |
4,916 | itsabot/itsabot | shared/datatypes/message.go | GetLastPlugin | func (m *Msg) GetLastPlugin(db *sqlx.DB) (string, string, error) {
var res struct {
Plugin string
Route string
}
var err error
if m.User.ID > 0 {
q := `SELECT route, plugin FROM messages
WHERE userid=$1 AND abotsent IS FALSE
ORDER BY createdat DESC`
err = db.Get(&res, q, m.User.ID)
} else {
q := `SELECT route, plugin FROM messages
WHERE flexid=$1 AND flexidtype=$2 AND abotsent IS FALSE
ORDER BY createdat DESC`
err = db.Get(&res, q, m.User.FlexID, m.User.FlexIDType)
}
if err != nil && err != sql.ErrNoRows {
return "", "", err
}
return res.Plugin, res.Route, nil
} | go | func (m *Msg) GetLastPlugin(db *sqlx.DB) (string, string, error) {
var res struct {
Plugin string
Route string
}
var err error
if m.User.ID > 0 {
q := `SELECT route, plugin FROM messages
WHERE userid=$1 AND abotsent IS FALSE
ORDER BY createdat DESC`
err = db.Get(&res, q, m.User.ID)
} else {
q := `SELECT route, plugin FROM messages
WHERE flexid=$1 AND flexidtype=$2 AND abotsent IS FALSE
ORDER BY createdat DESC`
err = db.Get(&res, q, m.User.FlexID, m.User.FlexIDType)
}
if err != nil && err != sql.ErrNoRows {
return "", "", err
}
return res.Plugin, res.Route, nil
} | [
"func",
"(",
"m",
"*",
"Msg",
")",
"GetLastPlugin",
"(",
"db",
"*",
"sqlx",
".",
"DB",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"var",
"res",
"struct",
"{",
"Plugin",
"string",
"\n",
"Route",
"string",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"m",
".",
"User",
".",
"ID",
">",
"0",
"{",
"q",
":=",
"`SELECT route, plugin FROM messages\n\t\t WHERE userid=$1 AND abotsent IS FALSE\n\t\t ORDER BY createdat DESC`",
"\n",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"res",
",",
"q",
",",
"m",
".",
"User",
".",
"ID",
")",
"\n",
"}",
"else",
"{",
"q",
":=",
"`SELECT route, plugin FROM messages\n\t\t WHERE flexid=$1 AND flexidtype=$2 AND abotsent IS FALSE\n\t\t ORDER BY createdat DESC`",
"\n",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"res",
",",
"q",
",",
"m",
".",
"User",
".",
"FlexID",
",",
"m",
".",
"User",
".",
"FlexIDType",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"sql",
".",
"ErrNoRows",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
".",
"Plugin",
",",
"res",
".",
"Route",
",",
"nil",
"\n",
"}"
] | // GetLastPlugin for a given user so the previous plugin can be called again if
// no new trigger is detected. | [
"GetLastPlugin",
"for",
"a",
"given",
"user",
"so",
"the",
"previous",
"plugin",
"can",
"be",
"called",
"again",
"if",
"no",
"new",
"trigger",
"is",
"detected",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/message.go#L76-L97 |
4,917 | itsabot/itsabot | shared/interface/emailsender/emailsender.go | Open | func Open(driverName, auth string) (*Conn, error) {
driversMu.RLock()
driveri, ok := drivers[driverName]
driversMu.RUnlock()
if !ok {
return nil, fmt.Errorf("sms: unknown driver %q (forgotten import?)",
driverName)
}
conn, err := driveri.Open(auth)
if err != nil {
return nil, err
}
c := &Conn{
driver: driveri,
conn: conn,
}
return c, nil
} | go | func Open(driverName, auth string) (*Conn, error) {
driversMu.RLock()
driveri, ok := drivers[driverName]
driversMu.RUnlock()
if !ok {
return nil, fmt.Errorf("sms: unknown driver %q (forgotten import?)",
driverName)
}
conn, err := driveri.Open(auth)
if err != nil {
return nil, err
}
c := &Conn{
driver: driveri,
conn: conn,
}
return c, nil
} | [
"func",
"Open",
"(",
"driverName",
",",
"auth",
"string",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"driversMu",
".",
"RLock",
"(",
")",
"\n",
"driveri",
",",
"ok",
":=",
"drivers",
"[",
"driverName",
"]",
"\n",
"driversMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"driverName",
")",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"driveri",
".",
"Open",
"(",
"auth",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"c",
":=",
"&",
"Conn",
"{",
"driver",
":",
"driveri",
",",
"conn",
":",
"conn",
",",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // Open a connection to a registered driver. | [
"Open",
"a",
"connection",
"to",
"a",
"registered",
"driver",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/interface/emailsender/emailsender.go#L52-L69 |
4,918 | itsabot/itsabot | shared/interface/emailsender/emailsender.go | SendHTML | func (c *Conn) SendHTML(to []string, from, subj, html string) error {
return c.conn.SendHTML(to, from, subj, html)
} | go | func (c *Conn) SendHTML(to []string, from, subj, html string) error {
return c.conn.SendHTML(to, from, subj, html)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"SendHTML",
"(",
"to",
"[",
"]",
"string",
",",
"from",
",",
"subj",
",",
"html",
"string",
")",
"error",
"{",
"return",
"c",
".",
"conn",
".",
"SendHTML",
"(",
"to",
",",
"from",
",",
"subj",
",",
"html",
")",
"\n",
"}"
] | // SendHTML email through the opened driver connection. | [
"SendHTML",
"email",
"through",
"the",
"opened",
"driver",
"connection",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/interface/emailsender/emailsender.go#L72-L74 |
4,919 | itsabot/itsabot | shared/interface/emailsender/emailsender.go | SendPlainText | func (c *Conn) SendPlainText(to []string, from, subj, plaintext string) error {
return c.conn.SendPlainText(to, from, subj, plaintext)
} | go | func (c *Conn) SendPlainText(to []string, from, subj, plaintext string) error {
return c.conn.SendPlainText(to, from, subj, plaintext)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"SendPlainText",
"(",
"to",
"[",
"]",
"string",
",",
"from",
",",
"subj",
",",
"plaintext",
"string",
")",
"error",
"{",
"return",
"c",
".",
"conn",
".",
"SendPlainText",
"(",
"to",
",",
"from",
",",
"subj",
",",
"plaintext",
")",
"\n",
"}"
] | // SendPlainText email through the opened driver connection. | [
"SendPlainText",
"email",
"through",
"the",
"opened",
"driver",
"connection",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/interface/emailsender/emailsender.go#L77-L79 |
4,920 | itsabot/itsabot | core/context.go | saveContext | func saveContext(db *sqlx.DB, in *dt.Msg) error {
if err := saveTimeContext(db, in); err != nil {
return err
}
if err := savePeopleContext(db, in); err != nil {
return err
}
return nil
} | go | func saveContext(db *sqlx.DB, in *dt.Msg) error {
if err := saveTimeContext(db, in); err != nil {
return err
}
if err := savePeopleContext(db, in); err != nil {
return err
}
return nil
} | [
"func",
"saveContext",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"in",
"*",
"dt",
".",
"Msg",
")",
"error",
"{",
"if",
"err",
":=",
"saveTimeContext",
"(",
"db",
",",
"in",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"savePeopleContext",
"(",
"db",
",",
"in",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // saveContext records context in the database across multiple categories. | [
"saveContext",
"records",
"context",
"in",
"the",
"database",
"across",
"multiple",
"categories",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/context.go#L22-L30 |
4,921 | itsabot/itsabot | core/context.go | saveTimeContext | func saveTimeContext(db *sqlx.DB, in *dt.Msg) error {
if len(in.StructuredInput.Times) == 0 {
return nil
}
byt, err := json.Marshal(in.StructuredInput.Times)
if err != nil {
return err
}
if in.User.ID > 0 {
q := `INSERT INTO states (key, value, userid, pluginname)
VALUES ($1, $2, $3, '')
ON CONFLICT (userid, pluginname, key)
DO UPDATE SET value=$2`
_, err = db.Exec(q, keyContextTime, byt, in.User.ID)
} else {
q := `INSERT INTO states
(key, value, flexid, flexidtype, pluginname)
VALUES ($1, $2, $3, $4, '')
ON CONFLICT (flexid, flexidtype, pluginname, key)
DO UPDATE SET value=$2`
_, err = db.Exec(q, keyContextTime, byt, in.User.FlexID,
in.User.FlexIDType)
}
if err != nil {
return err
}
return nil
} | go | func saveTimeContext(db *sqlx.DB, in *dt.Msg) error {
if len(in.StructuredInput.Times) == 0 {
return nil
}
byt, err := json.Marshal(in.StructuredInput.Times)
if err != nil {
return err
}
if in.User.ID > 0 {
q := `INSERT INTO states (key, value, userid, pluginname)
VALUES ($1, $2, $3, '')
ON CONFLICT (userid, pluginname, key)
DO UPDATE SET value=$2`
_, err = db.Exec(q, keyContextTime, byt, in.User.ID)
} else {
q := `INSERT INTO states
(key, value, flexid, flexidtype, pluginname)
VALUES ($1, $2, $3, $4, '')
ON CONFLICT (flexid, flexidtype, pluginname, key)
DO UPDATE SET value=$2`
_, err = db.Exec(q, keyContextTime, byt, in.User.FlexID,
in.User.FlexIDType)
}
if err != nil {
return err
}
return nil
} | [
"func",
"saveTimeContext",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"in",
"*",
"dt",
".",
"Msg",
")",
"error",
"{",
"if",
"len",
"(",
"in",
".",
"StructuredInput",
".",
"Times",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"byt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"in",
".",
"StructuredInput",
".",
"Times",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"in",
".",
"User",
".",
"ID",
">",
"0",
"{",
"q",
":=",
"`INSERT INTO states (key, value, userid, pluginname)\n\t\t VALUES ($1, $2, $3, '')\n\t\t ON CONFLICT (userid, pluginname, key)\n\t\t DO UPDATE SET value=$2`",
"\n",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"q",
",",
"keyContextTime",
",",
"byt",
",",
"in",
".",
"User",
".",
"ID",
")",
"\n",
"}",
"else",
"{",
"q",
":=",
"`INSERT INTO states\n\t\t (key, value, flexid, flexidtype, pluginname)\n\t\t VALUES ($1, $2, $3, $4, '')\n\t\t ON CONFLICT (flexid, flexidtype, pluginname, key)\n\t\t DO UPDATE SET value=$2`",
"\n",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"q",
",",
"keyContextTime",
",",
"byt",
",",
"in",
".",
"User",
".",
"FlexID",
",",
"in",
".",
"User",
".",
"FlexIDType",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // saveTimeContext records contextual information about the time being
// discussed, enabling Abot to replace things like "then" with the time it
// should represent. | [
"saveTimeContext",
"records",
"contextual",
"information",
"about",
"the",
"time",
"being",
"discussed",
"enabling",
"Abot",
"to",
"replace",
"things",
"like",
"then",
"with",
"the",
"time",
"it",
"should",
"represent",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/context.go#L35-L62 |
4,922 | itsabot/itsabot | core/context.go | savePeopleContext | func savePeopleContext(db *sqlx.DB, in *dt.Msg) error {
if len(in.StructuredInput.People) == 0 {
return nil
}
byt, err := json.Marshal(in.StructuredInput.People)
if err != nil {
return err
}
if in.User.ID > 0 {
q := `INSERT INTO states (key, value, userid, pluginname)
VALUES ($1, $2, $3, '')
ON CONFLICT (userid, pluginname, key)
DO UPDATE SET value=$2`
_, err = db.Exec(q, keyContextPeople, byt, in.User.ID)
} else {
q := `INSERT INTO states
(key, value, flexid, flexidtype, pluginname)
VALUES ($1, $2, $3, $4, '')
ON CONFLICT (flexid, flexidtype, pluginname, key)
DO UPDATE SET value=$2`
_, err = db.Exec(q, keyContextPeople, byt, in.User.FlexID,
in.User.FlexIDType)
}
if err != nil {
return err
}
return nil
} | go | func savePeopleContext(db *sqlx.DB, in *dt.Msg) error {
if len(in.StructuredInput.People) == 0 {
return nil
}
byt, err := json.Marshal(in.StructuredInput.People)
if err != nil {
return err
}
if in.User.ID > 0 {
q := `INSERT INTO states (key, value, userid, pluginname)
VALUES ($1, $2, $3, '')
ON CONFLICT (userid, pluginname, key)
DO UPDATE SET value=$2`
_, err = db.Exec(q, keyContextPeople, byt, in.User.ID)
} else {
q := `INSERT INTO states
(key, value, flexid, flexidtype, pluginname)
VALUES ($1, $2, $3, $4, '')
ON CONFLICT (flexid, flexidtype, pluginname, key)
DO UPDATE SET value=$2`
_, err = db.Exec(q, keyContextPeople, byt, in.User.FlexID,
in.User.FlexIDType)
}
if err != nil {
return err
}
return nil
} | [
"func",
"savePeopleContext",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"in",
"*",
"dt",
".",
"Msg",
")",
"error",
"{",
"if",
"len",
"(",
"in",
".",
"StructuredInput",
".",
"People",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"byt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"in",
".",
"StructuredInput",
".",
"People",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"in",
".",
"User",
".",
"ID",
">",
"0",
"{",
"q",
":=",
"`INSERT INTO states (key, value, userid, pluginname)\n\t\t VALUES ($1, $2, $3, '')\n\t\t ON CONFLICT (userid, pluginname, key)\n\t\t DO UPDATE SET value=$2`",
"\n",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"q",
",",
"keyContextPeople",
",",
"byt",
",",
"in",
".",
"User",
".",
"ID",
")",
"\n",
"}",
"else",
"{",
"q",
":=",
"`INSERT INTO states\n\t\t (key, value, flexid, flexidtype, pluginname)\n\t\t VALUES ($1, $2, $3, $4, '')\n\t\t ON CONFLICT (flexid, flexidtype, pluginname, key)\n\t\t DO UPDATE SET value=$2`",
"\n",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"q",
",",
"keyContextPeople",
",",
"byt",
",",
"in",
".",
"User",
".",
"FlexID",
",",
"in",
".",
"User",
".",
"FlexIDType",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // savePeopleContext records contextual information about people being
// discussed, enabling Abot to replace things like "him", "her", or "they" with
// the names the pronouns represent. | [
"savePeopleContext",
"records",
"contextual",
"information",
"about",
"people",
"being",
"discussed",
"enabling",
"Abot",
"to",
"replace",
"things",
"like",
"him",
"her",
"or",
"they",
"with",
"the",
"names",
"the",
"pronouns",
"represent",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/context.go#L67-L94 |
4,923 | itsabot/itsabot | core/context.go | addTimeContext | func addTimeContext(db *sqlx.DB, in *dt.Msg) error {
var addContext bool
for _, stem := range in.Stems {
if stem == "then" {
addContext = true
break
}
}
if !addContext {
return nil
}
var byt []byte
var err error
if in.User.ID > 0 {
q := `SELECT value FROM states WHERE userid=$1 AND key=$2`
err = db.Get(&byt, q, in.User.ID, keyContextTime)
} else {
q := `SELECT value FROM states
WHERE flexid=$1 AND flexidtype=$2 AND key=$3`
err = db.Get(&byt, q, in.User.FlexID, in.User.FlexIDType,
keyContextTime)
}
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
var times []time.Time
if err = json.Unmarshal(byt, ×); err != nil {
return err
}
in.StructuredInput.Times = times
return nil
} | go | func addTimeContext(db *sqlx.DB, in *dt.Msg) error {
var addContext bool
for _, stem := range in.Stems {
if stem == "then" {
addContext = true
break
}
}
if !addContext {
return nil
}
var byt []byte
var err error
if in.User.ID > 0 {
q := `SELECT value FROM states WHERE userid=$1 AND key=$2`
err = db.Get(&byt, q, in.User.ID, keyContextTime)
} else {
q := `SELECT value FROM states
WHERE flexid=$1 AND flexidtype=$2 AND key=$3`
err = db.Get(&byt, q, in.User.FlexID, in.User.FlexIDType,
keyContextTime)
}
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
var times []time.Time
if err = json.Unmarshal(byt, ×); err != nil {
return err
}
in.StructuredInput.Times = times
return nil
} | [
"func",
"addTimeContext",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"in",
"*",
"dt",
".",
"Msg",
")",
"error",
"{",
"var",
"addContext",
"bool",
"\n",
"for",
"_",
",",
"stem",
":=",
"range",
"in",
".",
"Stems",
"{",
"if",
"stem",
"==",
"\"",
"\"",
"{",
"addContext",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"addContext",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"byt",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n",
"if",
"in",
".",
"User",
".",
"ID",
">",
"0",
"{",
"q",
":=",
"`SELECT value FROM states WHERE userid=$1 AND key=$2`",
"\n",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"byt",
",",
"q",
",",
"in",
".",
"User",
".",
"ID",
",",
"keyContextTime",
")",
"\n",
"}",
"else",
"{",
"q",
":=",
"`SELECT value FROM states\n\t\t WHERE flexid=$1 AND flexidtype=$2 AND key=$3`",
"\n",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"byt",
",",
"q",
",",
"in",
".",
"User",
".",
"FlexID",
",",
"in",
".",
"User",
".",
"FlexIDType",
",",
"keyContextTime",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"times",
"[",
"]",
"time",
".",
"Time",
"\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"byt",
",",
"&",
"times",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"in",
".",
"StructuredInput",
".",
"Times",
"=",
"times",
"\n",
"return",
"nil",
"\n",
"}"
] | // addTimeContext adds a time context to a Message if the word "then" is found. | [
"addTimeContext",
"adds",
"a",
"time",
"context",
"to",
"a",
"Message",
"if",
"the",
"word",
"then",
"is",
"found",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/context.go#L114-L148 |
4,924 | itsabot/itsabot | core/context.go | addPeopleContext | func addPeopleContext(db *sqlx.DB, in *dt.Msg) error {
var addContext, singular bool
var sex dt.Sex
for _, stem := range in.Stems {
switch stem {
case "us":
addContext = true
case "him", "he":
addContext, singular = true, true
if sex == dt.SexFemale {
sex = dt.SexEither
} else if sex != dt.SexEither {
sex = dt.SexMale
}
case "her", "she":
addContext, singular = true, true
if sex == dt.SexMale {
sex = dt.SexEither
} else if sex != dt.SexEither {
sex = dt.SexFemale
}
case "them":
addContext = true
sex = dt.SexEither
}
}
if !addContext {
return nil
}
var byt []byte
var err error
if in.User.ID > 0 {
q := `SELECT value FROM states WHERE userid=$1 AND key=$2`
err = db.Get(&byt, q, in.User.ID, keyContextPeople)
} else {
q := `SELECT value FROM states
WHERE flexid=$1 AND flexidtype=$2 AND key=$3`
err = db.Get(&byt, q, in.User.FlexID, in.User.FlexIDType,
keyContextPeople)
}
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
var people []dt.Person
if err = json.Unmarshal(byt, &people); err != nil {
return err
}
// Filter our people in context by criteria, like sex.
if !singular {
in.StructuredInput.People = people
return nil
}
if sex == dt.SexEither {
// To reach this point, we have at least one person in context.
in.StructuredInput.People = []dt.Person{people[0]}
return nil
}
for _, person := range people {
if person.Sex == sex {
in.StructuredInput.People = []dt.Person{person}
break
}
}
return nil
} | go | func addPeopleContext(db *sqlx.DB, in *dt.Msg) error {
var addContext, singular bool
var sex dt.Sex
for _, stem := range in.Stems {
switch stem {
case "us":
addContext = true
case "him", "he":
addContext, singular = true, true
if sex == dt.SexFemale {
sex = dt.SexEither
} else if sex != dt.SexEither {
sex = dt.SexMale
}
case "her", "she":
addContext, singular = true, true
if sex == dt.SexMale {
sex = dt.SexEither
} else if sex != dt.SexEither {
sex = dt.SexFemale
}
case "them":
addContext = true
sex = dt.SexEither
}
}
if !addContext {
return nil
}
var byt []byte
var err error
if in.User.ID > 0 {
q := `SELECT value FROM states WHERE userid=$1 AND key=$2`
err = db.Get(&byt, q, in.User.ID, keyContextPeople)
} else {
q := `SELECT value FROM states
WHERE flexid=$1 AND flexidtype=$2 AND key=$3`
err = db.Get(&byt, q, in.User.FlexID, in.User.FlexIDType,
keyContextPeople)
}
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
var people []dt.Person
if err = json.Unmarshal(byt, &people); err != nil {
return err
}
// Filter our people in context by criteria, like sex.
if !singular {
in.StructuredInput.People = people
return nil
}
if sex == dt.SexEither {
// To reach this point, we have at least one person in context.
in.StructuredInput.People = []dt.Person{people[0]}
return nil
}
for _, person := range people {
if person.Sex == sex {
in.StructuredInput.People = []dt.Person{person}
break
}
}
return nil
} | [
"func",
"addPeopleContext",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"in",
"*",
"dt",
".",
"Msg",
")",
"error",
"{",
"var",
"addContext",
",",
"singular",
"bool",
"\n",
"var",
"sex",
"dt",
".",
"Sex",
"\n",
"for",
"_",
",",
"stem",
":=",
"range",
"in",
".",
"Stems",
"{",
"switch",
"stem",
"{",
"case",
"\"",
"\"",
":",
"addContext",
"=",
"true",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"addContext",
",",
"singular",
"=",
"true",
",",
"true",
"\n",
"if",
"sex",
"==",
"dt",
".",
"SexFemale",
"{",
"sex",
"=",
"dt",
".",
"SexEither",
"\n",
"}",
"else",
"if",
"sex",
"!=",
"dt",
".",
"SexEither",
"{",
"sex",
"=",
"dt",
".",
"SexMale",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"addContext",
",",
"singular",
"=",
"true",
",",
"true",
"\n",
"if",
"sex",
"==",
"dt",
".",
"SexMale",
"{",
"sex",
"=",
"dt",
".",
"SexEither",
"\n",
"}",
"else",
"if",
"sex",
"!=",
"dt",
".",
"SexEither",
"{",
"sex",
"=",
"dt",
".",
"SexFemale",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"addContext",
"=",
"true",
"\n",
"sex",
"=",
"dt",
".",
"SexEither",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"addContext",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"byt",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n",
"if",
"in",
".",
"User",
".",
"ID",
">",
"0",
"{",
"q",
":=",
"`SELECT value FROM states WHERE userid=$1 AND key=$2`",
"\n",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"byt",
",",
"q",
",",
"in",
".",
"User",
".",
"ID",
",",
"keyContextPeople",
")",
"\n",
"}",
"else",
"{",
"q",
":=",
"`SELECT value FROM states\n\t\t WHERE flexid=$1 AND flexidtype=$2 AND key=$3`",
"\n",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"byt",
",",
"q",
",",
"in",
".",
"User",
".",
"FlexID",
",",
"in",
".",
"User",
".",
"FlexIDType",
",",
"keyContextPeople",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"people",
"[",
"]",
"dt",
".",
"Person",
"\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"byt",
",",
"&",
"people",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Filter our people in context by criteria, like sex.",
"if",
"!",
"singular",
"{",
"in",
".",
"StructuredInput",
".",
"People",
"=",
"people",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"sex",
"==",
"dt",
".",
"SexEither",
"{",
"// To reach this point, we have at least one person in context.",
"in",
".",
"StructuredInput",
".",
"People",
"=",
"[",
"]",
"dt",
".",
"Person",
"{",
"people",
"[",
"0",
"]",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"person",
":=",
"range",
"people",
"{",
"if",
"person",
".",
"Sex",
"==",
"sex",
"{",
"in",
".",
"StructuredInput",
".",
"People",
"=",
"[",
"]",
"dt",
".",
"Person",
"{",
"person",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // addPeopleContext adds people based on context to the sentence when
// appropriate pronouns are found, like "us", "him", "her", or "them". | [
"addPeopleContext",
"adds",
"people",
"based",
"on",
"context",
"to",
"the",
"sentence",
"when",
"appropriate",
"pronouns",
"are",
"found",
"like",
"us",
"him",
"her",
"or",
"them",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/context.go#L152-L220 |
4,925 | itsabot/itsabot | core/nlp.go | classifyTokens | func (c classifier) classifyTokens(tokens []string) *dt.StructuredInput {
var s dt.StructuredInput
var sections []string
for _, t := range tokens {
var found bool
lower := strings.ToLower(t)
_, exists := c["C"+lower]
if exists {
s.Commands = append(s.Commands, lower)
found = true
}
_, exists = c["O"+lower]
if exists {
s.Objects = append(s.Objects, lower)
found = true
}
// Identify the sex of any people being discussed.
var sex dt.Sex
_, exists = c["PM"+lower]
if exists {
_, exists = c["PF"+lower]
if exists {
sex = dt.SexEither
} else {
sex = dt.SexMale
}
person := dt.Person{
Name: t,
Sex: sex,
}
s.People = append(s.People, person)
found = true
}
// If we haven't found a male or male+female name yet, check
// for female.
if sex == dt.SexInvalid {
_, exists = c["PF"+lower]
if exists {
person := dt.Person{
Name: t,
Sex: dt.SexFemale,
}
s.People = append(s.People, person)
found = true
}
}
// Each time we find an object, add a separator to sections,
// enabling us to check for times only along continuous
// stretches of a sentence (i.e. a single time won't appear on
// either side of the word "Jim" or "Bring")
if found || len(sections) == 0 {
sections = append(sections, t)
} else {
switch t {
case ".", ",", ";", "?", "-", "_", "=", "+", "#", "@",
"!", "$", "%", "^", "&", "*", "(", ")", "'":
continue
}
sections[len(sections)-1] += " " + t
}
}
for _, sec := range sections {
if len(sec) == 0 {
continue
}
s.Times = append(s.Times, timeparse.Parse(sec)...)
}
return &s
} | go | func (c classifier) classifyTokens(tokens []string) *dt.StructuredInput {
var s dt.StructuredInput
var sections []string
for _, t := range tokens {
var found bool
lower := strings.ToLower(t)
_, exists := c["C"+lower]
if exists {
s.Commands = append(s.Commands, lower)
found = true
}
_, exists = c["O"+lower]
if exists {
s.Objects = append(s.Objects, lower)
found = true
}
// Identify the sex of any people being discussed.
var sex dt.Sex
_, exists = c["PM"+lower]
if exists {
_, exists = c["PF"+lower]
if exists {
sex = dt.SexEither
} else {
sex = dt.SexMale
}
person := dt.Person{
Name: t,
Sex: sex,
}
s.People = append(s.People, person)
found = true
}
// If we haven't found a male or male+female name yet, check
// for female.
if sex == dt.SexInvalid {
_, exists = c["PF"+lower]
if exists {
person := dt.Person{
Name: t,
Sex: dt.SexFemale,
}
s.People = append(s.People, person)
found = true
}
}
// Each time we find an object, add a separator to sections,
// enabling us to check for times only along continuous
// stretches of a sentence (i.e. a single time won't appear on
// either side of the word "Jim" or "Bring")
if found || len(sections) == 0 {
sections = append(sections, t)
} else {
switch t {
case ".", ",", ";", "?", "-", "_", "=", "+", "#", "@",
"!", "$", "%", "^", "&", "*", "(", ")", "'":
continue
}
sections[len(sections)-1] += " " + t
}
}
for _, sec := range sections {
if len(sec) == 0 {
continue
}
s.Times = append(s.Times, timeparse.Parse(sec)...)
}
return &s
} | [
"func",
"(",
"c",
"classifier",
")",
"classifyTokens",
"(",
"tokens",
"[",
"]",
"string",
")",
"*",
"dt",
".",
"StructuredInput",
"{",
"var",
"s",
"dt",
".",
"StructuredInput",
"\n",
"var",
"sections",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"tokens",
"{",
"var",
"found",
"bool",
"\n",
"lower",
":=",
"strings",
".",
"ToLower",
"(",
"t",
")",
"\n",
"_",
",",
"exists",
":=",
"c",
"[",
"\"",
"\"",
"+",
"lower",
"]",
"\n",
"if",
"exists",
"{",
"s",
".",
"Commands",
"=",
"append",
"(",
"s",
".",
"Commands",
",",
"lower",
")",
"\n",
"found",
"=",
"true",
"\n",
"}",
"\n",
"_",
",",
"exists",
"=",
"c",
"[",
"\"",
"\"",
"+",
"lower",
"]",
"\n",
"if",
"exists",
"{",
"s",
".",
"Objects",
"=",
"append",
"(",
"s",
".",
"Objects",
",",
"lower",
")",
"\n",
"found",
"=",
"true",
"\n",
"}",
"\n\n",
"// Identify the sex of any people being discussed.",
"var",
"sex",
"dt",
".",
"Sex",
"\n",
"_",
",",
"exists",
"=",
"c",
"[",
"\"",
"\"",
"+",
"lower",
"]",
"\n",
"if",
"exists",
"{",
"_",
",",
"exists",
"=",
"c",
"[",
"\"",
"\"",
"+",
"lower",
"]",
"\n",
"if",
"exists",
"{",
"sex",
"=",
"dt",
".",
"SexEither",
"\n",
"}",
"else",
"{",
"sex",
"=",
"dt",
".",
"SexMale",
"\n",
"}",
"\n",
"person",
":=",
"dt",
".",
"Person",
"{",
"Name",
":",
"t",
",",
"Sex",
":",
"sex",
",",
"}",
"\n",
"s",
".",
"People",
"=",
"append",
"(",
"s",
".",
"People",
",",
"person",
")",
"\n",
"found",
"=",
"true",
"\n",
"}",
"\n\n",
"// If we haven't found a male or male+female name yet, check",
"// for female.",
"if",
"sex",
"==",
"dt",
".",
"SexInvalid",
"{",
"_",
",",
"exists",
"=",
"c",
"[",
"\"",
"\"",
"+",
"lower",
"]",
"\n",
"if",
"exists",
"{",
"person",
":=",
"dt",
".",
"Person",
"{",
"Name",
":",
"t",
",",
"Sex",
":",
"dt",
".",
"SexFemale",
",",
"}",
"\n",
"s",
".",
"People",
"=",
"append",
"(",
"s",
".",
"People",
",",
"person",
")",
"\n",
"found",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Each time we find an object, add a separator to sections,",
"// enabling us to check for times only along continuous",
"// stretches of a sentence (i.e. a single time won't appear on",
"// either side of the word \"Jim\" or \"Bring\")",
"if",
"found",
"||",
"len",
"(",
"sections",
")",
"==",
"0",
"{",
"sections",
"=",
"append",
"(",
"sections",
",",
"t",
")",
"\n",
"}",
"else",
"{",
"switch",
"t",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"continue",
"\n",
"}",
"\n",
"sections",
"[",
"len",
"(",
"sections",
")",
"-",
"1",
"]",
"+=",
"\"",
"\"",
"+",
"t",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"sec",
":=",
"range",
"sections",
"{",
"if",
"len",
"(",
"sec",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"s",
".",
"Times",
"=",
"append",
"(",
"s",
".",
"Times",
",",
"timeparse",
".",
"Parse",
"(",
"sec",
")",
"...",
")",
"\n",
"}",
"\n",
"return",
"&",
"s",
"\n",
"}"
] | // classifyTokens builds a StructuredInput from a tokenized sentence. | [
"classifyTokens",
"builds",
"a",
"StructuredInput",
"from",
"a",
"tokenized",
"sentence",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/nlp.go#L24-L95 |
4,926 | itsabot/itsabot | core/nlp.go | buildOffensiveMap | func buildOffensiveMap() (map[string]struct{}, error) {
o := map[string]struct{}{}
p := filepath.Join("data", "offensive.txt")
fi, err := os.Open(p)
if err != nil {
return o, err
}
scanner := bufio.NewScanner(fi)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
o[scanner.Text()] = struct{}{}
}
err = fi.Close()
return o, err
} | go | func buildOffensiveMap() (map[string]struct{}, error) {
o := map[string]struct{}{}
p := filepath.Join("data", "offensive.txt")
fi, err := os.Open(p)
if err != nil {
return o, err
}
scanner := bufio.NewScanner(fi)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
o[scanner.Text()] = struct{}{}
}
err = fi.Close()
return o, err
} | [
"func",
"buildOffensiveMap",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"error",
")",
"{",
"o",
":=",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"p",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"fi",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"o",
",",
"err",
"\n",
"}",
"\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"fi",
")",
"\n",
"scanner",
".",
"Split",
"(",
"bufio",
".",
"ScanLines",
")",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"o",
"[",
"scanner",
".",
"Text",
"(",
")",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"err",
"=",
"fi",
".",
"Close",
"(",
")",
"\n",
"return",
"o",
",",
"err",
"\n",
"}"
] | // buildOffensiveMap creates a map of offensive terms for which Abot will refuse
// to respond. This helps ensure that users are somewhat respectful to Abot and
// her human trainers, since sentences caught by the OffensiveMap are rejected
// before any human ever sees them. | [
"buildOffensiveMap",
"creates",
"a",
"map",
"of",
"offensive",
"terms",
"for",
"which",
"Abot",
"will",
"refuse",
"to",
"respond",
".",
"This",
"helps",
"ensure",
"that",
"users",
"are",
"somewhat",
"respectful",
"to",
"Abot",
"and",
"her",
"human",
"trainers",
"since",
"sentences",
"caught",
"by",
"the",
"OffensiveMap",
"are",
"rejected",
"before",
"any",
"human",
"ever",
"sees",
"them",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/nlp.go#L193-L207 |
4,927 | itsabot/itsabot | core/nlp.go | RespondWithNicety | func RespondWithNicety(in *dt.Msg) string {
for _, w := range in.Stems {
// Since these are stems, some of them look incorrectly spelled.
// Needless to say, these are the correct Porter2 Snowball stems
switch w {
case "thank":
return "You're welcome!"
case "cool", "sweet", "awesom", "neat", "perfect":
return "I know!"
case "sorri":
return "That's OK. I forgive you."
case "hi", "hello":
return "Hi there. :)"
}
}
return ""
} | go | func RespondWithNicety(in *dt.Msg) string {
for _, w := range in.Stems {
// Since these are stems, some of them look incorrectly spelled.
// Needless to say, these are the correct Porter2 Snowball stems
switch w {
case "thank":
return "You're welcome!"
case "cool", "sweet", "awesom", "neat", "perfect":
return "I know!"
case "sorri":
return "That's OK. I forgive you."
case "hi", "hello":
return "Hi there. :)"
}
}
return ""
} | [
"func",
"RespondWithNicety",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"string",
"{",
"for",
"_",
",",
"w",
":=",
"range",
"in",
".",
"Stems",
"{",
"// Since these are stems, some of them look incorrectly spelled.",
"// Needless to say, these are the correct Porter2 Snowball stems",
"switch",
"w",
"{",
"case",
"\"",
"\"",
":",
"return",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
":",
"return",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // RespondWithNicety replies to niceties that humans use, but Abot can ignore.
// Words like "Thank you" are not necessary for a robot, but it's important Abot
// respond correctly nonetheless. | [
"RespondWithNicety",
"replies",
"to",
"niceties",
"that",
"humans",
"use",
"but",
"Abot",
"can",
"ignore",
".",
"Words",
"like",
"Thank",
"you",
"are",
"not",
"necessary",
"for",
"a",
"robot",
"but",
"it",
"s",
"important",
"Abot",
"respond",
"correctly",
"nonetheless",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/nlp.go#L212-L228 |
4,928 | itsabot/itsabot | core/nlp.go | RespondWithHelp | func RespondWithHelp(in *dt.Msg) string {
if len(in.StructuredInput.Commands) != 1 {
return ""
}
if in.StructuredInput.Commands[0] != "help" {
return ""
}
if in.Plugin != nil {
use := randUseForPlugin(in.Plugin)
use2 := randUseForPlugin(in.Plugin)
if use == use2 {
return fmt.Sprintf("Try telling me %q", use)
}
return fmt.Sprintf("Try telling me %q or %q", use, use2)
}
switch len(PluginsGo) {
case 0:
return ""
case 1:
return fmt.Sprintf("Try saying %q", randUse())
default:
use := randUse()
use2 := randUse()
if use == use2 {
return fmt.Sprintf("Try telling me %q", use)
}
return fmt.Sprintf("Try telling me %q or %q", use, use2)
}
} | go | func RespondWithHelp(in *dt.Msg) string {
if len(in.StructuredInput.Commands) != 1 {
return ""
}
if in.StructuredInput.Commands[0] != "help" {
return ""
}
if in.Plugin != nil {
use := randUseForPlugin(in.Plugin)
use2 := randUseForPlugin(in.Plugin)
if use == use2 {
return fmt.Sprintf("Try telling me %q", use)
}
return fmt.Sprintf("Try telling me %q or %q", use, use2)
}
switch len(PluginsGo) {
case 0:
return ""
case 1:
return fmt.Sprintf("Try saying %q", randUse())
default:
use := randUse()
use2 := randUse()
if use == use2 {
return fmt.Sprintf("Try telling me %q", use)
}
return fmt.Sprintf("Try telling me %q or %q", use, use2)
}
} | [
"func",
"RespondWithHelp",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"string",
"{",
"if",
"len",
"(",
"in",
".",
"StructuredInput",
".",
"Commands",
")",
"!=",
"1",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"in",
".",
"StructuredInput",
".",
"Commands",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"in",
".",
"Plugin",
"!=",
"nil",
"{",
"use",
":=",
"randUseForPlugin",
"(",
"in",
".",
"Plugin",
")",
"\n",
"use2",
":=",
"randUseForPlugin",
"(",
"in",
".",
"Plugin",
")",
"\n",
"if",
"use",
"==",
"use2",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"use",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"use",
",",
"use2",
")",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"PluginsGo",
")",
"{",
"case",
"0",
":",
"return",
"\"",
"\"",
"\n",
"case",
"1",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"randUse",
"(",
")",
")",
"\n",
"default",
":",
"use",
":=",
"randUse",
"(",
")",
"\n",
"use2",
":=",
"randUse",
"(",
")",
"\n",
"if",
"use",
"==",
"use2",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"use",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"use",
",",
"use2",
")",
"\n",
"}",
"\n",
"}"
] | // RespondWithHelp replies to the user when he or she asks for "help". | [
"RespondWithHelp",
"replies",
"to",
"the",
"user",
"when",
"he",
"or",
"she",
"asks",
"for",
"help",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/nlp.go#L231-L259 |
4,929 | itsabot/itsabot | core/nlp.go | RespondWithHelpConfused | func RespondWithHelpConfused(in *dt.Msg) string {
if in.Plugin != nil {
use := randUseForPlugin(in.Plugin)
use2 := randUseForPlugin(in.Plugin)
if use == use2 {
return fmt.Sprintf("%s You can try telling me %q",
ConfusedLang(), use)
}
return fmt.Sprintf("%s You can try telling me %q or %q",
ConfusedLang(), use, use2)
}
if len(PluginsGo) == 0 {
return ConfusedLang()
}
use := randUse()
use2 := randUse()
if use == use2 {
return fmt.Sprintf("%s How about %q", ConfusedLang(), use)
}
return fmt.Sprintf("%s How about %q or %q", ConfusedLang(), use, use2)
} | go | func RespondWithHelpConfused(in *dt.Msg) string {
if in.Plugin != nil {
use := randUseForPlugin(in.Plugin)
use2 := randUseForPlugin(in.Plugin)
if use == use2 {
return fmt.Sprintf("%s You can try telling me %q",
ConfusedLang(), use)
}
return fmt.Sprintf("%s You can try telling me %q or %q",
ConfusedLang(), use, use2)
}
if len(PluginsGo) == 0 {
return ConfusedLang()
}
use := randUse()
use2 := randUse()
if use == use2 {
return fmt.Sprintf("%s How about %q", ConfusedLang(), use)
}
return fmt.Sprintf("%s How about %q or %q", ConfusedLang(), use, use2)
} | [
"func",
"RespondWithHelpConfused",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"string",
"{",
"if",
"in",
".",
"Plugin",
"!=",
"nil",
"{",
"use",
":=",
"randUseForPlugin",
"(",
"in",
".",
"Plugin",
")",
"\n",
"use2",
":=",
"randUseForPlugin",
"(",
"in",
".",
"Plugin",
")",
"\n",
"if",
"use",
"==",
"use2",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ConfusedLang",
"(",
")",
",",
"use",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ConfusedLang",
"(",
")",
",",
"use",
",",
"use2",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"PluginsGo",
")",
"==",
"0",
"{",
"return",
"ConfusedLang",
"(",
")",
"\n",
"}",
"\n",
"use",
":=",
"randUse",
"(",
")",
"\n",
"use2",
":=",
"randUse",
"(",
")",
"\n",
"if",
"use",
"==",
"use2",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ConfusedLang",
"(",
")",
",",
"use",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ConfusedLang",
"(",
")",
",",
"use",
",",
"use2",
")",
"\n",
"}"
] | // RespondWithHelpConfused replies to the user when Abot is confused. | [
"RespondWithHelpConfused",
"replies",
"to",
"the",
"user",
"when",
"Abot",
"is",
"confused",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/nlp.go#L262-L282 |
4,930 | itsabot/itsabot | core/nlp.go | randUse | func randUse() string {
if len(PluginsGo) == 0 {
return ""
}
pluginUses := PluginsGo[rand.Intn(len(PluginsGo))].Usage
if pluginUses == nil || len(pluginUses) == 0 {
return ""
}
return pluginUses[rand.Intn(len(pluginUses))]
} | go | func randUse() string {
if len(PluginsGo) == 0 {
return ""
}
pluginUses := PluginsGo[rand.Intn(len(PluginsGo))].Usage
if pluginUses == nil || len(pluginUses) == 0 {
return ""
}
return pluginUses[rand.Intn(len(pluginUses))]
} | [
"func",
"randUse",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"PluginsGo",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"pluginUses",
":=",
"PluginsGo",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"PluginsGo",
")",
")",
"]",
".",
"Usage",
"\n",
"if",
"pluginUses",
"==",
"nil",
"||",
"len",
"(",
"pluginUses",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"pluginUses",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"pluginUses",
")",
")",
"]",
"\n",
"}"
] | // randUse returns a random use from among all plugins. | [
"randUse",
"returns",
"a",
"random",
"use",
"from",
"among",
"all",
"plugins",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/nlp.go#L285-L294 |
4,931 | itsabot/itsabot | core/nlp.go | randUseForPlugin | func randUseForPlugin(plugin *dt.Plugin) string {
if plugin.Config.Usage == nil {
return ""
}
return plugin.Config.Usage[rand.Intn(len(plugin.Config.Usage))]
} | go | func randUseForPlugin(plugin *dt.Plugin) string {
if plugin.Config.Usage == nil {
return ""
}
return plugin.Config.Usage[rand.Intn(len(plugin.Config.Usage))]
} | [
"func",
"randUseForPlugin",
"(",
"plugin",
"*",
"dt",
".",
"Plugin",
")",
"string",
"{",
"if",
"plugin",
".",
"Config",
".",
"Usage",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"plugin",
".",
"Config",
".",
"Usage",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"plugin",
".",
"Config",
".",
"Usage",
")",
")",
"]",
"\n",
"}"
] | // randUseForPlugin returns a random use from a specific plugin. | [
"randUseForPlugin",
"returns",
"a",
"random",
"use",
"from",
"a",
"specific",
"plugin",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/nlp.go#L297-L302 |
4,932 | itsabot/itsabot | core/nlp.go | RespondWithOffense | func RespondWithOffense(in *dt.Msg) string {
for _, w := range in.Stems {
_, ok := offensive[w]
if ok {
return "I'm sorry, but I don't respond to rude language."
}
}
return ""
} | go | func RespondWithOffense(in *dt.Msg) string {
for _, w := range in.Stems {
_, ok := offensive[w]
if ok {
return "I'm sorry, but I don't respond to rude language."
}
}
return ""
} | [
"func",
"RespondWithOffense",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"string",
"{",
"for",
"_",
",",
"w",
":=",
"range",
"in",
".",
"Stems",
"{",
"_",
",",
"ok",
":=",
"offensive",
"[",
"w",
"]",
"\n",
"if",
"ok",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // RespondWithOffense is a one-off function to respond to rude user language by
// refusing to process the command. | [
"RespondWithOffense",
"is",
"a",
"one",
"-",
"off",
"function",
"to",
"respond",
"to",
"rude",
"user",
"language",
"by",
"refusing",
"to",
"process",
"the",
"command",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/nlp.go#L306-L314 |
4,933 | itsabot/itsabot | shared/helpers/address/address.go | Parse | func Parse(s string) (*dt.Address, error) {
s = regexAddress.FindString(s)
if len(s) == 0 {
log.Debug("missing address")
return nil, ErrInvalidAddress
}
log.Debug("address", s)
tmp := regexZip.FindStringIndex(s)
var zip string
if tmp != nil {
zip = s[tmp[0]:tmp[1]]
s = s[:tmp[0]]
} else {
log.Debug("no zip found")
}
tmp2 := regexState.FindStringIndex(s)
if tmp2 == nil && tmp == nil {
log.Debug("no state found AND no zip found")
return &dt.Address{}, ErrInvalidAddress
}
var city, state string
if tmp2 != nil {
state = s[tmp2[0]:tmp2[1]]
s = s[:tmp2[0]]
state = strings.Trim(state, ", \n")
if len(state) > 2 {
state = strings.ToLower(state)
state = states[state]
}
tmp = regexCity.FindStringIndex(s)
if tmp == nil {
log.Debug("no city found")
return &dt.Address{}, ErrInvalidAddress
}
city = s[tmp[0]:tmp[1]]
s = s[:tmp[0]]
} else {
log.Debug("no state found")
}
tmp = regexApartment.FindStringIndex(s)
var apartment string
if tmp != nil {
apartment = s[tmp[0]:tmp[1]]
s2 := s[:tmp[0]]
if len(s2) == 0 {
apartment = ""
} else {
s = s2
}
} else {
log.Debug("no apartment found")
}
tmp = regexStreet.FindStringIndex(s)
if tmp == nil {
log.Debug(s)
log.Debug("no street found")
return &dt.Address{}, ErrInvalidAddress
}
street := s[tmp[0]:tmp[1]]
return &dt.Address{
Line1: strings.Trim(street, " \n,"),
Line2: strings.Trim(apartment, " \n,"),
City: strings.Trim(city, " \n,"),
State: strings.Trim(state, " \n,"),
Zip: strings.Trim(zip, " \n,"),
Country: "USA",
}, nil
} | go | func Parse(s string) (*dt.Address, error) {
s = regexAddress.FindString(s)
if len(s) == 0 {
log.Debug("missing address")
return nil, ErrInvalidAddress
}
log.Debug("address", s)
tmp := regexZip.FindStringIndex(s)
var zip string
if tmp != nil {
zip = s[tmp[0]:tmp[1]]
s = s[:tmp[0]]
} else {
log.Debug("no zip found")
}
tmp2 := regexState.FindStringIndex(s)
if tmp2 == nil && tmp == nil {
log.Debug("no state found AND no zip found")
return &dt.Address{}, ErrInvalidAddress
}
var city, state string
if tmp2 != nil {
state = s[tmp2[0]:tmp2[1]]
s = s[:tmp2[0]]
state = strings.Trim(state, ", \n")
if len(state) > 2 {
state = strings.ToLower(state)
state = states[state]
}
tmp = regexCity.FindStringIndex(s)
if tmp == nil {
log.Debug("no city found")
return &dt.Address{}, ErrInvalidAddress
}
city = s[tmp[0]:tmp[1]]
s = s[:tmp[0]]
} else {
log.Debug("no state found")
}
tmp = regexApartment.FindStringIndex(s)
var apartment string
if tmp != nil {
apartment = s[tmp[0]:tmp[1]]
s2 := s[:tmp[0]]
if len(s2) == 0 {
apartment = ""
} else {
s = s2
}
} else {
log.Debug("no apartment found")
}
tmp = regexStreet.FindStringIndex(s)
if tmp == nil {
log.Debug(s)
log.Debug("no street found")
return &dt.Address{}, ErrInvalidAddress
}
street := s[tmp[0]:tmp[1]]
return &dt.Address{
Line1: strings.Trim(street, " \n,"),
Line2: strings.Trim(apartment, " \n,"),
City: strings.Trim(city, " \n,"),
State: strings.Trim(state, " \n,"),
Zip: strings.Trim(zip, " \n,"),
Country: "USA",
}, nil
} | [
"func",
"Parse",
"(",
"s",
"string",
")",
"(",
"*",
"dt",
".",
"Address",
",",
"error",
")",
"{",
"s",
"=",
"regexAddress",
".",
"FindString",
"(",
"s",
")",
"\n",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"ErrInvalidAddress",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"tmp",
":=",
"regexZip",
".",
"FindStringIndex",
"(",
"s",
")",
"\n",
"var",
"zip",
"string",
"\n",
"if",
"tmp",
"!=",
"nil",
"{",
"zip",
"=",
"s",
"[",
"tmp",
"[",
"0",
"]",
":",
"tmp",
"[",
"1",
"]",
"]",
"\n",
"s",
"=",
"s",
"[",
":",
"tmp",
"[",
"0",
"]",
"]",
"\n",
"}",
"else",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tmp2",
":=",
"regexState",
".",
"FindStringIndex",
"(",
"s",
")",
"\n",
"if",
"tmp2",
"==",
"nil",
"&&",
"tmp",
"==",
"nil",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"&",
"dt",
".",
"Address",
"{",
"}",
",",
"ErrInvalidAddress",
"\n",
"}",
"\n",
"var",
"city",
",",
"state",
"string",
"\n",
"if",
"tmp2",
"!=",
"nil",
"{",
"state",
"=",
"s",
"[",
"tmp2",
"[",
"0",
"]",
":",
"tmp2",
"[",
"1",
"]",
"]",
"\n",
"s",
"=",
"s",
"[",
":",
"tmp2",
"[",
"0",
"]",
"]",
"\n",
"state",
"=",
"strings",
".",
"Trim",
"(",
"state",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"if",
"len",
"(",
"state",
")",
">",
"2",
"{",
"state",
"=",
"strings",
".",
"ToLower",
"(",
"state",
")",
"\n",
"state",
"=",
"states",
"[",
"state",
"]",
"\n",
"}",
"\n",
"tmp",
"=",
"regexCity",
".",
"FindStringIndex",
"(",
"s",
")",
"\n",
"if",
"tmp",
"==",
"nil",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"&",
"dt",
".",
"Address",
"{",
"}",
",",
"ErrInvalidAddress",
"\n",
"}",
"\n",
"city",
"=",
"s",
"[",
"tmp",
"[",
"0",
"]",
":",
"tmp",
"[",
"1",
"]",
"]",
"\n",
"s",
"=",
"s",
"[",
":",
"tmp",
"[",
"0",
"]",
"]",
"\n",
"}",
"else",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tmp",
"=",
"regexApartment",
".",
"FindStringIndex",
"(",
"s",
")",
"\n",
"var",
"apartment",
"string",
"\n",
"if",
"tmp",
"!=",
"nil",
"{",
"apartment",
"=",
"s",
"[",
"tmp",
"[",
"0",
"]",
":",
"tmp",
"[",
"1",
"]",
"]",
"\n",
"s2",
":=",
"s",
"[",
":",
"tmp",
"[",
"0",
"]",
"]",
"\n",
"if",
"len",
"(",
"s2",
")",
"==",
"0",
"{",
"apartment",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"s",
"=",
"s2",
"\n",
"}",
"\n",
"}",
"else",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tmp",
"=",
"regexStreet",
".",
"FindStringIndex",
"(",
"s",
")",
"\n",
"if",
"tmp",
"==",
"nil",
"{",
"log",
".",
"Debug",
"(",
"s",
")",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"&",
"dt",
".",
"Address",
"{",
"}",
",",
"ErrInvalidAddress",
"\n",
"}",
"\n",
"street",
":=",
"s",
"[",
"tmp",
"[",
"0",
"]",
":",
"tmp",
"[",
"1",
"]",
"]",
"\n",
"return",
"&",
"dt",
".",
"Address",
"{",
"Line1",
":",
"strings",
".",
"Trim",
"(",
"street",
",",
"\"",
"\\n",
"\"",
")",
",",
"Line2",
":",
"strings",
".",
"Trim",
"(",
"apartment",
",",
"\"",
"\\n",
"\"",
")",
",",
"City",
":",
"strings",
".",
"Trim",
"(",
"city",
",",
"\"",
"\\n",
"\"",
")",
",",
"State",
":",
"strings",
".",
"Trim",
"(",
"state",
",",
"\"",
"\\n",
"\"",
")",
",",
"Zip",
":",
"strings",
".",
"Trim",
"(",
"zip",
",",
"\"",
"\\n",
"\"",
")",
",",
"Country",
":",
"\"",
"\"",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Parse a string to return a fully-validated U.S. address. | [
"Parse",
"a",
"string",
"to",
"return",
"a",
"fully",
"-",
"validated",
"U",
".",
"S",
".",
"address",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/helpers/address/address.go#L98-L165 |
4,934 | itsabot/itsabot | core/boot.go | compileAssets | func compileAssets() error {
p := filepath.Join("cmd", "compileassets.sh")
outC, err := exec.
Command("/bin/sh", "-c", p).
CombinedOutput()
if err != nil {
log.Debug(string(outC))
return err
}
return nil
} | go | func compileAssets() error {
p := filepath.Join("cmd", "compileassets.sh")
outC, err := exec.
Command("/bin/sh", "-c", p).
CombinedOutput()
if err != nil {
log.Debug(string(outC))
return err
}
return nil
} | [
"func",
"compileAssets",
"(",
")",
"error",
"{",
"p",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"outC",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"p",
")",
".",
"CombinedOutput",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debug",
"(",
"string",
"(",
"outC",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // compileAssets compresses and merges assets from Abot core and all plugins on
// boot. In development, this step is repeated on each server HTTP request prior
// to serving any assets. | [
"compileAssets",
"compresses",
"and",
"merges",
"assets",
"from",
"Abot",
"core",
"and",
"all",
"plugins",
"on",
"boot",
".",
"In",
"development",
"this",
"step",
"is",
"repeated",
"on",
"each",
"server",
"HTTP",
"request",
"prior",
"to",
"serving",
"any",
"assets",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/boot.go#L165-L175 |
4,935 | itsabot/itsabot | core/boot.go | ConnectDB | func ConnectDB(name string) (*sqlx.DB, error) {
if len(name) == 0 {
dir, err := os.Getwd()
if err != nil {
return nil, err
}
name = filepath.Base(dir)
}
dbConnStr := DBConnectionString(name)
log.Debug("connecting to db")
return sqlx.Connect("postgres", dbConnStr)
} | go | func ConnectDB(name string) (*sqlx.DB, error) {
if len(name) == 0 {
dir, err := os.Getwd()
if err != nil {
return nil, err
}
name = filepath.Base(dir)
}
dbConnStr := DBConnectionString(name)
log.Debug("connecting to db")
return sqlx.Connect("postgres", dbConnStr)
} | [
"func",
"ConnectDB",
"(",
"name",
"string",
")",
"(",
"*",
"sqlx",
".",
"DB",
",",
"error",
")",
"{",
"if",
"len",
"(",
"name",
")",
"==",
"0",
"{",
"dir",
",",
"err",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"name",
"=",
"filepath",
".",
"Base",
"(",
"dir",
")",
"\n",
"}",
"\n",
"dbConnStr",
":=",
"DBConnectionString",
"(",
"name",
")",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"sqlx",
".",
"Connect",
"(",
"\"",
"\"",
",",
"dbConnStr",
")",
"\n",
"}"
] | // ConnectDB opens a connection to the database. The name is the name of the
// database to connect to. If empty, it defaults to the current directory's
// name. | [
"ConnectDB",
"opens",
"a",
"connection",
"to",
"the",
"database",
".",
"The",
"name",
"is",
"the",
"name",
"of",
"the",
"database",
"to",
"connect",
"to",
".",
"If",
"empty",
"it",
"defaults",
"to",
"the",
"current",
"directory",
"s",
"name",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/boot.go#L207-L218 |
4,936 | itsabot/itsabot | core/boot.go | DBConnectionString | func DBConnectionString(name string) string {
dbConnStr := os.Getenv("ABOT_DATABASE_URL")
if dbConnStr == "" {
dbConnStr = "host=127.0.0.1 user=postgres"
}
if len(dbConnStr) <= 11 || dbConnStr[:11] != "postgres://" {
dbConnStr += " sslmode=disable dbname=" + name
if strings.ToLower(os.Getenv("ABOT_ENV")) == "test" {
dbConnStr += "_test"
}
}
return dbConnStr
} | go | func DBConnectionString(name string) string {
dbConnStr := os.Getenv("ABOT_DATABASE_URL")
if dbConnStr == "" {
dbConnStr = "host=127.0.0.1 user=postgres"
}
if len(dbConnStr) <= 11 || dbConnStr[:11] != "postgres://" {
dbConnStr += " sslmode=disable dbname=" + name
if strings.ToLower(os.Getenv("ABOT_ENV")) == "test" {
dbConnStr += "_test"
}
}
return dbConnStr
} | [
"func",
"DBConnectionString",
"(",
"name",
"string",
")",
"string",
"{",
"dbConnStr",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"dbConnStr",
"==",
"\"",
"\"",
"{",
"dbConnStr",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"len",
"(",
"dbConnStr",
")",
"<=",
"11",
"||",
"dbConnStr",
"[",
":",
"11",
"]",
"!=",
"\"",
"\"",
"{",
"dbConnStr",
"+=",
"\"",
"\"",
"+",
"name",
"\n",
"if",
"strings",
".",
"ToLower",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"==",
"\"",
"\"",
"{",
"dbConnStr",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"dbConnStr",
"\n",
"}"
] | // DBConnectionString returns the connection parameters for connecting to the
// database. | [
"DBConnectionString",
"returns",
"the",
"connection",
"parameters",
"for",
"connecting",
"to",
"the",
"database",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/boot.go#L222-L234 |
4,937 | itsabot/itsabot | core/boot.go | LoadConf | func LoadConf() error {
p := filepath.Join("plugins.json")
okVal := fmt.Sprintf("open %s: no such file or directory", p)
contents, err := ioutil.ReadFile(p)
if err != nil && err.Error() != okVal {
return err
}
return json.Unmarshal(contents, conf)
} | go | func LoadConf() error {
p := filepath.Join("plugins.json")
okVal := fmt.Sprintf("open %s: no such file or directory", p)
contents, err := ioutil.ReadFile(p)
if err != nil && err.Error() != okVal {
return err
}
return json.Unmarshal(contents, conf)
} | [
"func",
"LoadConf",
"(",
")",
"error",
"{",
"p",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
")",
"\n",
"okVal",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
")",
"\n",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
".",
"Error",
"(",
")",
"!=",
"okVal",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"json",
".",
"Unmarshal",
"(",
"contents",
",",
"conf",
")",
"\n",
"}"
] | // LoadConf plugins.json into a usable struct. | [
"LoadConf",
"plugins",
".",
"json",
"into",
"a",
"usable",
"struct",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/boot.go#L237-L245 |
4,938 | itsabot/itsabot | core/boot.go | LoadEnvVars | func LoadEnvVars() error {
if envLoaded {
return nil
}
if len(os.Getenv("ABOT_PATH")) == 0 {
p := filepath.Join(os.Getenv("GOPATH"), "src", "github.com",
"itsabot", "abot")
log.Debug("ABOT_PATH not set. defaulting to", p)
if err := os.Setenv("ABOT_PATH", p); err != nil {
return err
}
}
if len(os.Getenv("ITSABOT_URL")) == 0 {
log.Debug("ITSABOT_URL not set, using https://www.itsabot.org")
err := os.Setenv("ITSABOT_URL", "https://www.itsabot.org")
if err != nil {
return err
}
}
p := filepath.Join("abot.env")
fi, err := os.Open(p)
if os.IsNotExist(err) {
// Assume the user has loaded their env variables into their
// path
return nil
}
if err != nil {
return err
}
defer func() {
if err = fi.Close(); err != nil {
log.Info("failed to close file")
}
}()
scn := bufio.NewScanner(fi)
for scn.Scan() {
line := scn.Text()
fields := strings.SplitN(line, "=", 2)
if len(fields) != 2 {
continue
}
key := strings.TrimSpace(fields[0])
if len(key) == 0 {
continue
}
if len(os.Getenv(fields[0])) > 0 {
continue
}
val := strings.TrimSpace(fields[1])
if len(val) >= 2 {
if val[0] == '"' || val[0] == '\'' {
val = val[1 : len(val)-1]
}
}
if err = os.Setenv(key, val); err != nil {
return err
}
}
if err = scn.Err(); err != nil {
return err
}
envLoaded = true
return nil
} | go | func LoadEnvVars() error {
if envLoaded {
return nil
}
if len(os.Getenv("ABOT_PATH")) == 0 {
p := filepath.Join(os.Getenv("GOPATH"), "src", "github.com",
"itsabot", "abot")
log.Debug("ABOT_PATH not set. defaulting to", p)
if err := os.Setenv("ABOT_PATH", p); err != nil {
return err
}
}
if len(os.Getenv("ITSABOT_URL")) == 0 {
log.Debug("ITSABOT_URL not set, using https://www.itsabot.org")
err := os.Setenv("ITSABOT_URL", "https://www.itsabot.org")
if err != nil {
return err
}
}
p := filepath.Join("abot.env")
fi, err := os.Open(p)
if os.IsNotExist(err) {
// Assume the user has loaded their env variables into their
// path
return nil
}
if err != nil {
return err
}
defer func() {
if err = fi.Close(); err != nil {
log.Info("failed to close file")
}
}()
scn := bufio.NewScanner(fi)
for scn.Scan() {
line := scn.Text()
fields := strings.SplitN(line, "=", 2)
if len(fields) != 2 {
continue
}
key := strings.TrimSpace(fields[0])
if len(key) == 0 {
continue
}
if len(os.Getenv(fields[0])) > 0 {
continue
}
val := strings.TrimSpace(fields[1])
if len(val) >= 2 {
if val[0] == '"' || val[0] == '\'' {
val = val[1 : len(val)-1]
}
}
if err = os.Setenv(key, val); err != nil {
return err
}
}
if err = scn.Err(); err != nil {
return err
}
envLoaded = true
return nil
} | [
"func",
"LoadEnvVars",
"(",
")",
"error",
"{",
"if",
"envLoaded",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"==",
"0",
"{",
"p",
":=",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"p",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"p",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"==",
"0",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"err",
":=",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"p",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
")",
"\n",
"fi",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"p",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"// Assume the user has loaded their env variables into their",
"// path",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"=",
"fi",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"scn",
":=",
"bufio",
".",
"NewScanner",
"(",
"fi",
")",
"\n",
"for",
"scn",
".",
"Scan",
"(",
")",
"{",
"line",
":=",
"scn",
".",
"Text",
"(",
")",
"\n",
"fields",
":=",
"strings",
".",
"SplitN",
"(",
"line",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"fields",
")",
"!=",
"2",
"{",
"continue",
"\n",
"}",
"\n",
"key",
":=",
"strings",
".",
"TrimSpace",
"(",
"fields",
"[",
"0",
"]",
")",
"\n",
"if",
"len",
"(",
"key",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"len",
"(",
"os",
".",
"Getenv",
"(",
"fields",
"[",
"0",
"]",
")",
")",
">",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"val",
":=",
"strings",
".",
"TrimSpace",
"(",
"fields",
"[",
"1",
"]",
")",
"\n",
"if",
"len",
"(",
"val",
")",
">=",
"2",
"{",
"if",
"val",
"[",
"0",
"]",
"==",
"'\"'",
"||",
"val",
"[",
"0",
"]",
"==",
"'\\''",
"{",
"val",
"=",
"val",
"[",
"1",
":",
"len",
"(",
"val",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"os",
".",
"Setenv",
"(",
"key",
",",
"val",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"scn",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"envLoaded",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}"
] | // LoadEnvVars from abot.env into memory | [
"LoadEnvVars",
"from",
"abot",
".",
"env",
"into",
"memory"
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/boot.go#L248-L311 |
4,939 | itsabot/itsabot | core/boot.go | LoadPluginsGo | func LoadPluginsGo() error {
p := filepath.Join("plugins.go")
okVal := fmt.Sprintf("open %s: no such file or directory", p)
contents, err := ioutil.ReadFile(p)
if err != nil && err.Error() != okVal {
return err
}
var val []byte
var foundStart bool
var nestLvl int
for _, b := range contents {
switch b {
case '{':
nestLvl++
if nestLvl == 1 {
foundStart = true
}
case '}':
nestLvl--
if nestLvl == 0 {
val = append(val, b)
val = append(val, []byte(",")...)
foundStart = false
}
}
if !foundStart {
continue
}
val = append(val, b)
}
if len(val) == 0 {
return nil
}
val = append([]byte("["), val...)
val = append(val[:len(val)-1], []byte("]")...)
return json.Unmarshal(val, &PluginsGo)
} | go | func LoadPluginsGo() error {
p := filepath.Join("plugins.go")
okVal := fmt.Sprintf("open %s: no such file or directory", p)
contents, err := ioutil.ReadFile(p)
if err != nil && err.Error() != okVal {
return err
}
var val []byte
var foundStart bool
var nestLvl int
for _, b := range contents {
switch b {
case '{':
nestLvl++
if nestLvl == 1 {
foundStart = true
}
case '}':
nestLvl--
if nestLvl == 0 {
val = append(val, b)
val = append(val, []byte(",")...)
foundStart = false
}
}
if !foundStart {
continue
}
val = append(val, b)
}
if len(val) == 0 {
return nil
}
val = append([]byte("["), val...)
val = append(val[:len(val)-1], []byte("]")...)
return json.Unmarshal(val, &PluginsGo)
} | [
"func",
"LoadPluginsGo",
"(",
")",
"error",
"{",
"p",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
")",
"\n",
"okVal",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
")",
"\n",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
".",
"Error",
"(",
")",
"!=",
"okVal",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"val",
"[",
"]",
"byte",
"\n",
"var",
"foundStart",
"bool",
"\n",
"var",
"nestLvl",
"int",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"contents",
"{",
"switch",
"b",
"{",
"case",
"'{'",
":",
"nestLvl",
"++",
"\n",
"if",
"nestLvl",
"==",
"1",
"{",
"foundStart",
"=",
"true",
"\n",
"}",
"\n",
"case",
"'}'",
":",
"nestLvl",
"--",
"\n",
"if",
"nestLvl",
"==",
"0",
"{",
"val",
"=",
"append",
"(",
"val",
",",
"b",
")",
"\n",
"val",
"=",
"append",
"(",
"val",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
"...",
")",
"\n",
"foundStart",
"=",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"foundStart",
"{",
"continue",
"\n",
"}",
"\n",
"val",
"=",
"append",
"(",
"val",
",",
"b",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"val",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"val",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"val",
"...",
")",
"\n",
"val",
"=",
"append",
"(",
"val",
"[",
":",
"len",
"(",
"val",
")",
"-",
"1",
"]",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
"...",
")",
"\n",
"return",
"json",
".",
"Unmarshal",
"(",
"val",
",",
"&",
"PluginsGo",
")",
"\n",
"}"
] | // LoadPluginsGo loads the plugins.go file into memory. | [
"LoadPluginsGo",
"loads",
"the",
"plugins",
".",
"go",
"file",
"into",
"memory",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/boot.go#L314-L350 |
4,940 | itsabot/itsabot | core/boot.go | trainClassifiers | func trainClassifiers() error {
for _, pconf := range PluginsGo {
ss, err := fetchTrainingSentences(pconf.ID, pconf.Name)
if err != nil {
return err
}
// Assemble list of Bayesian classes from all trained intents
// for this plugin. m is used to keep track of the classes
// already taught to each classifier.
m := map[string]struct{}{}
for _, s := range ss {
_, ok := m[s.Intent]
if ok {
continue
}
log.Debug("learning intent", s.Intent)
m[s.Intent] = struct{}{}
pluginIntents[s.PluginID] = append(pluginIntents[s.PluginID],
bayesian.Class(s.Intent))
}
// Build classifier from complete sets of intents
for _, s := range ss {
intents := pluginIntents[s.PluginID]
// Calling bayesian.NewClassifier() with 0 or 1
// classes causes a panic.
if len(intents) == 0 {
break
}
if len(intents) == 1 {
intents = append(intents, bayesian.Class("__no_intent"))
}
c := bayesian.NewClassifier(intents...)
bClassifiers[s.PluginID] = c
}
// With classifiers initialized, train each of them on a
// sentence's stems.
for _, s := range ss {
tokens := TokenizeSentence(s.Sentence)
stems := StemTokens(tokens)
c, exists := bClassifiers[s.PluginID]
if exists {
c.Learn(stems, bayesian.Class(s.Intent))
}
}
}
return nil
} | go | func trainClassifiers() error {
for _, pconf := range PluginsGo {
ss, err := fetchTrainingSentences(pconf.ID, pconf.Name)
if err != nil {
return err
}
// Assemble list of Bayesian classes from all trained intents
// for this plugin. m is used to keep track of the classes
// already taught to each classifier.
m := map[string]struct{}{}
for _, s := range ss {
_, ok := m[s.Intent]
if ok {
continue
}
log.Debug("learning intent", s.Intent)
m[s.Intent] = struct{}{}
pluginIntents[s.PluginID] = append(pluginIntents[s.PluginID],
bayesian.Class(s.Intent))
}
// Build classifier from complete sets of intents
for _, s := range ss {
intents := pluginIntents[s.PluginID]
// Calling bayesian.NewClassifier() with 0 or 1
// classes causes a panic.
if len(intents) == 0 {
break
}
if len(intents) == 1 {
intents = append(intents, bayesian.Class("__no_intent"))
}
c := bayesian.NewClassifier(intents...)
bClassifiers[s.PluginID] = c
}
// With classifiers initialized, train each of them on a
// sentence's stems.
for _, s := range ss {
tokens := TokenizeSentence(s.Sentence)
stems := StemTokens(tokens)
c, exists := bClassifiers[s.PluginID]
if exists {
c.Learn(stems, bayesian.Class(s.Intent))
}
}
}
return nil
} | [
"func",
"trainClassifiers",
"(",
")",
"error",
"{",
"for",
"_",
",",
"pconf",
":=",
"range",
"PluginsGo",
"{",
"ss",
",",
"err",
":=",
"fetchTrainingSentences",
"(",
"pconf",
".",
"ID",
",",
"pconf",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Assemble list of Bayesian classes from all trained intents",
"// for this plugin. m is used to keep track of the classes",
"// already taught to each classifier.",
"m",
":=",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"ss",
"{",
"_",
",",
"ok",
":=",
"m",
"[",
"s",
".",
"Intent",
"]",
"\n",
"if",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"s",
".",
"Intent",
")",
"\n",
"m",
"[",
"s",
".",
"Intent",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"pluginIntents",
"[",
"s",
".",
"PluginID",
"]",
"=",
"append",
"(",
"pluginIntents",
"[",
"s",
".",
"PluginID",
"]",
",",
"bayesian",
".",
"Class",
"(",
"s",
".",
"Intent",
")",
")",
"\n",
"}",
"\n\n",
"// Build classifier from complete sets of intents",
"for",
"_",
",",
"s",
":=",
"range",
"ss",
"{",
"intents",
":=",
"pluginIntents",
"[",
"s",
".",
"PluginID",
"]",
"\n",
"// Calling bayesian.NewClassifier() with 0 or 1",
"// classes causes a panic.",
"if",
"len",
"(",
"intents",
")",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"if",
"len",
"(",
"intents",
")",
"==",
"1",
"{",
"intents",
"=",
"append",
"(",
"intents",
",",
"bayesian",
".",
"Class",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"c",
":=",
"bayesian",
".",
"NewClassifier",
"(",
"intents",
"...",
")",
"\n",
"bClassifiers",
"[",
"s",
".",
"PluginID",
"]",
"=",
"c",
"\n",
"}",
"\n\n",
"// With classifiers initialized, train each of them on a",
"// sentence's stems.",
"for",
"_",
",",
"s",
":=",
"range",
"ss",
"{",
"tokens",
":=",
"TokenizeSentence",
"(",
"s",
".",
"Sentence",
")",
"\n",
"stems",
":=",
"StemTokens",
"(",
"tokens",
")",
"\n",
"c",
",",
"exists",
":=",
"bClassifiers",
"[",
"s",
".",
"PluginID",
"]",
"\n",
"if",
"exists",
"{",
"c",
".",
"Learn",
"(",
"stems",
",",
"bayesian",
".",
"Class",
"(",
"s",
".",
"Intent",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // trainClassifiers trains classifiers for each plugin. | [
"trainClassifiers",
"trains",
"classifiers",
"for",
"each",
"plugin",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/boot.go#L353-L402 |
4,941 | itsabot/itsabot | shared/datatypes/slice.go | Scan | func (u *Uint64Slice) Scan(src interface{}) error {
asBytes, ok := src.([]byte)
if !ok {
return errors.New("scan source was not []bytes")
}
str := string(asBytes)
str = str[1 : len(str)-1]
csvReader := csv.NewReader(strings.NewReader(str))
slice, err := csvReader.Read()
if err != nil && err.Error() != "EOF" {
return err
}
var s []uint64
for _, sl := range slice {
tmp, err := strconv.ParseUint(sl, 10, 64)
if err != nil {
return err
}
s = append(s, tmp)
}
*u = Uint64Slice(s)
return nil
} | go | func (u *Uint64Slice) Scan(src interface{}) error {
asBytes, ok := src.([]byte)
if !ok {
return errors.New("scan source was not []bytes")
}
str := string(asBytes)
str = str[1 : len(str)-1]
csvReader := csv.NewReader(strings.NewReader(str))
slice, err := csvReader.Read()
if err != nil && err.Error() != "EOF" {
return err
}
var s []uint64
for _, sl := range slice {
tmp, err := strconv.ParseUint(sl, 10, 64)
if err != nil {
return err
}
s = append(s, tmp)
}
*u = Uint64Slice(s)
return nil
} | [
"func",
"(",
"u",
"*",
"Uint64Slice",
")",
"Scan",
"(",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"asBytes",
",",
"ok",
":=",
"src",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"str",
":=",
"string",
"(",
"asBytes",
")",
"\n",
"str",
"=",
"str",
"[",
"1",
":",
"len",
"(",
"str",
")",
"-",
"1",
"]",
"\n",
"csvReader",
":=",
"csv",
".",
"NewReader",
"(",
"strings",
".",
"NewReader",
"(",
"str",
")",
")",
"\n",
"slice",
",",
"err",
":=",
"csvReader",
".",
"Read",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
".",
"Error",
"(",
")",
"!=",
"\"",
"\"",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"s",
"[",
"]",
"uint64",
"\n",
"for",
"_",
",",
"sl",
":=",
"range",
"slice",
"{",
"tmp",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"sl",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
"=",
"append",
"(",
"s",
",",
"tmp",
")",
"\n",
"}",
"\n",
"*",
"u",
"=",
"Uint64Slice",
"(",
"s",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Scan converts to a slice of uint64. | [
"Scan",
"converts",
"to",
"a",
"slice",
"of",
"uint64",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/slice.go#L16-L38 |
4,942 | itsabot/itsabot | shared/datatypes/slice.go | Value | func (u Uint64Slice) Value() (driver.Value, error) {
var ss []string
for i := 0; i < len(u); i++ {
tmp := strconv.FormatUint(u[i], 10)
ss = append(ss, tmp)
}
return "{" + strings.Join(ss, ",") + "}", nil
} | go | func (u Uint64Slice) Value() (driver.Value, error) {
var ss []string
for i := 0; i < len(u); i++ {
tmp := strconv.FormatUint(u[i], 10)
ss = append(ss, tmp)
}
return "{" + strings.Join(ss, ",") + "}", nil
} | [
"func",
"(",
"u",
"Uint64Slice",
")",
"Value",
"(",
")",
"(",
"driver",
".",
"Value",
",",
"error",
")",
"{",
"var",
"ss",
"[",
"]",
"string",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"u",
")",
";",
"i",
"++",
"{",
"tmp",
":=",
"strconv",
".",
"FormatUint",
"(",
"u",
"[",
"i",
"]",
",",
"10",
")",
"\n",
"ss",
"=",
"append",
"(",
"ss",
",",
"tmp",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"ss",
",",
"\"",
"\"",
")",
"+",
"\"",
"\"",
",",
"nil",
"\n",
"}"
] | // Value converts to a slice of uint64. | [
"Value",
"converts",
"to",
"a",
"slice",
"of",
"uint64",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/slice.go#L41-L48 |
4,943 | itsabot/itsabot | shared/datatypes/slice.go | String | func (s StringSlice) String() string {
if len(s) == 0 {
return ""
}
var ss string
for _, w := range s {
ss += " " + w
}
return ss[1:]
} | go | func (s StringSlice) String() string {
if len(s) == 0 {
return ""
}
var ss string
for _, w := range s {
ss += " " + w
}
return ss[1:]
} | [
"func",
"(",
"s",
"StringSlice",
")",
"String",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"var",
"ss",
"string",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"s",
"{",
"ss",
"+=",
"\"",
"\"",
"+",
"w",
"\n",
"}",
"\n",
"return",
"ss",
"[",
"1",
":",
"]",
"\n",
"}"
] | // String converts a StringSlice into a string with each word separated by
// spaces. | [
"String",
"converts",
"a",
"StringSlice",
"into",
"a",
"string",
"with",
"each",
"word",
"separated",
"by",
"spaces",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/slice.go#L103-L112 |
4,944 | itsabot/itsabot | shared/datatypes/slice.go | Map | func (s StringSlice) Map() map[string]struct{} {
m := map[string]struct{}{}
for _, w := range s {
m[w] = struct{}{}
}
return m
} | go | func (s StringSlice) Map() map[string]struct{} {
m := map[string]struct{}{}
for _, w := range s {
m[w] = struct{}{}
}
return m
} | [
"func",
"(",
"s",
"StringSlice",
")",
"Map",
"(",
")",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"m",
":=",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"s",
"{",
"m",
"[",
"w",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // Map converts a StringSlice into a map to check quickly if words exist within
// it. | [
"Map",
"converts",
"a",
"StringSlice",
"into",
"a",
"map",
"to",
"check",
"quickly",
"if",
"words",
"exist",
"within",
"it",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/slice.go#L128-L134 |
4,945 | itsabot/itsabot | core/template/forgot_password_email.go | ForgotPasswordEmail | func ForgotPasswordEmail(name, secret string) string {
h := `<html><body>`
h += fmt.Sprintf("<p>Hi %s:</p>", name)
h += "<p>Please click the following link to reset your password. This link will expire in 30 minutes.</p>"
h += fmt.Sprintf("<p>%s</p>", os.Getenv("ABOT_URL")+"/reset_password?s="+secret)
h += "<p>If you received this email in error, please ignore it.</p>"
h += "<p>Have a great day!</p>"
h += "<p>-Abot</p>"
h += "</body></html>"
return h
} | go | func ForgotPasswordEmail(name, secret string) string {
h := `<html><body>`
h += fmt.Sprintf("<p>Hi %s:</p>", name)
h += "<p>Please click the following link to reset your password. This link will expire in 30 minutes.</p>"
h += fmt.Sprintf("<p>%s</p>", os.Getenv("ABOT_URL")+"/reset_password?s="+secret)
h += "<p>If you received this email in error, please ignore it.</p>"
h += "<p>Have a great day!</p>"
h += "<p>-Abot</p>"
h += "</body></html>"
return h
} | [
"func",
"ForgotPasswordEmail",
"(",
"name",
",",
"secret",
"string",
")",
"string",
"{",
"h",
":=",
"`<html><body>`",
"\n",
"h",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"h",
"+=",
"\"",
"\"",
"\n",
"h",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"+",
"\"",
"\"",
"+",
"secret",
")",
"\n",
"h",
"+=",
"\"",
"\"",
"\n",
"h",
"+=",
"\"",
"\"",
"\n",
"h",
"+=",
"\"",
"\"",
"\n",
"h",
"+=",
"\"",
"\"",
"\n",
"return",
"h",
"\n",
"}"
] | // ForgotPasswordEmail takes a user's name and a secret token stored in the
// database and returns an HTML-format email. | [
"ForgotPasswordEmail",
"takes",
"a",
"user",
"s",
"name",
"and",
"a",
"secret",
"token",
"stored",
"in",
"the",
"database",
"and",
"returns",
"an",
"HTML",
"-",
"format",
"email",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/template/forgot_password_email.go#L13-L23 |
4,946 | itsabot/itsabot | core/websocket/websocket.go | NewAtomicWebSocketSet | func NewAtomicWebSocketSet() AtomicWebSocketSet {
return AtomicWebSocketSet{
sockets: map[uint64]*websocket.Conn{},
mutex: &sync.Mutex{},
}
} | go | func NewAtomicWebSocketSet() AtomicWebSocketSet {
return AtomicWebSocketSet{
sockets: map[uint64]*websocket.Conn{},
mutex: &sync.Mutex{},
}
} | [
"func",
"NewAtomicWebSocketSet",
"(",
")",
"AtomicWebSocketSet",
"{",
"return",
"AtomicWebSocketSet",
"{",
"sockets",
":",
"map",
"[",
"uint64",
"]",
"*",
"websocket",
".",
"Conn",
"{",
"}",
",",
"mutex",
":",
"&",
"sync",
".",
"Mutex",
"{",
"}",
",",
"}",
"\n",
"}"
] | // NewAtomicWebSocketSet returns an AtomicWebSocketSet to maintain open
// WebSocket connections on a per-user basis. | [
"NewAtomicWebSocketSet",
"returns",
"an",
"AtomicWebSocketSet",
"to",
"maintain",
"open",
"WebSocket",
"connections",
"on",
"a",
"per",
"-",
"user",
"basis",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/websocket/websocket.go#L24-L29 |
4,947 | itsabot/itsabot | core/websocket/websocket.go | Get | func (as AtomicWebSocketSet) Get(userID uint64) *websocket.Conn {
var conn *websocket.Conn
as.mutex.Lock()
conn = as.sockets[userID]
as.mutex.Unlock()
runtime.Gosched()
return conn
} | go | func (as AtomicWebSocketSet) Get(userID uint64) *websocket.Conn {
var conn *websocket.Conn
as.mutex.Lock()
conn = as.sockets[userID]
as.mutex.Unlock()
runtime.Gosched()
return conn
} | [
"func",
"(",
"as",
"AtomicWebSocketSet",
")",
"Get",
"(",
"userID",
"uint64",
")",
"*",
"websocket",
".",
"Conn",
"{",
"var",
"conn",
"*",
"websocket",
".",
"Conn",
"\n",
"as",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"conn",
"=",
"as",
".",
"sockets",
"[",
"userID",
"]",
"\n",
"as",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"runtime",
".",
"Gosched",
"(",
")",
"\n",
"return",
"conn",
"\n",
"}"
] | // Get returns a WebSocket connection for a given userID in a thread-safe way. | [
"Get",
"returns",
"a",
"WebSocket",
"connection",
"for",
"a",
"given",
"userID",
"in",
"a",
"thread",
"-",
"safe",
"way",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/websocket/websocket.go#L32-L39 |
4,948 | itsabot/itsabot | core/websocket/websocket.go | NotifySockets | func (as AtomicWebSocketSet) NotifySockets(uid uint64, cmd, ret string) error {
s := as.Get(uid)
if s == nil {
// Trainer is not online.
return nil
}
t := time.Now()
data := []struct {
Sentence string
AvaSent bool
CreatedAt *time.Time
}{
{
Sentence: cmd,
AvaSent: false,
CreatedAt: &t,
},
}
if len(ret) > 0 {
data = append(data, struct {
Sentence string
AvaSent bool
CreatedAt *time.Time
}{
Sentence: ret,
AvaSent: true,
CreatedAt: &t,
})
}
return websocket.JSON.Send(s, &data)
} | go | func (as AtomicWebSocketSet) NotifySockets(uid uint64, cmd, ret string) error {
s := as.Get(uid)
if s == nil {
// Trainer is not online.
return nil
}
t := time.Now()
data := []struct {
Sentence string
AvaSent bool
CreatedAt *time.Time
}{
{
Sentence: cmd,
AvaSent: false,
CreatedAt: &t,
},
}
if len(ret) > 0 {
data = append(data, struct {
Sentence string
AvaSent bool
CreatedAt *time.Time
}{
Sentence: ret,
AvaSent: true,
CreatedAt: &t,
})
}
return websocket.JSON.Send(s, &data)
} | [
"func",
"(",
"as",
"AtomicWebSocketSet",
")",
"NotifySockets",
"(",
"uid",
"uint64",
",",
"cmd",
",",
"ret",
"string",
")",
"error",
"{",
"s",
":=",
"as",
".",
"Get",
"(",
"uid",
")",
"\n",
"if",
"s",
"==",
"nil",
"{",
"// Trainer is not online.",
"return",
"nil",
"\n",
"}",
"\n",
"t",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"data",
":=",
"[",
"]",
"struct",
"{",
"Sentence",
"string",
"\n",
"AvaSent",
"bool",
"\n",
"CreatedAt",
"*",
"time",
".",
"Time",
"\n",
"}",
"{",
"{",
"Sentence",
":",
"cmd",
",",
"AvaSent",
":",
"false",
",",
"CreatedAt",
":",
"&",
"t",
",",
"}",
",",
"}",
"\n",
"if",
"len",
"(",
"ret",
")",
">",
"0",
"{",
"data",
"=",
"append",
"(",
"data",
",",
"struct",
"{",
"Sentence",
"string",
"\n",
"AvaSent",
"bool",
"\n",
"CreatedAt",
"*",
"time",
".",
"Time",
"\n",
"}",
"{",
"Sentence",
":",
"ret",
",",
"AvaSent",
":",
"true",
",",
"CreatedAt",
":",
"&",
"t",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"websocket",
".",
"JSON",
".",
"Send",
"(",
"s",
",",
"&",
"data",
")",
"\n",
"}"
] | // NotifySockets sends listening clients new messages over WebSockets,
// eliminating the need for trainers to constantly reload the page. | [
"NotifySockets",
"sends",
"listening",
"clients",
"new",
"messages",
"over",
"WebSockets",
"eliminating",
"the",
"need",
"for",
"trainers",
"to",
"constantly",
"reload",
"the",
"page",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/websocket/websocket.go#L51-L81 |
4,949 | itsabot/itsabot | core/plugin.go | Get | func (pm PkgMap) Get(k string) *dt.Plugin {
var p *dt.Plugin
pm.mutex.Lock()
p = pm.plugins[k]
pm.mutex.Unlock()
runtime.Gosched()
return p
} | go | func (pm PkgMap) Get(k string) *dt.Plugin {
var p *dt.Plugin
pm.mutex.Lock()
p = pm.plugins[k]
pm.mutex.Unlock()
runtime.Gosched()
return p
} | [
"func",
"(",
"pm",
"PkgMap",
")",
"Get",
"(",
"k",
"string",
")",
"*",
"dt",
".",
"Plugin",
"{",
"var",
"p",
"*",
"dt",
".",
"Plugin",
"\n",
"pm",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"p",
"=",
"pm",
".",
"plugins",
"[",
"k",
"]",
"\n",
"pm",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"runtime",
".",
"Gosched",
"(",
")",
"\n",
"return",
"p",
"\n",
"}"
] | // Get is a thread-safe, locking way to access the values of a PkgMap. | [
"Get",
"is",
"a",
"thread",
"-",
"safe",
"locking",
"way",
"to",
"access",
"the",
"values",
"of",
"a",
"PkgMap",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/plugin.go#L43-L50 |
4,950 | itsabot/itsabot | core/plugin.go | Set | func (pm PkgMap) Set(k string, v *dt.Plugin) {
pm.mutex.Lock()
pm.plugins[k] = v
pm.mutex.Unlock()
runtime.Gosched()
} | go | func (pm PkgMap) Set(k string, v *dt.Plugin) {
pm.mutex.Lock()
pm.plugins[k] = v
pm.mutex.Unlock()
runtime.Gosched()
} | [
"func",
"(",
"pm",
"PkgMap",
")",
"Set",
"(",
"k",
"string",
",",
"v",
"*",
"dt",
".",
"Plugin",
")",
"{",
"pm",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"pm",
".",
"plugins",
"[",
"k",
"]",
"=",
"v",
"\n",
"pm",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"runtime",
".",
"Gosched",
"(",
")",
"\n",
"}"
] | // Set is a thread-safe, locking way to set the values of a PkgMap. | [
"Set",
"is",
"a",
"thread",
"-",
"safe",
"locking",
"way",
"to",
"set",
"the",
"values",
"of",
"a",
"PkgMap",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/plugin.go#L53-L58 |
4,951 | itsabot/itsabot | core/plugin.go | GetPlugin | func GetPlugin(db *sqlx.DB, m *dt.Msg) (p *dt.Plugin, route string, directroute,
followup bool, err error) {
// Iterate through all intents to see if any plugin has been registered
// for the route
for _, i := range m.StructuredInput.Intents {
route = "I_" + strings.ToLower(i)
log.Debug("searching for route", route)
if p = RegPlugins.Get(route); p != nil {
// Found route. Return it
return p, route, true, false, nil
}
}
log.Debug("getting last plugin route")
prevPlugin, prevRoute, err := m.GetLastPlugin(db)
if err != nil && err != sql.ErrNoRows {
return nil, "", false, false, err
}
if len(prevPlugin) > 0 {
log.Debugf("found user's last plugin route: %s - %s\n",
prevPlugin, prevRoute)
}
// Iterate over all command/object pairs and see if any plugin has been
// registered for the resulting route
eng := porter2.Stemmer
for _, c := range m.StructuredInput.Commands {
c = strings.ToLower(eng.Stem(c))
for _, o := range m.StructuredInput.Objects {
o = strings.ToLower(eng.Stem(o))
route := "CO_" + c + "_" + o
log.Debug("searching for route", route)
if p = RegPlugins.Get(route); p != nil {
// Found route. Return it
followup := prevPlugin == p.Config.Name
return p, route, true, followup, nil
}
}
}
// The user input didn't match any plugins. Let's see if the previous
// route does
if prevRoute != "" {
if p = RegPlugins.Get(prevRoute); p != nil {
// Prev route matches a pkg! Return it
return p, prevRoute, false, true, nil
}
}
// Sadly, if we've reached this point, we are at a loss.
log.Debug("could not match user input to any plugin")
return nil, "", false, false, errMissingPlugin
} | go | func GetPlugin(db *sqlx.DB, m *dt.Msg) (p *dt.Plugin, route string, directroute,
followup bool, err error) {
// Iterate through all intents to see if any plugin has been registered
// for the route
for _, i := range m.StructuredInput.Intents {
route = "I_" + strings.ToLower(i)
log.Debug("searching for route", route)
if p = RegPlugins.Get(route); p != nil {
// Found route. Return it
return p, route, true, false, nil
}
}
log.Debug("getting last plugin route")
prevPlugin, prevRoute, err := m.GetLastPlugin(db)
if err != nil && err != sql.ErrNoRows {
return nil, "", false, false, err
}
if len(prevPlugin) > 0 {
log.Debugf("found user's last plugin route: %s - %s\n",
prevPlugin, prevRoute)
}
// Iterate over all command/object pairs and see if any plugin has been
// registered for the resulting route
eng := porter2.Stemmer
for _, c := range m.StructuredInput.Commands {
c = strings.ToLower(eng.Stem(c))
for _, o := range m.StructuredInput.Objects {
o = strings.ToLower(eng.Stem(o))
route := "CO_" + c + "_" + o
log.Debug("searching for route", route)
if p = RegPlugins.Get(route); p != nil {
// Found route. Return it
followup := prevPlugin == p.Config.Name
return p, route, true, followup, nil
}
}
}
// The user input didn't match any plugins. Let's see if the previous
// route does
if prevRoute != "" {
if p = RegPlugins.Get(prevRoute); p != nil {
// Prev route matches a pkg! Return it
return p, prevRoute, false, true, nil
}
}
// Sadly, if we've reached this point, we are at a loss.
log.Debug("could not match user input to any plugin")
return nil, "", false, false, errMissingPlugin
} | [
"func",
"GetPlugin",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"m",
"*",
"dt",
".",
"Msg",
")",
"(",
"p",
"*",
"dt",
".",
"Plugin",
",",
"route",
"string",
",",
"directroute",
",",
"followup",
"bool",
",",
"err",
"error",
")",
"{",
"// Iterate through all intents to see if any plugin has been registered",
"// for the route",
"for",
"_",
",",
"i",
":=",
"range",
"m",
".",
"StructuredInput",
".",
"Intents",
"{",
"route",
"=",
"\"",
"\"",
"+",
"strings",
".",
"ToLower",
"(",
"i",
")",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"route",
")",
"\n",
"if",
"p",
"=",
"RegPlugins",
".",
"Get",
"(",
"route",
")",
";",
"p",
"!=",
"nil",
"{",
"// Found route. Return it",
"return",
"p",
",",
"route",
",",
"true",
",",
"false",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"prevPlugin",
",",
"prevRoute",
",",
"err",
":=",
"m",
".",
"GetLastPlugin",
"(",
"db",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"sql",
".",
"ErrNoRows",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"false",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"prevPlugin",
")",
">",
"0",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"prevPlugin",
",",
"prevRoute",
")",
"\n",
"}",
"\n\n",
"// Iterate over all command/object pairs and see if any plugin has been",
"// registered for the resulting route",
"eng",
":=",
"porter2",
".",
"Stemmer",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"m",
".",
"StructuredInput",
".",
"Commands",
"{",
"c",
"=",
"strings",
".",
"ToLower",
"(",
"eng",
".",
"Stem",
"(",
"c",
")",
")",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"m",
".",
"StructuredInput",
".",
"Objects",
"{",
"o",
"=",
"strings",
".",
"ToLower",
"(",
"eng",
".",
"Stem",
"(",
"o",
")",
")",
"\n",
"route",
":=",
"\"",
"\"",
"+",
"c",
"+",
"\"",
"\"",
"+",
"o",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"route",
")",
"\n",
"if",
"p",
"=",
"RegPlugins",
".",
"Get",
"(",
"route",
")",
";",
"p",
"!=",
"nil",
"{",
"// Found route. Return it",
"followup",
":=",
"prevPlugin",
"==",
"p",
".",
"Config",
".",
"Name",
"\n",
"return",
"p",
",",
"route",
",",
"true",
",",
"followup",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// The user input didn't match any plugins. Let's see if the previous",
"// route does",
"if",
"prevRoute",
"!=",
"\"",
"\"",
"{",
"if",
"p",
"=",
"RegPlugins",
".",
"Get",
"(",
"prevRoute",
")",
";",
"p",
"!=",
"nil",
"{",
"// Prev route matches a pkg! Return it",
"return",
"p",
",",
"prevRoute",
",",
"false",
",",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Sadly, if we've reached this point, we are at a loss.",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"false",
",",
"false",
",",
"errMissingPlugin",
"\n",
"}"
] | // GetPlugin attempts to find a plugin and route for the given msg input if none
// can be found, it checks the database for the last route used and gets the
// plugin for that. If there is no previously used plugin, we return
// errMissingPlugin. The bool value return indicates whether this plugin is
// different from the last plugin used by the user. | [
"GetPlugin",
"attempts",
"to",
"find",
"a",
"plugin",
"and",
"route",
"for",
"the",
"given",
"msg",
"input",
"if",
"none",
"can",
"be",
"found",
"it",
"checks",
"the",
"database",
"for",
"the",
"last",
"route",
"used",
"and",
"gets",
"the",
"plugin",
"for",
"that",
".",
"If",
"there",
"is",
"no",
"previously",
"used",
"plugin",
"we",
"return",
"errMissingPlugin",
".",
"The",
"bool",
"value",
"return",
"indicates",
"whether",
"this",
"plugin",
"is",
"different",
"from",
"the",
"last",
"plugin",
"used",
"by",
"the",
"user",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/plugin.go#L65-L118 |
4,952 | itsabot/itsabot | core/analytics.go | updateAnalytics | func updateAnalytics(interval time.Duration) {
t := time.NewTicker(time.Hour)
select {
case now := <-t.C:
updateAnalyticsTick(now)
updateAnalytics(interval)
}
} | go | func updateAnalytics(interval time.Duration) {
t := time.NewTicker(time.Hour)
select {
case now := <-t.C:
updateAnalyticsTick(now)
updateAnalytics(interval)
}
} | [
"func",
"updateAnalytics",
"(",
"interval",
"time",
".",
"Duration",
")",
"{",
"t",
":=",
"time",
".",
"NewTicker",
"(",
"time",
".",
"Hour",
")",
"\n",
"select",
"{",
"case",
"now",
":=",
"<-",
"t",
".",
"C",
":",
"updateAnalyticsTick",
"(",
"now",
")",
"\n",
"updateAnalytics",
"(",
"interval",
")",
"\n",
"}",
"\n",
"}"
] | // updateAnalytics recursively calls itself to continue running. | [
"updateAnalytics",
"recursively",
"calls",
"itself",
"to",
"continue",
"running",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/analytics.go#L21-L28 |
4,953 | itsabot/itsabot | shared/datatypes/plugin.go | DeleteMemory | func (p *Plugin) DeleteMemory(in *Msg, k string) {
var err error
if in.User.ID > 0 {
q := `DELETE FROM states
WHERE userid=$1 AND pluginname=$2 AND key=$3`
_, err = p.DB.Exec(q, in.User.ID, p.Config.Name, k)
} else {
q := `DELETE FROM states
WHERE flexid=$1 AND flexidtype=$2 AND pluginname=$3
AND key=$4`
_, err = p.DB.Exec(q, in.User.FlexID, in.User.FlexIDType,
p.Config.Name, k)
}
if err != nil {
p.Log.Infof("could not delete memory for key %s. %s", k,
err.Error())
}
} | go | func (p *Plugin) DeleteMemory(in *Msg, k string) {
var err error
if in.User.ID > 0 {
q := `DELETE FROM states
WHERE userid=$1 AND pluginname=$2 AND key=$3`
_, err = p.DB.Exec(q, in.User.ID, p.Config.Name, k)
} else {
q := `DELETE FROM states
WHERE flexid=$1 AND flexidtype=$2 AND pluginname=$3
AND key=$4`
_, err = p.DB.Exec(q, in.User.FlexID, in.User.FlexIDType,
p.Config.Name, k)
}
if err != nil {
p.Log.Infof("could not delete memory for key %s. %s", k,
err.Error())
}
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"DeleteMemory",
"(",
"in",
"*",
"Msg",
",",
"k",
"string",
")",
"{",
"var",
"err",
"error",
"\n",
"if",
"in",
".",
"User",
".",
"ID",
">",
"0",
"{",
"q",
":=",
"`DELETE FROM states\n\t\t WHERE userid=$1 AND pluginname=$2 AND key=$3`",
"\n",
"_",
",",
"err",
"=",
"p",
".",
"DB",
".",
"Exec",
"(",
"q",
",",
"in",
".",
"User",
".",
"ID",
",",
"p",
".",
"Config",
".",
"Name",
",",
"k",
")",
"\n",
"}",
"else",
"{",
"q",
":=",
"`DELETE FROM states\n\t\t WHERE flexid=$1 AND flexidtype=$2 AND pluginname=$3\n\t\t AND key=$4`",
"\n",
"_",
",",
"err",
"=",
"p",
".",
"DB",
".",
"Exec",
"(",
"q",
",",
"in",
".",
"User",
".",
"FlexID",
",",
"in",
".",
"User",
".",
"FlexIDType",
",",
"p",
".",
"Config",
".",
"Name",
",",
"k",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"k",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] | // DeleteMemory deletes a memory for a given key. It is not an error to delete
// a key that does not exist. | [
"DeleteMemory",
"deletes",
"a",
"memory",
"for",
"a",
"given",
"key",
".",
"It",
"is",
"not",
"an",
"error",
"to",
"delete",
"a",
"key",
"that",
"does",
"not",
"exist",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/plugin.go#L220-L237 |
4,954 | itsabot/itsabot | shared/datatypes/plugin.go | GetSetting | func (p *Plugin) GetSetting(name string) string {
if p.Config.Settings[name] == nil {
pluginName := p.Config.Name
if len(pluginName) == 0 {
pluginName = "plugin"
}
m := fmt.Sprintf(
"missing setting %s. please declare it in the %s's plugin.json",
name, pluginName)
log.Fatal(m)
}
var val string
q := `SELECT value FROM settings WHERE name=$1 AND pluginname=$2`
err := p.DB.Get(&val, q, name, p.Config.Name)
if err == sql.ErrNoRows {
return p.Config.Settings[name].Default
}
if err != nil {
log.Info("failed to get plugin setting.", err)
return ""
}
return val
} | go | func (p *Plugin) GetSetting(name string) string {
if p.Config.Settings[name] == nil {
pluginName := p.Config.Name
if len(pluginName) == 0 {
pluginName = "plugin"
}
m := fmt.Sprintf(
"missing setting %s. please declare it in the %s's plugin.json",
name, pluginName)
log.Fatal(m)
}
var val string
q := `SELECT value FROM settings WHERE name=$1 AND pluginname=$2`
err := p.DB.Get(&val, q, name, p.Config.Name)
if err == sql.ErrNoRows {
return p.Config.Settings[name].Default
}
if err != nil {
log.Info("failed to get plugin setting.", err)
return ""
}
return val
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"GetSetting",
"(",
"name",
"string",
")",
"string",
"{",
"if",
"p",
".",
"Config",
".",
"Settings",
"[",
"name",
"]",
"==",
"nil",
"{",
"pluginName",
":=",
"p",
".",
"Config",
".",
"Name",
"\n",
"if",
"len",
"(",
"pluginName",
")",
"==",
"0",
"{",
"pluginName",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"m",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
",",
"pluginName",
")",
"\n",
"log",
".",
"Fatal",
"(",
"m",
")",
"\n",
"}",
"\n",
"var",
"val",
"string",
"\n",
"q",
":=",
"`SELECT value FROM settings WHERE name=$1 AND pluginname=$2`",
"\n",
"err",
":=",
"p",
".",
"DB",
".",
"Get",
"(",
"&",
"val",
",",
"q",
",",
"name",
",",
"p",
".",
"Config",
".",
"Name",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"p",
".",
"Config",
".",
"Settings",
"[",
"name",
"]",
".",
"Default",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"val",
"\n",
"}"
] | // GetSetting retrieves a specific setting's value. It throws a fatal error if
// the setting has not been declared in the plugin's plugin.json file. | [
"GetSetting",
"retrieves",
"a",
"specific",
"setting",
"s",
"value",
".",
"It",
"throws",
"a",
"fatal",
"error",
"if",
"the",
"setting",
"has",
"not",
"been",
"declared",
"in",
"the",
"plugin",
"s",
"plugin",
".",
"json",
"file",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/plugin.go#L241-L263 |
4,955 | itsabot/itsabot | shared/language/language.go | Greeting | func Greeting(r *rand.Rand, name string) string {
var n int
if len(name) == 0 {
n = r.Intn(3)
switch n {
case 0:
return fmt.Sprintf("Hi, %s.", name)
case 1:
return fmt.Sprintf("Hello, %s.", name)
case 2:
return fmt.Sprintf("Hi there, %s.", name)
}
} else {
n = r.Intn(3)
switch n {
case 0:
return "Hi. How can I help you?"
case 1:
return "Hello. What can I do for you?"
}
}
log.Debug("greeting failed to return a response")
return ""
} | go | func Greeting(r *rand.Rand, name string) string {
var n int
if len(name) == 0 {
n = r.Intn(3)
switch n {
case 0:
return fmt.Sprintf("Hi, %s.", name)
case 1:
return fmt.Sprintf("Hello, %s.", name)
case 2:
return fmt.Sprintf("Hi there, %s.", name)
}
} else {
n = r.Intn(3)
switch n {
case 0:
return "Hi. How can I help you?"
case 1:
return "Hello. What can I do for you?"
}
}
log.Debug("greeting failed to return a response")
return ""
} | [
"func",
"Greeting",
"(",
"r",
"*",
"rand",
".",
"Rand",
",",
"name",
"string",
")",
"string",
"{",
"var",
"n",
"int",
"\n",
"if",
"len",
"(",
"name",
")",
"==",
"0",
"{",
"n",
"=",
"r",
".",
"Intn",
"(",
"3",
")",
"\n",
"switch",
"n",
"{",
"case",
"0",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"case",
"1",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"case",
"2",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"n",
"=",
"r",
".",
"Intn",
"(",
"3",
")",
"\n",
"switch",
"n",
"{",
"case",
"0",
":",
"return",
"\"",
"\"",
"\n",
"case",
"1",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Greeting returns a randomized greeting. | [
"Greeting",
"returns",
"a",
"randomized",
"greeting",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/language.go#L69-L92 |
4,956 | itsabot/itsabot | shared/language/language.go | SuggestedPlace | func SuggestedPlace(s string) string {
n := rand.Intn(4)
switch n {
case 0:
return "How does this place look? " + s
case 1:
return "How about " + s + "?"
case 2:
return "Have you been here before? " + s
case 3:
return "You could try this: " + s
}
log.Debug("suggestedPlace failed to return a response")
return ""
} | go | func SuggestedPlace(s string) string {
n := rand.Intn(4)
switch n {
case 0:
return "How does this place look? " + s
case 1:
return "How about " + s + "?"
case 2:
return "Have you been here before? " + s
case 3:
return "You could try this: " + s
}
log.Debug("suggestedPlace failed to return a response")
return ""
} | [
"func",
"SuggestedPlace",
"(",
"s",
"string",
")",
"string",
"{",
"n",
":=",
"rand",
".",
"Intn",
"(",
"4",
")",
"\n",
"switch",
"n",
"{",
"case",
"0",
":",
"return",
"\"",
"\"",
"+",
"s",
"\n",
"case",
"1",
":",
"return",
"\"",
"\"",
"+",
"s",
"+",
"\"",
"\"",
"\n",
"case",
"2",
":",
"return",
"\"",
"\"",
"+",
"s",
"\n",
"case",
"3",
":",
"return",
"\"",
"\"",
"+",
"s",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // SuggestedPlace returns a randomized place suggestion useful for recommending
// restaurants, businesses, etc. | [
"SuggestedPlace",
"returns",
"a",
"randomized",
"place",
"suggestion",
"useful",
"for",
"recommending",
"restaurants",
"businesses",
"etc",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/language.go#L130-L144 |
4,957 | itsabot/itsabot | shared/language/language.go | SuggestedProduct | func SuggestedProduct(s string, num uint) string {
var n int
var val, flair string
if num > 0 {
n = rand.Intn(3)
switch n {
case 0, 1:
flair = ", then"
case 2: // do nothing
}
}
n = rand.Intn(6)
switch n {
case 0:
val = "I found just the thing"
case 1:
val = "This is the one for you"
case 2:
val = "You'll love this"
case 3:
val = "This is a real treat"
case 4:
val = "This will amaze you"
case 5:
val = "I found just the thing for you"
}
return val + flair + ". " + s
} | go | func SuggestedProduct(s string, num uint) string {
var n int
var val, flair string
if num > 0 {
n = rand.Intn(3)
switch n {
case 0, 1:
flair = ", then"
case 2: // do nothing
}
}
n = rand.Intn(6)
switch n {
case 0:
val = "I found just the thing"
case 1:
val = "This is the one for you"
case 2:
val = "You'll love this"
case 3:
val = "This is a real treat"
case 4:
val = "This will amaze you"
case 5:
val = "I found just the thing for you"
}
return val + flair + ". " + s
} | [
"func",
"SuggestedProduct",
"(",
"s",
"string",
",",
"num",
"uint",
")",
"string",
"{",
"var",
"n",
"int",
"\n",
"var",
"val",
",",
"flair",
"string",
"\n",
"if",
"num",
">",
"0",
"{",
"n",
"=",
"rand",
".",
"Intn",
"(",
"3",
")",
"\n",
"switch",
"n",
"{",
"case",
"0",
",",
"1",
":",
"flair",
"=",
"\"",
"\"",
"\n",
"case",
"2",
":",
"// do nothing",
"}",
"\n",
"}",
"\n",
"n",
"=",
"rand",
".",
"Intn",
"(",
"6",
")",
"\n",
"switch",
"n",
"{",
"case",
"0",
":",
"val",
"=",
"\"",
"\"",
"\n",
"case",
"1",
":",
"val",
"=",
"\"",
"\"",
"\n",
"case",
"2",
":",
"val",
"=",
"\"",
"\"",
"\n",
"case",
"3",
":",
"val",
"=",
"\"",
"\"",
"\n",
"case",
"4",
":",
"val",
"=",
"\"",
"\"",
"\n",
"case",
"5",
":",
"val",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"val",
"+",
"flair",
"+",
"\"",
"\"",
"+",
"s",
"\n",
"}"
] | // SuggestedProduct returns natural language, randomized text for a product
// suggestion. | [
"SuggestedProduct",
"returns",
"natural",
"language",
"randomized",
"text",
"for",
"a",
"product",
"suggestion",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/language.go#L148-L175 |
4,958 | itsabot/itsabot | shared/language/language.go | QuestionLocation | func QuestionLocation(loc string) string {
if len(loc) == 0 {
n := rand.Intn(10)
switch n {
case 0:
return "Where are you?"
case 1:
return "Where are you now?"
case 2:
return "Sure thing. Where are you?"
case 3:
return "Sure thing. Where are you now?"
case 4:
return "Happy to help. Where are you?"
case 5:
return "Happy to help. Where are you now?"
case 6:
return "I can help with that. Where are you?"
case 7:
return "I can help with that. Where are you now?"
case 8:
return "I can help solve this. Where are you?"
case 9:
return "I can help solve this. Where are you now?"
}
}
return fmt.Sprintf("Are you still near %s?", loc)
} | go | func QuestionLocation(loc string) string {
if len(loc) == 0 {
n := rand.Intn(10)
switch n {
case 0:
return "Where are you?"
case 1:
return "Where are you now?"
case 2:
return "Sure thing. Where are you?"
case 3:
return "Sure thing. Where are you now?"
case 4:
return "Happy to help. Where are you?"
case 5:
return "Happy to help. Where are you now?"
case 6:
return "I can help with that. Where are you?"
case 7:
return "I can help with that. Where are you now?"
case 8:
return "I can help solve this. Where are you?"
case 9:
return "I can help solve this. Where are you now?"
}
}
return fmt.Sprintf("Are you still near %s?", loc)
} | [
"func",
"QuestionLocation",
"(",
"loc",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"loc",
")",
"==",
"0",
"{",
"n",
":=",
"rand",
".",
"Intn",
"(",
"10",
")",
"\n",
"switch",
"n",
"{",
"case",
"0",
":",
"return",
"\"",
"\"",
"\n",
"case",
"1",
":",
"return",
"\"",
"\"",
"\n",
"case",
"2",
":",
"return",
"\"",
"\"",
"\n",
"case",
"3",
":",
"return",
"\"",
"\"",
"\n",
"case",
"4",
":",
"return",
"\"",
"\"",
"\n",
"case",
"5",
":",
"return",
"\"",
"\"",
"\n",
"case",
"6",
":",
"return",
"\"",
"\"",
"\n",
"case",
"7",
":",
"return",
"\"",
"\"",
"\n",
"case",
"8",
":",
"return",
"\"",
"\"",
"\n",
"case",
"9",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"loc",
")",
"\n",
"}"
] | // QuestionLocation returns a randomized question asking a user where they are. | [
"QuestionLocation",
"returns",
"a",
"randomized",
"question",
"asking",
"a",
"user",
"where",
"they",
"are",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/language.go#L415-L442 |
4,959 | itsabot/itsabot | shared/language/language.go | Yes | func Yes(s string) bool {
s = strings.ToLower(s)
_, ok := yes[s]
return ok
} | go | func Yes(s string) bool {
s = strings.ToLower(s)
_, ok := yes[s]
return ok
} | [
"func",
"Yes",
"(",
"s",
"string",
")",
"bool",
"{",
"s",
"=",
"strings",
".",
"ToLower",
"(",
"s",
")",
"\n",
"_",
",",
"ok",
":=",
"yes",
"[",
"s",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // Yes determines if a specific word is a positive "Yes" response. For example,
// "yeah" returns true. | [
"Yes",
"determines",
"if",
"a",
"specific",
"word",
"is",
"a",
"positive",
"Yes",
"response",
".",
"For",
"example",
"yeah",
"returns",
"true",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/language.go#L446-L450 |
4,960 | itsabot/itsabot | shared/language/language.go | No | func No(s string) bool {
s = strings.ToLower(s)
_, ok := no[s]
return ok
} | go | func No(s string) bool {
s = strings.ToLower(s)
_, ok := no[s]
return ok
} | [
"func",
"No",
"(",
"s",
"string",
")",
"bool",
"{",
"s",
"=",
"strings",
".",
"ToLower",
"(",
"s",
")",
"\n",
"_",
",",
"ok",
":=",
"no",
"[",
"s",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // No determines if a specific word is a "No" response. For example, "nah"
// returns true. | [
"No",
"determines",
"if",
"a",
"specific",
"word",
"is",
"a",
"No",
"response",
".",
"For",
"example",
"nah",
"returns",
"true",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/language.go#L454-L458 |
4,961 | itsabot/itsabot | shared/language/language.go | RemoveStopWords | func RemoveStopWords(ss []string) []string {
var removal []int
for i, s := range ss {
if Contains(StopWords, s) {
removal = append(removal, i)
}
}
for _, i := range removal {
ss = append(ss[:i], ss[i+1:]...)
}
return ss
} | go | func RemoveStopWords(ss []string) []string {
var removal []int
for i, s := range ss {
if Contains(StopWords, s) {
removal = append(removal, i)
}
}
for _, i := range removal {
ss = append(ss[:i], ss[i+1:]...)
}
return ss
} | [
"func",
"RemoveStopWords",
"(",
"ss",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"var",
"removal",
"[",
"]",
"int",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"ss",
"{",
"if",
"Contains",
"(",
"StopWords",
",",
"s",
")",
"{",
"removal",
"=",
"append",
"(",
"removal",
",",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"i",
":=",
"range",
"removal",
"{",
"ss",
"=",
"append",
"(",
"ss",
"[",
":",
"i",
"]",
",",
"ss",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"return",
"ss",
"\n",
"}"
] | // RemoveStopWords finds and removes stopwords from a slice of strings. | [
"RemoveStopWords",
"finds",
"and",
"removes",
"stopwords",
"from",
"a",
"slice",
"of",
"strings",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/language.go#L573-L584 |
4,962 | itsabot/itsabot | core/log/log.go | New | func New(pluginName string) *Logger {
lg := log.New(os.Stdout, "", log.Ldate|log.Ltime)
if len(pluginName) == 0 {
return &Logger{logger: lg}
}
return &Logger{
prefix: fmt.Sprintf("[%s] ", pluginName),
logger: lg,
}
} | go | func New(pluginName string) *Logger {
lg := log.New(os.Stdout, "", log.Ldate|log.Ltime)
if len(pluginName) == 0 {
return &Logger{logger: lg}
}
return &Logger{
prefix: fmt.Sprintf("[%s] ", pluginName),
logger: lg,
}
} | [
"func",
"New",
"(",
"pluginName",
"string",
")",
"*",
"Logger",
"{",
"lg",
":=",
"log",
".",
"New",
"(",
"os",
".",
"Stdout",
",",
"\"",
"\"",
",",
"log",
".",
"Ldate",
"|",
"log",
".",
"Ltime",
")",
"\n",
"if",
"len",
"(",
"pluginName",
")",
"==",
"0",
"{",
"return",
"&",
"Logger",
"{",
"logger",
":",
"lg",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Logger",
"{",
"prefix",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"pluginName",
")",
",",
"logger",
":",
"lg",
",",
"}",
"\n",
"}"
] | // New returns a Logger which supports a custom prefix representing a plugin's
// name. | [
"New",
"returns",
"a",
"Logger",
"which",
"supports",
"a",
"custom",
"prefix",
"representing",
"a",
"plugin",
"s",
"name",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/log/log.go#L100-L109 |
4,963 | itsabot/itsabot | core/log/log.go | Fatal | func (l *Logger) Fatal(v ...interface{}) {
l.logger.Fatalf("%s", l.prefix+fmt.Sprintln(v...))
} | go | func (l *Logger) Fatal(v ...interface{}) {
l.logger.Fatalf("%s", l.prefix+fmt.Sprintln(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Fatal",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"logger",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"l",
".",
"prefix",
"+",
"fmt",
".",
"Sprintln",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // Fatal logs a statement and kills the running process. | [
"Fatal",
"logs",
"a",
"statement",
"and",
"kills",
"the",
"running",
"process",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/log/log.go#L142-L144 |
4,964 | itsabot/itsabot | shared/task/iterate.go | Iterate | func Iterate(p *dt.Plugin, label string, opts OptsIterate) []dt.State {
if len(label) == 0 {
label = "__iterableStart"
}
return []dt.State{
{
Label: label,
OnEntry: func(in *dt.Msg) string {
var ss []string
mem := p.GetMemory(in, opts.IterableMemKey)
if len(mem.Val) == 0 {
mem.Val = []byte(`[]`)
}
err := json.Unmarshal(mem.Val, &ss)
if err != nil {
p.Log.Info("failed to get iterable memory.", err)
return ""
}
if len(ss) == 0 {
return "I'm afraid I couldn't find any results like that."
}
var idx int64
if p.HasMemory(in, keySelection) {
idx = p.GetMemory(in, keySelection).Int64() + 1
}
if idx >= int64(len(ss)) {
return "I'm afraid that's all I have."
}
p.SetMemory(in, keySelection, idx)
return fmt.Sprintf("How about %s?", ss[idx])
},
OnInput: func(in *dt.Msg) {
yes, err := language.ExtractYesNo(in.Sentence)
if err != nil {
// Yes/No answer not found
return
}
if yes {
idx := p.GetMemory(in, keySelection).Int64()
p.SetMemory(in, opts.ResultMemKeyIdx, idx)
return
}
// TODO handle "next", "something else", etc.
},
Complete: func(in *dt.Msg) (bool, string) {
if p.HasMemory(in, opts.ResultMemKeyIdx) {
return true, ""
}
return false, p.SM.ReplayState(in)
},
},
}
} | go | func Iterate(p *dt.Plugin, label string, opts OptsIterate) []dt.State {
if len(label) == 0 {
label = "__iterableStart"
}
return []dt.State{
{
Label: label,
OnEntry: func(in *dt.Msg) string {
var ss []string
mem := p.GetMemory(in, opts.IterableMemKey)
if len(mem.Val) == 0 {
mem.Val = []byte(`[]`)
}
err := json.Unmarshal(mem.Val, &ss)
if err != nil {
p.Log.Info("failed to get iterable memory.", err)
return ""
}
if len(ss) == 0 {
return "I'm afraid I couldn't find any results like that."
}
var idx int64
if p.HasMemory(in, keySelection) {
idx = p.GetMemory(in, keySelection).Int64() + 1
}
if idx >= int64(len(ss)) {
return "I'm afraid that's all I have."
}
p.SetMemory(in, keySelection, idx)
return fmt.Sprintf("How about %s?", ss[idx])
},
OnInput: func(in *dt.Msg) {
yes, err := language.ExtractYesNo(in.Sentence)
if err != nil {
// Yes/No answer not found
return
}
if yes {
idx := p.GetMemory(in, keySelection).Int64()
p.SetMemory(in, opts.ResultMemKeyIdx, idx)
return
}
// TODO handle "next", "something else", etc.
},
Complete: func(in *dt.Msg) (bool, string) {
if p.HasMemory(in, opts.ResultMemKeyIdx) {
return true, ""
}
return false, p.SM.ReplayState(in)
},
},
}
} | [
"func",
"Iterate",
"(",
"p",
"*",
"dt",
".",
"Plugin",
",",
"label",
"string",
",",
"opts",
"OptsIterate",
")",
"[",
"]",
"dt",
".",
"State",
"{",
"if",
"len",
"(",
"label",
")",
"==",
"0",
"{",
"label",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"[",
"]",
"dt",
".",
"State",
"{",
"{",
"Label",
":",
"label",
",",
"OnEntry",
":",
"func",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"string",
"{",
"var",
"ss",
"[",
"]",
"string",
"\n",
"mem",
":=",
"p",
".",
"GetMemory",
"(",
"in",
",",
"opts",
".",
"IterableMemKey",
")",
"\n",
"if",
"len",
"(",
"mem",
".",
"Val",
")",
"==",
"0",
"{",
"mem",
".",
"Val",
"=",
"[",
"]",
"byte",
"(",
"`[]`",
")",
"\n",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"mem",
".",
"Val",
",",
"&",
"ss",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ss",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"var",
"idx",
"int64",
"\n",
"if",
"p",
".",
"HasMemory",
"(",
"in",
",",
"keySelection",
")",
"{",
"idx",
"=",
"p",
".",
"GetMemory",
"(",
"in",
",",
"keySelection",
")",
".",
"Int64",
"(",
")",
"+",
"1",
"\n",
"}",
"\n",
"if",
"idx",
">=",
"int64",
"(",
"len",
"(",
"ss",
")",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"p",
".",
"SetMemory",
"(",
"in",
",",
"keySelection",
",",
"idx",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ss",
"[",
"idx",
"]",
")",
"\n",
"}",
",",
"OnInput",
":",
"func",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"{",
"yes",
",",
"err",
":=",
"language",
".",
"ExtractYesNo",
"(",
"in",
".",
"Sentence",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Yes/No answer not found",
"return",
"\n",
"}",
"\n",
"if",
"yes",
"{",
"idx",
":=",
"p",
".",
"GetMemory",
"(",
"in",
",",
"keySelection",
")",
".",
"Int64",
"(",
")",
"\n",
"p",
".",
"SetMemory",
"(",
"in",
",",
"opts",
".",
"ResultMemKeyIdx",
",",
"idx",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// TODO handle \"next\", \"something else\", etc.",
"}",
",",
"Complete",
":",
"func",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"(",
"bool",
",",
"string",
")",
"{",
"if",
"p",
".",
"HasMemory",
"(",
"in",
",",
"opts",
".",
"ResultMemKeyIdx",
")",
"{",
"return",
"true",
",",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"false",
",",
"p",
".",
"SM",
".",
"ReplayState",
"(",
"in",
")",
"\n",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // Iterate through a set of options allowing the user to select one before
// continuing. | [
"Iterate",
"through",
"a",
"set",
"of",
"options",
"allowing",
"the",
"user",
"to",
"select",
"one",
"before",
"continuing",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/task/iterate.go#L27-L79 |
4,965 | itsabot/itsabot | shared/task/iterate.go | ResetIterate | func ResetIterate(p *dt.Plugin, in *dt.Msg) {
p.DeleteMemory(in, keySelection)
} | go | func ResetIterate(p *dt.Plugin, in *dt.Msg) {
p.DeleteMemory(in, keySelection)
} | [
"func",
"ResetIterate",
"(",
"p",
"*",
"dt",
".",
"Plugin",
",",
"in",
"*",
"dt",
".",
"Msg",
")",
"{",
"p",
".",
"DeleteMemory",
"(",
"in",
",",
"keySelection",
")",
"\n",
"}"
] | // ResetIterate should be called from within your plugin's SetOnReset function
// if you use the Iterable task. | [
"ResetIterate",
"should",
"be",
"called",
"from",
"within",
"your",
"plugin",
"s",
"SetOnReset",
"function",
"if",
"you",
"use",
"the",
"Iterable",
"task",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/task/iterate.go#L83-L85 |
4,966 | itsabot/itsabot | shared/datatypes/http_route.go | AddRoutes | func (hm HandlerMap) AddRoutes(prefix string, r *httprouter.Router) {
for httpRoute, h := range hm {
p := path.Join("/", prefix, httpRoute.Path)
r.HandlerFunc(httpRoute.Method, p, h)
}
} | go | func (hm HandlerMap) AddRoutes(prefix string, r *httprouter.Router) {
for httpRoute, h := range hm {
p := path.Join("/", prefix, httpRoute.Path)
r.HandlerFunc(httpRoute.Method, p, h)
}
} | [
"func",
"(",
"hm",
"HandlerMap",
")",
"AddRoutes",
"(",
"prefix",
"string",
",",
"r",
"*",
"httprouter",
".",
"Router",
")",
"{",
"for",
"httpRoute",
",",
"h",
":=",
"range",
"hm",
"{",
"p",
":=",
"path",
".",
"Join",
"(",
"\"",
"\"",
",",
"prefix",
",",
"httpRoute",
".",
"Path",
")",
"\n",
"r",
".",
"HandlerFunc",
"(",
"httpRoute",
".",
"Method",
",",
"p",
",",
"h",
")",
"\n",
"}",
"\n",
"}"
] | // AddRoutes to the router dynamically, enabling drivers to add routes to an
// application at runtime usually as part of their initialization. | [
"AddRoutes",
"to",
"the",
"router",
"dynamically",
"enabling",
"drivers",
"to",
"add",
"routes",
"to",
"an",
"application",
"at",
"runtime",
"usually",
"as",
"part",
"of",
"their",
"initialization",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/http_route.go#L29-L34 |
4,967 | itsabot/itsabot | shared/datatypes/http_route.go | NewHandlerMap | func NewHandlerMap(rhs []RouteHandler) HandlerMap {
hm := HandlerMap{}
for _, rh := range rhs {
route := HTTPRoute{
Path: rh.Path,
Method: rh.Method,
}
hm[route] = rh.Handler
}
return hm
} | go | func NewHandlerMap(rhs []RouteHandler) HandlerMap {
hm := HandlerMap{}
for _, rh := range rhs {
route := HTTPRoute{
Path: rh.Path,
Method: rh.Method,
}
hm[route] = rh.Handler
}
return hm
} | [
"func",
"NewHandlerMap",
"(",
"rhs",
"[",
"]",
"RouteHandler",
")",
"HandlerMap",
"{",
"hm",
":=",
"HandlerMap",
"{",
"}",
"\n",
"for",
"_",
",",
"rh",
":=",
"range",
"rhs",
"{",
"route",
":=",
"HTTPRoute",
"{",
"Path",
":",
"rh",
".",
"Path",
",",
"Method",
":",
"rh",
".",
"Method",
",",
"}",
"\n",
"hm",
"[",
"route",
"]",
"=",
"rh",
".",
"Handler",
"\n",
"}",
"\n",
"return",
"hm",
"\n",
"}"
] | // NewHandlerMap builds a HandlerMap from a slice of RouteHandlers. This is a
// convenience function, since using RouteHandlers directly is very verbose for
// plugins. | [
"NewHandlerMap",
"builds",
"a",
"HandlerMap",
"from",
"a",
"slice",
"of",
"RouteHandlers",
".",
"This",
"is",
"a",
"convenience",
"function",
"since",
"using",
"RouteHandlers",
"directly",
"is",
"very",
"verbose",
"for",
"plugins",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/http_route.go#L39-L49 |
4,968 | itsabot/itsabot | shared/interface/sms/sms.go | Send | func (c *Conn) Send(to, msg string) error {
return c.conn.Send(to, msg)
} | go | func (c *Conn) Send(to, msg string) error {
return c.conn.Send(to, msg)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Send",
"(",
"to",
",",
"msg",
"string",
")",
"error",
"{",
"return",
"c",
".",
"conn",
".",
"Send",
"(",
"to",
",",
"msg",
")",
"\n",
"}"
] | // Send an SMS message through an opened driver connection. The from number is
// handled by the driver. | [
"Send",
"an",
"SMS",
"message",
"through",
"an",
"opened",
"driver",
"connection",
".",
"The",
"from",
"number",
"is",
"handled",
"by",
"the",
"driver",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/interface/sms/sms.go#L77-L79 |
4,969 | itsabot/itsabot | shared/language/summarize.go | Contains | func Contains(wordList []string, s string) bool {
s = strings.TrimRight(strings.ToLower(s), ".,;:!?'\"")
for _, word := range wordList {
if s == word {
return true
}
}
return false
} | go | func Contains(wordList []string, s string) bool {
s = strings.TrimRight(strings.ToLower(s), ".,;:!?'\"")
for _, word := range wordList {
if s == word {
return true
}
}
return false
} | [
"func",
"Contains",
"(",
"wordList",
"[",
"]",
"string",
",",
"s",
"string",
")",
"bool",
"{",
"s",
"=",
"strings",
".",
"TrimRight",
"(",
"strings",
".",
"ToLower",
"(",
"s",
")",
",",
"\"",
"\\\"",
"\"",
")",
"\n",
"for",
"_",
",",
"word",
":=",
"range",
"wordList",
"{",
"if",
"s",
"==",
"word",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Contains determines whether a slice of strings contains a specific word. | [
"Contains",
"determines",
"whether",
"a",
"slice",
"of",
"strings",
"contains",
"a",
"specific",
"word",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/summarize.go#L6-L14 |
4,970 | itsabot/itsabot | core/handlers.go | newRouter | func newRouter() *httprouter.Router {
router := httprouter.New()
router.ServeFiles("/public/*filepath", http.Dir("public"))
if os.Getenv("ABOT_ENV") != "production" {
initCMDGroup(router)
}
// Web routes
router.HandlerFunc("GET", "/", hIndex)
router.HandlerFunc("POST", "/", hMain)
router.HandlerFunc("OPTIONS", "/", hOptions)
// Route any unknown request to our single page app front-end
router.NotFound = http.HandlerFunc(hIndex)
// API routes (no restrictions)
router.HandlerFunc("POST", "/api/login.json", hapiLoginSubmit)
router.HandlerFunc("POST", "/api/logout.json", hapiLogoutSubmit)
router.HandlerFunc("POST", "/api/signup.json", hapiSignupSubmit)
router.HandlerFunc("POST", "/api/forgot_password.json", hapiForgotPasswordSubmit)
router.HandlerFunc("POST", "/api/reset_password.json", hapiResetPasswordSubmit)
router.HandlerFunc("GET", "/api/admin_exists.json", hapiAdminExists)
// API routes (restricted by login)
router.HandlerFunc("GET", "/api/user/profile.json", hapiProfile)
router.HandlerFunc("PUT", "/api/user/profile.json", hapiProfileView)
// API routes (restricted to admins)
router.HandlerFunc("GET", "/api/admin/plugins.json", hapiPlugins)
router.HandlerFunc("GET", "/api/admin/conversations_need_training.json", hapiConversationsNeedTraining)
router.Handle("GET", "/api/admin/conversations/:uid/:fid/:fidt/:off", hapiConversation)
router.HandlerFunc("PATCH", "/api/admin/conversations.json", hapiConversationsUpdate)
router.HandlerFunc("POST", "/api/admins/send_message.json", hapiSendMessage)
router.HandlerFunc("GET", "/api/admins.json", hapiAdmins)
router.HandlerFunc("PUT", "/api/admins.json", hapiAdminsUpdate)
router.HandlerFunc("GET", "/api/admin/remote_tokens.json", hapiRemoteTokens)
router.HandlerFunc("POST", "/api/admin/remote_tokens.json", hapiRemoteTokensSubmit)
router.HandlerFunc("DELETE", "/api/admin/remote_tokens.json", hapiRemoteTokensDelete)
router.HandlerFunc("PUT", "/api/admin/settings.json", hapiSettingsUpdate)
router.HandlerFunc("GET", "/api/admin/dashboard.json", hapiDashboard)
return router
} | go | func newRouter() *httprouter.Router {
router := httprouter.New()
router.ServeFiles("/public/*filepath", http.Dir("public"))
if os.Getenv("ABOT_ENV") != "production" {
initCMDGroup(router)
}
// Web routes
router.HandlerFunc("GET", "/", hIndex)
router.HandlerFunc("POST", "/", hMain)
router.HandlerFunc("OPTIONS", "/", hOptions)
// Route any unknown request to our single page app front-end
router.NotFound = http.HandlerFunc(hIndex)
// API routes (no restrictions)
router.HandlerFunc("POST", "/api/login.json", hapiLoginSubmit)
router.HandlerFunc("POST", "/api/logout.json", hapiLogoutSubmit)
router.HandlerFunc("POST", "/api/signup.json", hapiSignupSubmit)
router.HandlerFunc("POST", "/api/forgot_password.json", hapiForgotPasswordSubmit)
router.HandlerFunc("POST", "/api/reset_password.json", hapiResetPasswordSubmit)
router.HandlerFunc("GET", "/api/admin_exists.json", hapiAdminExists)
// API routes (restricted by login)
router.HandlerFunc("GET", "/api/user/profile.json", hapiProfile)
router.HandlerFunc("PUT", "/api/user/profile.json", hapiProfileView)
// API routes (restricted to admins)
router.HandlerFunc("GET", "/api/admin/plugins.json", hapiPlugins)
router.HandlerFunc("GET", "/api/admin/conversations_need_training.json", hapiConversationsNeedTraining)
router.Handle("GET", "/api/admin/conversations/:uid/:fid/:fidt/:off", hapiConversation)
router.HandlerFunc("PATCH", "/api/admin/conversations.json", hapiConversationsUpdate)
router.HandlerFunc("POST", "/api/admins/send_message.json", hapiSendMessage)
router.HandlerFunc("GET", "/api/admins.json", hapiAdmins)
router.HandlerFunc("PUT", "/api/admins.json", hapiAdminsUpdate)
router.HandlerFunc("GET", "/api/admin/remote_tokens.json", hapiRemoteTokens)
router.HandlerFunc("POST", "/api/admin/remote_tokens.json", hapiRemoteTokensSubmit)
router.HandlerFunc("DELETE", "/api/admin/remote_tokens.json", hapiRemoteTokensDelete)
router.HandlerFunc("PUT", "/api/admin/settings.json", hapiSettingsUpdate)
router.HandlerFunc("GET", "/api/admin/dashboard.json", hapiDashboard)
return router
} | [
"func",
"newRouter",
"(",
")",
"*",
"httprouter",
".",
"Router",
"{",
"router",
":=",
"httprouter",
".",
"New",
"(",
")",
"\n",
"router",
".",
"ServeFiles",
"(",
"\"",
"\"",
",",
"http",
".",
"Dir",
"(",
"\"",
"\"",
")",
")",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"initCMDGroup",
"(",
"router",
")",
"\n",
"}",
"\n\n",
"// Web routes",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hIndex",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hMain",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hOptions",
")",
"\n\n",
"// Route any unknown request to our single page app front-end",
"router",
".",
"NotFound",
"=",
"http",
".",
"HandlerFunc",
"(",
"hIndex",
")",
"\n\n",
"// API routes (no restrictions)",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiLoginSubmit",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiLogoutSubmit",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiSignupSubmit",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiForgotPasswordSubmit",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiResetPasswordSubmit",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiAdminExists",
")",
"\n\n",
"// API routes (restricted by login)",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiProfile",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiProfileView",
")",
"\n\n",
"// API routes (restricted to admins)",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiPlugins",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiConversationsNeedTraining",
")",
"\n",
"router",
".",
"Handle",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiConversation",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiConversationsUpdate",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiSendMessage",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiAdmins",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiAdminsUpdate",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiRemoteTokens",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiRemoteTokensSubmit",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiRemoteTokensDelete",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiSettingsUpdate",
")",
"\n",
"router",
".",
"HandlerFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hapiDashboard",
")",
"\n",
"return",
"router",
"\n",
"}"
] | // newRouter initializes and returns a router. | [
"newRouter",
"initializes",
"and",
"returns",
"a",
"router",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L42-L84 |
4,971 | itsabot/itsabot | core/handlers.go | hIndex | func hIndex(w http.ResponseWriter, r *http.Request) {
var err error
env := os.Getenv("ABOT_ENV")
if env != "production" && env != "test" {
p := filepath.Join("assets", "html", "layout.html")
tmplLayout, err = template.ParseFiles(p)
if err != nil {
writeErrorInternal(w, err)
return
}
if err = compileAssets(); err != nil {
writeErrorInternal(w, err)
return
}
}
data := struct {
IsProd bool
ItsAbotURL string
}{
IsProd: os.Getenv("ABOT_ENV") == "production",
ItsAbotURL: os.Getenv("ITSABOT_URL"),
}
if err = tmplLayout.Execute(w, data); err != nil {
writeErrorInternal(w, err)
}
} | go | func hIndex(w http.ResponseWriter, r *http.Request) {
var err error
env := os.Getenv("ABOT_ENV")
if env != "production" && env != "test" {
p := filepath.Join("assets", "html", "layout.html")
tmplLayout, err = template.ParseFiles(p)
if err != nil {
writeErrorInternal(w, err)
return
}
if err = compileAssets(); err != nil {
writeErrorInternal(w, err)
return
}
}
data := struct {
IsProd bool
ItsAbotURL string
}{
IsProd: os.Getenv("ABOT_ENV") == "production",
ItsAbotURL: os.Getenv("ITSABOT_URL"),
}
if err = tmplLayout.Execute(w, data); err != nil {
writeErrorInternal(w, err)
}
} | [
"func",
"hIndex",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"err",
"error",
"\n",
"env",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"env",
"!=",
"\"",
"\"",
"&&",
"env",
"!=",
"\"",
"\"",
"{",
"p",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"tmplLayout",
",",
"err",
"=",
"template",
".",
"ParseFiles",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"compileAssets",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"data",
":=",
"struct",
"{",
"IsProd",
"bool",
"\n",
"ItsAbotURL",
"string",
"\n",
"}",
"{",
"IsProd",
":",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
",",
"ItsAbotURL",
":",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"if",
"err",
"=",
"tmplLayout",
".",
"Execute",
"(",
"w",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // hIndex presents the homepage to the user and populates the HTML with
// server-side variables. | [
"hIndex",
"presents",
"the",
"homepage",
"to",
"the",
"user",
"and",
"populates",
"the",
"HTML",
"with",
"server",
"-",
"side",
"variables",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L88-L113 |
4,972 | itsabot/itsabot | core/handlers.go | hMain | func hMain(w http.ResponseWriter, r *http.Request) {
errMsg := "Something went wrong with my wiring... I'll get that fixed up soon."
ret, err := ProcessText(r)
if err != nil {
if len(ret) > 0 {
ret = errMsg
}
log.Info("failed to process text.", err)
// TODO notify plugins listening for errors
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Origin")
_, err = fmt.Fprint(w, ret)
if err != nil {
writeErrorInternal(w, err)
}
} | go | func hMain(w http.ResponseWriter, r *http.Request) {
errMsg := "Something went wrong with my wiring... I'll get that fixed up soon."
ret, err := ProcessText(r)
if err != nil {
if len(ret) > 0 {
ret = errMsg
}
log.Info("failed to process text.", err)
// TODO notify plugins listening for errors
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Origin")
_, err = fmt.Fprint(w, ret)
if err != nil {
writeErrorInternal(w, err)
}
} | [
"func",
"hMain",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"errMsg",
":=",
"\"",
"\"",
"\n",
"ret",
",",
"err",
":=",
"ProcessText",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"len",
"(",
"ret",
")",
">",
"0",
"{",
"ret",
"=",
"errMsg",
"\n",
"}",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"// TODO notify plugins listening for errors",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"_",
",",
"err",
"=",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"ret",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // hMain is the endpoint to hit when you want a direct response via JSON.
// The Abot console uses this endpoint. | [
"hMain",
"is",
"the",
"endpoint",
"to",
"hit",
"when",
"you",
"want",
"a",
"direct",
"response",
"via",
"JSON",
".",
"The",
"Abot",
"console",
"uses",
"this",
"endpoint",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L117-L133 |
4,973 | itsabot/itsabot | core/handlers.go | hOptions | func hOptions(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Origin")
w.WriteHeader(http.StatusOK)
} | go | func hOptions(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Origin")
w.WriteHeader(http.StatusOK)
} | [
"func",
"hOptions",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // hOptions sets appropriate response headers in cases like browser-based
// communication with Abot. | [
"hOptions",
"sets",
"appropriate",
"response",
"headers",
"in",
"cases",
"like",
"browser",
"-",
"based",
"communication",
"with",
"Abot",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L137-L141 |
4,974 | itsabot/itsabot | core/handlers.go | hapiLogoutSubmit | func hapiLogoutSubmit(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("id")
if err != nil {
writeError(w, err)
return
}
uid := cookie.Value
if uid == "null" {
http.Error(w, "id was null", http.StatusBadRequest)
return
}
q := `DELETE FROM sessions WHERE userid=$1`
if _, err = db.Exec(q, uid); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | go | func hapiLogoutSubmit(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("id")
if err != nil {
writeError(w, err)
return
}
uid := cookie.Value
if uid == "null" {
http.Error(w, "id was null", http.StatusBadRequest)
return
}
q := `DELETE FROM sessions WHERE userid=$1`
if _, err = db.Exec(q, uid); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | [
"func",
"hapiLogoutSubmit",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"uid",
":=",
"cookie",
".",
"Value",
"\n",
"if",
"uid",
"==",
"\"",
"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"q",
":=",
"`DELETE FROM sessions WHERE userid=$1`",
"\n",
"if",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"q",
",",
"uid",
")",
";",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // hapiLogoutSubmit processes a logout request deleting the session from
// the server. | [
"hapiLogoutSubmit",
"processes",
"a",
"logout",
"request",
"deleting",
"the",
"session",
"from",
"the",
"server",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L145-L162 |
4,975 | itsabot/itsabot | core/handlers.go | hapiLoginSubmit | func hapiLoginSubmit(w http.ResponseWriter, r *http.Request) {
var req struct {
Email string
Password string
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorInternal(w, err)
return
}
var u struct {
ID uint64
Password []byte
Admin bool
}
q := `SELECT id, password, admin FROM users WHERE email=$1`
err := db.Get(&u, q, req.Email)
if err == sql.ErrNoRows {
writeErrorAuth(w, ErrInvalidUserPass)
return
} else if err != nil {
writeErrorInternal(w, err)
return
}
if u.ID == 0 {
writeErrorAuth(w, ErrInvalidUserPass)
return
}
err = bcrypt.CompareHashAndPassword(u.Password, []byte(req.Password))
if err == bcrypt.ErrMismatchedHashAndPassword || err == bcrypt.ErrHashTooShort {
writeErrorAuth(w, ErrInvalidUserPass)
return
} else if err != nil {
writeErrorInternal(w, err)
return
}
user := &dt.User{
ID: u.ID,
Email: req.Email,
Admin: u.Admin,
}
csrfToken, err := createCSRFToken(user)
if err != nil {
writeErrorInternal(w, err)
return
}
header, token, err := getAuthToken(user)
if err != nil {
writeErrorInternal(w, err)
return
}
resp := struct {
ID uint64
Email string
Scopes []string
AuthToken string
IssuedAt int64
CSRFToken string
}{
ID: user.ID,
Email: user.Email,
Scopes: header.Scopes,
AuthToken: token,
IssuedAt: header.IssuedAt,
CSRFToken: csrfToken,
}
writeBytes(w, resp)
} | go | func hapiLoginSubmit(w http.ResponseWriter, r *http.Request) {
var req struct {
Email string
Password string
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorInternal(w, err)
return
}
var u struct {
ID uint64
Password []byte
Admin bool
}
q := `SELECT id, password, admin FROM users WHERE email=$1`
err := db.Get(&u, q, req.Email)
if err == sql.ErrNoRows {
writeErrorAuth(w, ErrInvalidUserPass)
return
} else if err != nil {
writeErrorInternal(w, err)
return
}
if u.ID == 0 {
writeErrorAuth(w, ErrInvalidUserPass)
return
}
err = bcrypt.CompareHashAndPassword(u.Password, []byte(req.Password))
if err == bcrypt.ErrMismatchedHashAndPassword || err == bcrypt.ErrHashTooShort {
writeErrorAuth(w, ErrInvalidUserPass)
return
} else if err != nil {
writeErrorInternal(w, err)
return
}
user := &dt.User{
ID: u.ID,
Email: req.Email,
Admin: u.Admin,
}
csrfToken, err := createCSRFToken(user)
if err != nil {
writeErrorInternal(w, err)
return
}
header, token, err := getAuthToken(user)
if err != nil {
writeErrorInternal(w, err)
return
}
resp := struct {
ID uint64
Email string
Scopes []string
AuthToken string
IssuedAt int64
CSRFToken string
}{
ID: user.ID,
Email: user.Email,
Scopes: header.Scopes,
AuthToken: token,
IssuedAt: header.IssuedAt,
CSRFToken: csrfToken,
}
writeBytes(w, resp)
} | [
"func",
"hapiLoginSubmit",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"req",
"struct",
"{",
"Email",
"string",
"\n",
"Password",
"string",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"u",
"struct",
"{",
"ID",
"uint64",
"\n",
"Password",
"[",
"]",
"byte",
"\n",
"Admin",
"bool",
"\n",
"}",
"\n",
"q",
":=",
"`SELECT id, password, admin FROM users WHERE email=$1`",
"\n",
"err",
":=",
"db",
".",
"Get",
"(",
"&",
"u",
",",
"q",
",",
"req",
".",
"Email",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"writeErrorAuth",
"(",
"w",
",",
"ErrInvalidUserPass",
")",
"\n",
"return",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"u",
".",
"ID",
"==",
"0",
"{",
"writeErrorAuth",
"(",
"w",
",",
"ErrInvalidUserPass",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"bcrypt",
".",
"CompareHashAndPassword",
"(",
"u",
".",
"Password",
",",
"[",
"]",
"byte",
"(",
"req",
".",
"Password",
")",
")",
"\n",
"if",
"err",
"==",
"bcrypt",
".",
"ErrMismatchedHashAndPassword",
"||",
"err",
"==",
"bcrypt",
".",
"ErrHashTooShort",
"{",
"writeErrorAuth",
"(",
"w",
",",
"ErrInvalidUserPass",
")",
"\n",
"return",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"user",
":=",
"&",
"dt",
".",
"User",
"{",
"ID",
":",
"u",
".",
"ID",
",",
"Email",
":",
"req",
".",
"Email",
",",
"Admin",
":",
"u",
".",
"Admin",
",",
"}",
"\n",
"csrfToken",
",",
"err",
":=",
"createCSRFToken",
"(",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"header",
",",
"token",
",",
"err",
":=",
"getAuthToken",
"(",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"resp",
":=",
"struct",
"{",
"ID",
"uint64",
"\n",
"Email",
"string",
"\n",
"Scopes",
"[",
"]",
"string",
"\n",
"AuthToken",
"string",
"\n",
"IssuedAt",
"int64",
"\n",
"CSRFToken",
"string",
"\n",
"}",
"{",
"ID",
":",
"user",
".",
"ID",
",",
"Email",
":",
"user",
".",
"Email",
",",
"Scopes",
":",
"header",
".",
"Scopes",
",",
"AuthToken",
":",
"token",
",",
"IssuedAt",
":",
"header",
".",
"IssuedAt",
",",
"CSRFToken",
":",
"csrfToken",
",",
"}",
"\n",
"writeBytes",
"(",
"w",
",",
"resp",
")",
"\n",
"}"
] | // hapiLoginSubmit processes a logout request deleting the session from
// the server. | [
"hapiLoginSubmit",
"processes",
"a",
"logout",
"request",
"deleting",
"the",
"session",
"from",
"the",
"server",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L166-L232 |
4,976 | itsabot/itsabot | core/handlers.go | hapiProfile | func hapiProfile(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isLoggedIn(w, r) {
return
}
}
cookie, err := r.Cookie("id")
if err != nil {
writeErrorInternal(w, err)
return
}
uid := cookie.Value
var user struct {
Name string
Email string
Phones []dt.Phone
}
q := `SELECT name, email FROM users WHERE id=$1`
err = db.Get(&user, q, uid)
if err != nil {
writeErrorInternal(w, err)
return
}
q = `SELECT flexid FROM userflexids
WHERE flexidtype=2 AND userid=$1
LIMIT 10`
err = db.Select(&user.Phones, q, uid)
if err != nil && err != sql.ErrNoRows {
writeErrorInternal(w, err)
return
}
writeBytes(w, user)
} | go | func hapiProfile(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isLoggedIn(w, r) {
return
}
}
cookie, err := r.Cookie("id")
if err != nil {
writeErrorInternal(w, err)
return
}
uid := cookie.Value
var user struct {
Name string
Email string
Phones []dt.Phone
}
q := `SELECT name, email FROM users WHERE id=$1`
err = db.Get(&user, q, uid)
if err != nil {
writeErrorInternal(w, err)
return
}
q = `SELECT flexid FROM userflexids
WHERE flexidtype=2 AND userid=$1
LIMIT 10`
err = db.Select(&user.Phones, q, uid)
if err != nil && err != sql.ErrNoRows {
writeErrorInternal(w, err)
return
}
writeBytes(w, user)
} | [
"func",
"hapiProfile",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"uid",
":=",
"cookie",
".",
"Value",
"\n",
"var",
"user",
"struct",
"{",
"Name",
"string",
"\n",
"Email",
"string",
"\n",
"Phones",
"[",
"]",
"dt",
".",
"Phone",
"\n",
"}",
"\n",
"q",
":=",
"`SELECT name, email FROM users WHERE id=$1`",
"\n",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"user",
",",
"q",
",",
"uid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"q",
"=",
"`SELECT flexid FROM userflexids\n\t WHERE flexidtype=2 AND userid=$1\n\t LIMIT 10`",
"\n",
"err",
"=",
"db",
".",
"Select",
"(",
"&",
"user",
".",
"Phones",
",",
"q",
",",
"uid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"sql",
".",
"ErrNoRows",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"writeBytes",
"(",
"w",
",",
"user",
")",
"\n",
"}"
] | // hapiProfile shows a user profile with the user's current addresses, credit
// cards, and contact information. | [
"hapiProfile",
"shows",
"a",
"user",
"profile",
"with",
"the",
"user",
"s",
"current",
"addresses",
"credit",
"cards",
"and",
"contact",
"information",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L346-L378 |
4,977 | itsabot/itsabot | core/handlers.go | hapiForgotPasswordSubmit | func hapiForgotPasswordSubmit(w http.ResponseWriter, r *http.Request) {
var req struct{ Email string }
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorInternal(w, err)
return
}
var user dt.User
q := `SELECT id, name, email FROM users WHERE email=$1`
err := db.Get(&user, q, req.Email)
if err == sql.ErrNoRows {
writeError(w, errors.New("Sorry, there's no record of that email. Are you sure that's the email you used to sign up with and that you typed it correctly?"))
return
}
if err != nil {
writeError(w, err)
return
}
secret := RandSeq(40)
q = `INSERT INTO passwordresets (userid, secret) VALUES ($1, $2)`
if _, err = db.Exec(q, user.ID, secret); err != nil {
writeError(w, err)
return
}
if len(emailsender.Drivers()) == 0 {
writeError(w, errors.New("Sorry, this feature is not enabled. To be enabled, an email driver must be imported."))
return
}
w.WriteHeader(http.StatusOK)
} | go | func hapiForgotPasswordSubmit(w http.ResponseWriter, r *http.Request) {
var req struct{ Email string }
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorInternal(w, err)
return
}
var user dt.User
q := `SELECT id, name, email FROM users WHERE email=$1`
err := db.Get(&user, q, req.Email)
if err == sql.ErrNoRows {
writeError(w, errors.New("Sorry, there's no record of that email. Are you sure that's the email you used to sign up with and that you typed it correctly?"))
return
}
if err != nil {
writeError(w, err)
return
}
secret := RandSeq(40)
q = `INSERT INTO passwordresets (userid, secret) VALUES ($1, $2)`
if _, err = db.Exec(q, user.ID, secret); err != nil {
writeError(w, err)
return
}
if len(emailsender.Drivers()) == 0 {
writeError(w, errors.New("Sorry, this feature is not enabled. To be enabled, an email driver must be imported."))
return
}
w.WriteHeader(http.StatusOK)
} | [
"func",
"hapiForgotPasswordSubmit",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"req",
"struct",
"{",
"Email",
"string",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"user",
"dt",
".",
"User",
"\n",
"q",
":=",
"`SELECT id, name, email FROM users WHERE email=$1`",
"\n",
"err",
":=",
"db",
".",
"Get",
"(",
"&",
"user",
",",
"q",
",",
"req",
".",
"Email",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"writeError",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"secret",
":=",
"RandSeq",
"(",
"40",
")",
"\n",
"q",
"=",
"`INSERT INTO passwordresets (userid, secret) VALUES ($1, $2)`",
"\n",
"if",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"q",
",",
"user",
".",
"ID",
",",
"secret",
")",
";",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"len",
"(",
"emailsender",
".",
"Drivers",
"(",
")",
")",
"==",
"0",
"{",
"writeError",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // hapiForgotPasswordSubmit asks the server to send the user a "Forgot
// Password" email with instructions for resetting their password. | [
"hapiForgotPasswordSubmit",
"asks",
"the",
"server",
"to",
"send",
"the",
"user",
"a",
"Forgot",
"Password",
"email",
"with",
"instructions",
"for",
"resetting",
"their",
"password",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L429-L457 |
4,978 | itsabot/itsabot | core/handlers.go | hapiResetPasswordSubmit | func hapiResetPasswordSubmit(w http.ResponseWriter, r *http.Request) {
var req struct {
Password string
Secret string
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorInternal(w, err)
return
}
if len(req.Password) < 8 {
writeError(w, errors.New("Your password must be at least 8 characters"))
return
}
var uid uint64
q := `SELECT userid FROM passwordresets
WHERE secret=$1 AND
createdat >= CURRENT_TIMESTAMP - interval '30 minutes'`
err := db.Get(&uid, q, req.Secret)
if err == sql.ErrNoRows {
writeError(w, errors.New("Sorry, that information doesn't match our records."))
return
}
if err != nil {
writeError(w, err)
return
}
hpw, err := bcrypt.GenerateFromPassword([]byte(req.Password), 10)
if err != nil {
writeError(w, err)
return
}
tx, err := db.Begin()
if err != nil {
writeError(w, err)
return
}
q = `UPDATE users SET password=$1 WHERE id=$2`
if _, err = tx.Exec(q, hpw, uid); err != nil {
writeError(w, err)
return
}
q = `DELETE FROM passwordresets WHERE secret=$1`
if _, err = tx.Exec(q, req.Secret); err != nil {
writeError(w, err)
return
}
if err = tx.Commit(); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | go | func hapiResetPasswordSubmit(w http.ResponseWriter, r *http.Request) {
var req struct {
Password string
Secret string
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorInternal(w, err)
return
}
if len(req.Password) < 8 {
writeError(w, errors.New("Your password must be at least 8 characters"))
return
}
var uid uint64
q := `SELECT userid FROM passwordresets
WHERE secret=$1 AND
createdat >= CURRENT_TIMESTAMP - interval '30 minutes'`
err := db.Get(&uid, q, req.Secret)
if err == sql.ErrNoRows {
writeError(w, errors.New("Sorry, that information doesn't match our records."))
return
}
if err != nil {
writeError(w, err)
return
}
hpw, err := bcrypt.GenerateFromPassword([]byte(req.Password), 10)
if err != nil {
writeError(w, err)
return
}
tx, err := db.Begin()
if err != nil {
writeError(w, err)
return
}
q = `UPDATE users SET password=$1 WHERE id=$2`
if _, err = tx.Exec(q, hpw, uid); err != nil {
writeError(w, err)
return
}
q = `DELETE FROM passwordresets WHERE secret=$1`
if _, err = tx.Exec(q, req.Secret); err != nil {
writeError(w, err)
return
}
if err = tx.Commit(); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | [
"func",
"hapiResetPasswordSubmit",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"req",
"struct",
"{",
"Password",
"string",
"\n",
"Secret",
"string",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"len",
"(",
"req",
".",
"Password",
")",
"<",
"8",
"{",
"writeError",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"var",
"uid",
"uint64",
"\n",
"q",
":=",
"`SELECT userid FROM passwordresets\n\t WHERE secret=$1 AND\n\t createdat >= CURRENT_TIMESTAMP - interval '30 minutes'`",
"\n",
"err",
":=",
"db",
".",
"Get",
"(",
"&",
"uid",
",",
"q",
",",
"req",
".",
"Secret",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"writeError",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"hpw",
",",
"err",
":=",
"bcrypt",
".",
"GenerateFromPassword",
"(",
"[",
"]",
"byte",
"(",
"req",
".",
"Password",
")",
",",
"10",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"tx",
",",
"err",
":=",
"db",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"q",
"=",
"`UPDATE users SET password=$1 WHERE id=$2`",
"\n",
"if",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"q",
",",
"hpw",
",",
"uid",
")",
";",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"q",
"=",
"`DELETE FROM passwordresets WHERE secret=$1`",
"\n",
"if",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"q",
",",
"req",
".",
"Secret",
")",
";",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"tx",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // hapiResetPasswordSubmit is arrived at through the email generated by
// hapiForgotPasswordSubmit. This endpoint resets the user password with
// another bcrypt hash after validating on the server that their new password is
// sufficient. | [
"hapiResetPasswordSubmit",
"is",
"arrived",
"at",
"through",
"the",
"email",
"generated",
"by",
"hapiForgotPasswordSubmit",
".",
"This",
"endpoint",
"resets",
"the",
"user",
"password",
"with",
"another",
"bcrypt",
"hash",
"after",
"validating",
"on",
"the",
"server",
"that",
"their",
"new",
"password",
"is",
"sufficient",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L463-L517 |
4,979 | itsabot/itsabot | core/handlers.go | hapiAdminExists | func hapiAdminExists(w http.ResponseWriter, r *http.Request) {
var count int
q := `SELECT COUNT(*) FROM users WHERE admin=TRUE LIMIT 1`
if err := db.Get(&count, q); err != nil {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(count > 0)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(byt)
if err != nil {
log.Info("failed writing response header.", err)
}
} | go | func hapiAdminExists(w http.ResponseWriter, r *http.Request) {
var count int
q := `SELECT COUNT(*) FROM users WHERE admin=TRUE LIMIT 1`
if err := db.Get(&count, q); err != nil {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(count > 0)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(byt)
if err != nil {
log.Info("failed writing response header.", err)
}
} | [
"func",
"hapiAdminExists",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"count",
"int",
"\n",
"q",
":=",
"`SELECT COUNT(*) FROM users WHERE admin=TRUE LIMIT 1`",
"\n",
"if",
"err",
":=",
"db",
".",
"Get",
"(",
"&",
"count",
",",
"q",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"byt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"count",
">",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"byt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // hapiAdminExists checks if an admin exists in the database. | [
"hapiAdminExists",
"checks",
"if",
"an",
"admin",
"exists",
"in",
"the",
"database",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L520-L536 |
4,980 | itsabot/itsabot | core/handlers.go | hapiPlugins | func hapiPlugins(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
var settings []struct {
Name string
Value string
PluginName string
}
q := `SELECT name, value, pluginname FROM settings`
if err := db.Select(&settings, q); err != nil {
writeErrorInternal(w, err)
return
}
type respT struct {
ID uint64
Name string
Icon string
Maintainer string
Settings map[string]string
}
var resp []respT
for _, plugin := range PluginsGo {
data := respT{
ID: plugin.ID,
Name: plugin.Name,
Icon: plugin.Icon,
Maintainer: plugin.Maintainer,
Settings: map[string]string{},
}
for k, v := range plugin.Settings {
data.Settings[k] = v.Default
}
for _, setting := range settings {
if setting.PluginName != plugin.Name {
continue
}
data.Settings[setting.Name] = setting.Value
}
resp = append(resp, data)
}
writeBytes(w, resp)
} | go | func hapiPlugins(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
var settings []struct {
Name string
Value string
PluginName string
}
q := `SELECT name, value, pluginname FROM settings`
if err := db.Select(&settings, q); err != nil {
writeErrorInternal(w, err)
return
}
type respT struct {
ID uint64
Name string
Icon string
Maintainer string
Settings map[string]string
}
var resp []respT
for _, plugin := range PluginsGo {
data := respT{
ID: plugin.ID,
Name: plugin.Name,
Icon: plugin.Icon,
Maintainer: plugin.Maintainer,
Settings: map[string]string{},
}
for k, v := range plugin.Settings {
data.Settings[k] = v.Default
}
for _, setting := range settings {
if setting.PluginName != plugin.Name {
continue
}
data.Settings[setting.Name] = setting.Value
}
resp = append(resp, data)
}
writeBytes(w, resp)
} | [
"func",
"hapiPlugins",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"settings",
"[",
"]",
"struct",
"{",
"Name",
"string",
"\n",
"Value",
"string",
"\n",
"PluginName",
"string",
"\n",
"}",
"\n",
"q",
":=",
"`SELECT name, value, pluginname FROM settings`",
"\n",
"if",
"err",
":=",
"db",
".",
"Select",
"(",
"&",
"settings",
",",
"q",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"type",
"respT",
"struct",
"{",
"ID",
"uint64",
"\n",
"Name",
"string",
"\n",
"Icon",
"string",
"\n",
"Maintainer",
"string",
"\n",
"Settings",
"map",
"[",
"string",
"]",
"string",
"\n",
"}",
"\n",
"var",
"resp",
"[",
"]",
"respT",
"\n",
"for",
"_",
",",
"plugin",
":=",
"range",
"PluginsGo",
"{",
"data",
":=",
"respT",
"{",
"ID",
":",
"plugin",
".",
"ID",
",",
"Name",
":",
"plugin",
".",
"Name",
",",
"Icon",
":",
"plugin",
".",
"Icon",
",",
"Maintainer",
":",
"plugin",
".",
"Maintainer",
",",
"Settings",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
",",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"plugin",
".",
"Settings",
"{",
"data",
".",
"Settings",
"[",
"k",
"]",
"=",
"v",
".",
"Default",
"\n",
"}",
"\n",
"for",
"_",
",",
"setting",
":=",
"range",
"settings",
"{",
"if",
"setting",
".",
"PluginName",
"!=",
"plugin",
".",
"Name",
"{",
"continue",
"\n",
"}",
"\n",
"data",
".",
"Settings",
"[",
"setting",
".",
"Name",
"]",
"=",
"setting",
".",
"Value",
"\n",
"}",
"\n",
"resp",
"=",
"append",
"(",
"resp",
",",
"data",
")",
"\n",
"}",
"\n",
"writeBytes",
"(",
"w",
",",
"resp",
")",
"\n",
"}"
] | // hapiPlugins responds with all of the server's installed plugin
// configurations from each their respective plugin.json files and
// database-stored configuration. | [
"hapiPlugins",
"responds",
"with",
"all",
"of",
"the",
"server",
"s",
"installed",
"plugin",
"configurations",
"from",
"each",
"their",
"respective",
"plugin",
".",
"json",
"files",
"and",
"database",
"-",
"stored",
"configuration",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L541-L588 |
4,981 | itsabot/itsabot | core/handlers.go | hapiConversationsNeedTraining | func hapiConversationsNeedTraining(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
msgs := []struct {
Sentence string
FlexID *string
CreatedAt time.Time
UserID uint64
FlexIDType *int
}{}
q := `SELECT * FROM (
SELECT DISTINCT ON (flexid)
userid, flexid, flexidtype, sentence, createdat
FROM messages
WHERE needstraining=TRUE AND trained=FALSE AND abotsent=FALSE AND sentence<>''
) t ORDER BY createdat DESC`
err := db.Select(&msgs, q)
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusOK)
}
if err != nil {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(msgs)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(byt)
if err != nil {
log.Info("failed to write response.", err)
}
} | go | func hapiConversationsNeedTraining(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
msgs := []struct {
Sentence string
FlexID *string
CreatedAt time.Time
UserID uint64
FlexIDType *int
}{}
q := `SELECT * FROM (
SELECT DISTINCT ON (flexid)
userid, flexid, flexidtype, sentence, createdat
FROM messages
WHERE needstraining=TRUE AND trained=FALSE AND abotsent=FALSE AND sentence<>''
) t ORDER BY createdat DESC`
err := db.Select(&msgs, q)
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusOK)
}
if err != nil {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(msgs)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(byt)
if err != nil {
log.Info("failed to write response.", err)
}
} | [
"func",
"hapiConversationsNeedTraining",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"msgs",
":=",
"[",
"]",
"struct",
"{",
"Sentence",
"string",
"\n",
"FlexID",
"*",
"string",
"\n",
"CreatedAt",
"time",
".",
"Time",
"\n",
"UserID",
"uint64",
"\n",
"FlexIDType",
"*",
"int",
"\n",
"}",
"{",
"}",
"\n",
"q",
":=",
"`SELECT * FROM (\n\t\tSELECT DISTINCT ON (flexid)\n\t\t\tuserid, flexid, flexidtype, sentence, createdat\n\t\tFROM messages\n\t\tWHERE needstraining=TRUE AND trained=FALSE AND abotsent=FALSE AND sentence<>''\n\t) t ORDER BY createdat DESC`",
"\n",
"err",
":=",
"db",
".",
"Select",
"(",
"&",
"msgs",
",",
"q",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"byt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"msgs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"byt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // hapiConversationsNeedTraining returns a list of all sentences that require a
// human response. | [
"hapiConversationsNeedTraining",
"returns",
"a",
"list",
"of",
"all",
"sentences",
"that",
"require",
"a",
"human",
"response",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L592-L631 |
4,982 | itsabot/itsabot | core/handlers.go | hapiSendMessage | func hapiSendMessage(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
UserID uint64
FlexID string
FlexIDType dt.FlexIDType
Name string
Sentence string
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
msg := &dt.Msg{
User: &dt.User{ID: req.UserID},
FlexID: req.FlexID,
FlexIDType: req.FlexIDType,
Sentence: req.Sentence,
AbotSent: true,
}
switch req.FlexIDType {
case dt.FIDTPhone:
if smsConn == nil {
writeErrorInternal(w, errors.New("No SMS driver installed."))
return
}
if err := smsConn.Send(msg.FlexID, msg.Sentence); err != nil {
writeErrorInternal(w, err)
return
}
case dt.FIDTEmail:
/*
// TODO
if emailConn == nil {
writeErrorInternal(w, errors.New("No email driver installed."))
return
}
adminEmail := os.Getenv("ABOT_EMAIL")
email := template.GenericEmail(req.Name)
err := emailConn.SendHTML(msg.FlexID, adminEmail, "SUBJ", email)
if err != nil {
writeErrorInternal(w, err)
return
}
*/
case dt.FIDTSession:
/*
// TODO
if err := ws.NotifySocketSession(); err != nil {
}
*/
default:
writeErrorInternal(w, errors.New("invalid flexidtype"))
return
}
if err := msg.Save(db); err != nil {
writeErrorInternal(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | go | func hapiSendMessage(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
UserID uint64
FlexID string
FlexIDType dt.FlexIDType
Name string
Sentence string
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
msg := &dt.Msg{
User: &dt.User{ID: req.UserID},
FlexID: req.FlexID,
FlexIDType: req.FlexIDType,
Sentence: req.Sentence,
AbotSent: true,
}
switch req.FlexIDType {
case dt.FIDTPhone:
if smsConn == nil {
writeErrorInternal(w, errors.New("No SMS driver installed."))
return
}
if err := smsConn.Send(msg.FlexID, msg.Sentence); err != nil {
writeErrorInternal(w, err)
return
}
case dt.FIDTEmail:
/*
// TODO
if emailConn == nil {
writeErrorInternal(w, errors.New("No email driver installed."))
return
}
adminEmail := os.Getenv("ABOT_EMAIL")
email := template.GenericEmail(req.Name)
err := emailConn.SendHTML(msg.FlexID, adminEmail, "SUBJ", email)
if err != nil {
writeErrorInternal(w, err)
return
}
*/
case dt.FIDTSession:
/*
// TODO
if err := ws.NotifySocketSession(); err != nil {
}
*/
default:
writeErrorInternal(w, errors.New("invalid flexidtype"))
return
}
if err := msg.Save(db); err != nil {
writeErrorInternal(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | [
"func",
"hapiSendMessage",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isValidCSRF",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"req",
"struct",
"{",
"UserID",
"uint64",
"\n",
"FlexID",
"string",
"\n",
"FlexIDType",
"dt",
".",
"FlexIDType",
"\n",
"Name",
"string",
"\n",
"Sentence",
"string",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"msg",
":=",
"&",
"dt",
".",
"Msg",
"{",
"User",
":",
"&",
"dt",
".",
"User",
"{",
"ID",
":",
"req",
".",
"UserID",
"}",
",",
"FlexID",
":",
"req",
".",
"FlexID",
",",
"FlexIDType",
":",
"req",
".",
"FlexIDType",
",",
"Sentence",
":",
"req",
".",
"Sentence",
",",
"AbotSent",
":",
"true",
",",
"}",
"\n",
"switch",
"req",
".",
"FlexIDType",
"{",
"case",
"dt",
".",
"FIDTPhone",
":",
"if",
"smsConn",
"==",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"smsConn",
".",
"Send",
"(",
"msg",
".",
"FlexID",
",",
"msg",
".",
"Sentence",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"case",
"dt",
".",
"FIDTEmail",
":",
"/*\n\t\t\t// TODO\n\t\t\tif emailConn == nil {\n\t\t\t\twriteErrorInternal(w, errors.New(\"No email driver installed.\"))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tadminEmail := os.Getenv(\"ABOT_EMAIL\")\n\t\t\temail := template.GenericEmail(req.Name)\n\t\t\terr := emailConn.SendHTML(msg.FlexID, adminEmail, \"SUBJ\", email)\n\t\t\tif err != nil {\n\t\t\t\twriteErrorInternal(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t*/",
"case",
"dt",
".",
"FIDTSession",
":",
"/*\n\t\t\t// TODO\n\t\t\tif err := ws.NotifySocketSession(); err != nil {\n\t\t\t}\n\t\t*/",
"default",
":",
"writeErrorInternal",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"msg",
".",
"Save",
"(",
"db",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // hapiSendMessage enables an admin to send a message to a user on behalf of
// Abot from the Response Panel. | [
"hapiSendMessage",
"enables",
"an",
"admin",
"to",
"send",
"a",
"message",
"to",
"a",
"user",
"on",
"behalf",
"of",
"Abot",
"from",
"the",
"Response",
"Panel",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L780-L850 |
4,983 | itsabot/itsabot | core/handlers.go | hapiAdmins | func hapiAdmins(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
var admins []struct {
ID uint64
Name string
Email string
}
q := `SELECT id, name, email FROM users WHERE admin=TRUE`
err := db.Select(&admins, q)
if err != nil && err != sql.ErrNoRows {
writeErrorInternal(w, err)
return
}
b, err := json.Marshal(admins)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(b)
if err != nil {
log.Info("failed to write response.", err)
}
} | go | func hapiAdmins(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
var admins []struct {
ID uint64
Name string
Email string
}
q := `SELECT id, name, email FROM users WHERE admin=TRUE`
err := db.Select(&admins, q)
if err != nil && err != sql.ErrNoRows {
writeErrorInternal(w, err)
return
}
b, err := json.Marshal(admins)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(b)
if err != nil {
log.Info("failed to write response.", err)
}
} | [
"func",
"hapiAdmins",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"admins",
"[",
"]",
"struct",
"{",
"ID",
"uint64",
"\n",
"Name",
"string",
"\n",
"Email",
"string",
"\n",
"}",
"\n",
"q",
":=",
"`SELECT id, name, email FROM users WHERE admin=TRUE`",
"\n",
"err",
":=",
"db",
".",
"Select",
"(",
"&",
"admins",
",",
"q",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"sql",
".",
"ErrNoRows",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"admins",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // hapiAdmins returns a list of all admins with the training and manage team
// permissions. | [
"hapiAdmins",
"returns",
"a",
"list",
"of",
"all",
"admins",
"with",
"the",
"training",
"and",
"manage",
"team",
"permissions",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L854-L883 |
4,984 | itsabot/itsabot | core/handlers.go | hapiAdminsUpdate | func hapiAdminsUpdate(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
ID uint64
Email string
Admin bool
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
// This is a clever way to update the user using EITHER email or ID
// (whatever the client had available). Then we return the ID of the
// updated entry to send back to the client for faster future requests.
if req.ID > 0 && len(req.Email) > 0 {
writeErrorBadRequest(w, errors.New("only one value allowed: ID or Email"))
return
}
q := `UPDATE users SET admin=$1 WHERE id=$2 OR email=$3 RETURNING id`
err := db.QueryRow(q, req.Admin, req.ID, req.Email).Scan(&req.ID)
if err == sql.ErrNoRows {
// This error is frequently user-facing.
writeErrorBadRequest(w, errors.New("User not found."))
return
}
if err != nil {
writeErrorInternal(w, err)
return
}
var user struct {
ID uint64
Email string
Name string
}
q = `SELECT id, email, name FROM users WHERE id=$1`
if err = db.Get(&user, q, req.ID); err != nil {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(user)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(byt)
if err != nil {
log.Info("failed to write response.", err)
}
} | go | func hapiAdminsUpdate(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
ID uint64
Email string
Admin bool
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
// This is a clever way to update the user using EITHER email or ID
// (whatever the client had available). Then we return the ID of the
// updated entry to send back to the client for faster future requests.
if req.ID > 0 && len(req.Email) > 0 {
writeErrorBadRequest(w, errors.New("only one value allowed: ID or Email"))
return
}
q := `UPDATE users SET admin=$1 WHERE id=$2 OR email=$3 RETURNING id`
err := db.QueryRow(q, req.Admin, req.ID, req.Email).Scan(&req.ID)
if err == sql.ErrNoRows {
// This error is frequently user-facing.
writeErrorBadRequest(w, errors.New("User not found."))
return
}
if err != nil {
writeErrorInternal(w, err)
return
}
var user struct {
ID uint64
Email string
Name string
}
q = `SELECT id, email, name FROM users WHERE id=$1`
if err = db.Get(&user, q, req.ID); err != nil {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(user)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(byt)
if err != nil {
log.Info("failed to write response.", err)
}
} | [
"func",
"hapiAdminsUpdate",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isValidCSRF",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"req",
"struct",
"{",
"ID",
"uint64",
"\n",
"Email",
"string",
"\n",
"Admin",
"bool",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// This is a clever way to update the user using EITHER email or ID",
"// (whatever the client had available). Then we return the ID of the",
"// updated entry to send back to the client for faster future requests.",
"if",
"req",
".",
"ID",
">",
"0",
"&&",
"len",
"(",
"req",
".",
"Email",
")",
">",
"0",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"q",
":=",
"`UPDATE users SET admin=$1 WHERE id=$2 OR email=$3 RETURNING id`",
"\n",
"err",
":=",
"db",
".",
"QueryRow",
"(",
"q",
",",
"req",
".",
"Admin",
",",
"req",
".",
"ID",
",",
"req",
".",
"Email",
")",
".",
"Scan",
"(",
"&",
"req",
".",
"ID",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"// This error is frequently user-facing.",
"writeErrorBadRequest",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"user",
"struct",
"{",
"ID",
"uint64",
"\n",
"Email",
"string",
"\n",
"Name",
"string",
"\n",
"}",
"\n",
"q",
"=",
"`SELECT id, email, name FROM users WHERE id=$1`",
"\n",
"if",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"user",
",",
"q",
",",
"req",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"byt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"byt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // hapiAdminsUpdate adds or removes admin permission from a given user. | [
"hapiAdminsUpdate",
"adds",
"or",
"removes",
"admin",
"permission",
"from",
"a",
"given",
"user",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L886-L944 |
4,985 | itsabot/itsabot | core/handlers.go | hapiRemoteTokens | func hapiRemoteTokens(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
// We initialize the variable here because we want empty slices to
// marshal to [], not null
auths := []struct {
Token string
Email string
CreatedAt time.Time
PluginIDs dt.Uint64Slice
}{}
q := `SELECT token, email, pluginids, createdat FROM remotetokens`
err := db.Select(&auths, q)
if err != nil && err != sql.ErrNoRows {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(auths)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(byt)
if err != nil {
log.Info("failed to write response.", err)
}
} | go | func hapiRemoteTokens(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
// We initialize the variable here because we want empty slices to
// marshal to [], not null
auths := []struct {
Token string
Email string
CreatedAt time.Time
PluginIDs dt.Uint64Slice
}{}
q := `SELECT token, email, pluginids, createdat FROM remotetokens`
err := db.Select(&auths, q)
if err != nil && err != sql.ErrNoRows {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(auths)
if err != nil {
writeErrorInternal(w, err)
return
}
_, err = w.Write(byt)
if err != nil {
log.Info("failed to write response.", err)
}
} | [
"func",
"hapiRemoteTokens",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// We initialize the variable here because we want empty slices to",
"// marshal to [], not null",
"auths",
":=",
"[",
"]",
"struct",
"{",
"Token",
"string",
"\n",
"Email",
"string",
"\n",
"CreatedAt",
"time",
".",
"Time",
"\n",
"PluginIDs",
"dt",
".",
"Uint64Slice",
"\n",
"}",
"{",
"}",
"\n",
"q",
":=",
"`SELECT token, email, pluginids, createdat FROM remotetokens`",
"\n",
"err",
":=",
"db",
".",
"Select",
"(",
"&",
"auths",
",",
"q",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"sql",
".",
"ErrNoRows",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"byt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"auths",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"byt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // hapiRemoteTokens returns the final six bytes of each auth token used to
// authenticate to the remote service and when. | [
"hapiRemoteTokens",
"returns",
"the",
"final",
"six",
"bytes",
"of",
"each",
"auth",
"token",
"used",
"to",
"authenticate",
"to",
"the",
"remote",
"service",
"and",
"when",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L948-L981 |
4,986 | itsabot/itsabot | core/handlers.go | hapiRemoteTokensSubmit | func hapiRemoteTokensSubmit(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
Token string
PluginIDs dt.Uint64Slice
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
cookie, err := r.Cookie("email")
if err != nil {
writeErrorBadRequest(w, err)
return
}
q := `INSERT INTO remotetokens (token, email, pluginids)
VALUES ($1, $2, $3)`
_, err = db.Exec(q, req.Token, cookie.Value, req.PluginIDs)
if err != nil {
if err.Error() == `pq: duplicate key value violates unique constraint "remotetokens_token_key"` {
writeErrorBadRequest(w, errors.New("Token has already been added."))
return
}
writeErrorInternal(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | go | func hapiRemoteTokensSubmit(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
Token string
PluginIDs dt.Uint64Slice
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
cookie, err := r.Cookie("email")
if err != nil {
writeErrorBadRequest(w, err)
return
}
q := `INSERT INTO remotetokens (token, email, pluginids)
VALUES ($1, $2, $3)`
_, err = db.Exec(q, req.Token, cookie.Value, req.PluginIDs)
if err != nil {
if err.Error() == `pq: duplicate key value violates unique constraint "remotetokens_token_key"` {
writeErrorBadRequest(w, errors.New("Token has already been added."))
return
}
writeErrorInternal(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | [
"func",
"hapiRemoteTokensSubmit",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isValidCSRF",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"req",
"struct",
"{",
"Token",
"string",
"\n",
"PluginIDs",
"dt",
".",
"Uint64Slice",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"q",
":=",
"`INSERT INTO remotetokens (token, email, pluginids)\n\t VALUES ($1, $2, $3)`",
"\n",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"q",
",",
"req",
".",
"Token",
",",
"cookie",
".",
"Value",
",",
"req",
".",
"PluginIDs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
".",
"Error",
"(",
")",
"==",
"`pq: duplicate key value violates unique constraint \"remotetokens_token_key\"`",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // hapiRemoteTokensSubmit adds a remote token for modifying ITSABOT_URL's
// plugin training data. | [
"hapiRemoteTokensSubmit",
"adds",
"a",
"remote",
"token",
"for",
"modifying",
"ITSABOT_URL",
"s",
"plugin",
"training",
"data",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L985-L1022 |
4,987 | itsabot/itsabot | core/handlers.go | hapiRemoteTokensDelete | func hapiRemoteTokensDelete(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
Token string
Email string
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
q := `DELETE FROM remotetokens WHERE token=$1`
res, err := db.Exec(q, req.Token)
if err != nil {
writeErrorInternal(w, err)
return
}
rows, err := res.RowsAffected()
if err != nil {
writeErrorInternal(w, err)
return
}
if rows == 0 {
writeErrorBadRequest(w, errors.New("invalid token or email"))
return
}
w.WriteHeader(http.StatusOK)
} | go | func hapiRemoteTokensDelete(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
Token string
Email string
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
q := `DELETE FROM remotetokens WHERE token=$1`
res, err := db.Exec(q, req.Token)
if err != nil {
writeErrorInternal(w, err)
return
}
rows, err := res.RowsAffected()
if err != nil {
writeErrorInternal(w, err)
return
}
if rows == 0 {
writeErrorBadRequest(w, errors.New("invalid token or email"))
return
}
w.WriteHeader(http.StatusOK)
} | [
"func",
"hapiRemoteTokensDelete",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isValidCSRF",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"req",
"struct",
"{",
"Token",
"string",
"\n",
"Email",
"string",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"q",
":=",
"`DELETE FROM remotetokens WHERE token=$1`",
"\n",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"q",
",",
"req",
".",
"Token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"rows",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"rows",
"==",
"0",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // hapiRemoteTokensDelete removes a remote token from the DB and responds with
// 200 OK. | [
"hapiRemoteTokensDelete",
"removes",
"a",
"remote",
"token",
"from",
"the",
"DB",
"and",
"responds",
"with",
"200",
"OK",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L1026-L1062 |
4,988 | itsabot/itsabot | core/handlers.go | hapiSettingsUpdate | func hapiSettingsUpdate(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
var req map[string]map[string]string
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
tx, err := db.Begin()
if err != nil {
writeErrorInternal(w, err)
return
}
for plugin, data := range req {
for k, v := range data {
q := `INSERT INTO settings (name, value, pluginname)
VALUES ($1, $2, $3)
ON CONFLICT (name, pluginname) DO
UPDATE SET value=$2`
_, err = tx.Exec(q, k, v, plugin)
if err != nil {
writeErrorInternal(w, err)
return
}
}
}
if err = tx.Commit(); err != nil {
writeErrorInternal(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | go | func hapiSettingsUpdate(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
}
var req map[string]map[string]string
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorBadRequest(w, err)
return
}
tx, err := db.Begin()
if err != nil {
writeErrorInternal(w, err)
return
}
for plugin, data := range req {
for k, v := range data {
q := `INSERT INTO settings (name, value, pluginname)
VALUES ($1, $2, $3)
ON CONFLICT (name, pluginname) DO
UPDATE SET value=$2`
_, err = tx.Exec(q, k, v, plugin)
if err != nil {
writeErrorInternal(w, err)
return
}
}
}
if err = tx.Commit(); err != nil {
writeErrorInternal(w, err)
return
}
w.WriteHeader(http.StatusOK)
} | [
"func",
"hapiSettingsUpdate",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isAdmin",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"isLoggedIn",
"(",
"w",
",",
"r",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"req",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorBadRequest",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"tx",
",",
"err",
":=",
"db",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"plugin",
",",
"data",
":=",
"range",
"req",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"data",
"{",
"q",
":=",
"`INSERT INTO settings (name, value, pluginname)\n\t\t\t VALUES ($1, $2, $3)\n\t\t\t ON CONFLICT (name, pluginname) DO\n\t\t\t\tUPDATE SET value=$2`",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"q",
",",
"k",
",",
"v",
",",
"plugin",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"tx",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // hapiSettingsUpdate updates settings in the database for plugins. | [
"hapiSettingsUpdate",
"updates",
"settings",
"in",
"the",
"database",
"for",
"plugins",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L1065-L1102 |
4,989 | itsabot/itsabot | core/handlers.go | createCSRFToken | func createCSRFToken(u *dt.User) (token string, err error) {
q := `INSERT INTO sessions (token, userid, label)
VALUES ($1, $2, 'csrfToken')
ON CONFLICT (userid, label) DO UPDATE SET token=$1`
token = RandSeq(32)
if _, err := db.Exec(q, token, u.ID); err != nil {
return "", err
}
return token, nil
} | go | func createCSRFToken(u *dt.User) (token string, err error) {
q := `INSERT INTO sessions (token, userid, label)
VALUES ($1, $2, 'csrfToken')
ON CONFLICT (userid, label) DO UPDATE SET token=$1`
token = RandSeq(32)
if _, err := db.Exec(q, token, u.ID); err != nil {
return "", err
}
return token, nil
} | [
"func",
"createCSRFToken",
"(",
"u",
"*",
"dt",
".",
"User",
")",
"(",
"token",
"string",
",",
"err",
"error",
")",
"{",
"q",
":=",
"`INSERT INTO sessions (token, userid, label)\n\t VALUES ($1, $2, 'csrfToken')\n\t ON CONFLICT (userid, label) DO UPDATE SET token=$1`",
"\n",
"token",
"=",
"RandSeq",
"(",
"32",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"q",
",",
"token",
",",
"u",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"token",
",",
"nil",
"\n",
"}"
] | // createCSRFToken creates a new token, invalidating any existing token. | [
"createCSRFToken",
"creates",
"a",
"new",
"token",
"invalidating",
"any",
"existing",
"token",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L1196-L1205 |
4,990 | itsabot/itsabot | core/handlers.go | getAuthToken | func getAuthToken(u *dt.User) (header *Header, authToken string, err error) {
scopes := []string{}
if u.Admin {
scopes = append(scopes, "admin")
}
header = &Header{
ID: u.ID,
Email: u.Email,
Scopes: scopes,
IssuedAt: time.Now().Unix(),
}
byt, err := json.Marshal(header)
if err != nil {
return nil, "", err
}
hash := hmac.New(sha512.New, []byte(os.Getenv("ABOT_SECRET")))
_, err = hash.Write(byt)
if err != nil {
return nil, "", err
}
authToken = base64.StdEncoding.EncodeToString(hash.Sum(nil))
return header, authToken, nil
} | go | func getAuthToken(u *dt.User) (header *Header, authToken string, err error) {
scopes := []string{}
if u.Admin {
scopes = append(scopes, "admin")
}
header = &Header{
ID: u.ID,
Email: u.Email,
Scopes: scopes,
IssuedAt: time.Now().Unix(),
}
byt, err := json.Marshal(header)
if err != nil {
return nil, "", err
}
hash := hmac.New(sha512.New, []byte(os.Getenv("ABOT_SECRET")))
_, err = hash.Write(byt)
if err != nil {
return nil, "", err
}
authToken = base64.StdEncoding.EncodeToString(hash.Sum(nil))
return header, authToken, nil
} | [
"func",
"getAuthToken",
"(",
"u",
"*",
"dt",
".",
"User",
")",
"(",
"header",
"*",
"Header",
",",
"authToken",
"string",
",",
"err",
"error",
")",
"{",
"scopes",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"if",
"u",
".",
"Admin",
"{",
"scopes",
"=",
"append",
"(",
"scopes",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"header",
"=",
"&",
"Header",
"{",
"ID",
":",
"u",
".",
"ID",
",",
"Email",
":",
"u",
".",
"Email",
",",
"Scopes",
":",
"scopes",
",",
"IssuedAt",
":",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
",",
"}",
"\n",
"byt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"hash",
":=",
"hmac",
".",
"New",
"(",
"sha512",
".",
"New",
",",
"[",
"]",
"byte",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
")",
"\n",
"_",
",",
"err",
"=",
"hash",
".",
"Write",
"(",
"byt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"authToken",
"=",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"hash",
".",
"Sum",
"(",
"nil",
")",
")",
"\n",
"return",
"header",
",",
"authToken",
",",
"nil",
"\n",
"}"
] | // getAuthToken returns a token used for future client authorization with a CSRF
// token. | [
"getAuthToken",
"returns",
"a",
"token",
"used",
"for",
"future",
"client",
"authorization",
"with",
"a",
"CSRF",
"token",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L1209-L1231 |
4,991 | itsabot/itsabot | core/handlers.go | isValidCSRF | func isValidCSRF(w http.ResponseWriter, r *http.Request) bool {
// TODO look into other session-based temporary storage systems for
// these csrf tokens to prevent hitting the database. Whatever is
// selected must *not* introduce an external (system) dependency like
// memcached/Redis. Bolt might be an option.
log.Debug("validating csrf")
var label string
q := `SELECT label FROM sessions
WHERE userid=$1 AND label='csrfToken' AND token=$2`
cookie, err := r.Cookie("id")
if err == http.ErrNoCookie {
writeErrorAuth(w, err)
return false
}
if err != nil {
writeErrorInternal(w, err)
return false
}
uid := cookie.Value
cookie, err = r.Cookie("csrfToken")
if err == http.ErrNoCookie {
writeErrorAuth(w, err)
return false
}
if err != nil {
writeErrorInternal(w, err)
return false
}
err = db.Get(&label, q, uid, cookie.Value)
if err == sql.ErrNoRows {
writeErrorAuth(w, errors.New("invalid CSRF token"))
return false
}
if err != nil {
writeErrorInternal(w, err)
return false
}
log.Debug("validated csrf")
return true
} | go | func isValidCSRF(w http.ResponseWriter, r *http.Request) bool {
// TODO look into other session-based temporary storage systems for
// these csrf tokens to prevent hitting the database. Whatever is
// selected must *not* introduce an external (system) dependency like
// memcached/Redis. Bolt might be an option.
log.Debug("validating csrf")
var label string
q := `SELECT label FROM sessions
WHERE userid=$1 AND label='csrfToken' AND token=$2`
cookie, err := r.Cookie("id")
if err == http.ErrNoCookie {
writeErrorAuth(w, err)
return false
}
if err != nil {
writeErrorInternal(w, err)
return false
}
uid := cookie.Value
cookie, err = r.Cookie("csrfToken")
if err == http.ErrNoCookie {
writeErrorAuth(w, err)
return false
}
if err != nil {
writeErrorInternal(w, err)
return false
}
err = db.Get(&label, q, uid, cookie.Value)
if err == sql.ErrNoRows {
writeErrorAuth(w, errors.New("invalid CSRF token"))
return false
}
if err != nil {
writeErrorInternal(w, err)
return false
}
log.Debug("validated csrf")
return true
} | [
"func",
"isValidCSRF",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"// TODO look into other session-based temporary storage systems for",
"// these csrf tokens to prevent hitting the database. Whatever is",
"// selected must *not* introduce an external (system) dependency like",
"// memcached/Redis. Bolt might be an option.",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"var",
"label",
"string",
"\n",
"q",
":=",
"`SELECT label FROM sessions\n\t WHERE userid=$1 AND label='csrfToken' AND token=$2`",
"\n",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"==",
"http",
".",
"ErrNoCookie",
"{",
"writeErrorAuth",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"uid",
":=",
"cookie",
".",
"Value",
"\n",
"cookie",
",",
"err",
"=",
"r",
".",
"Cookie",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"==",
"http",
".",
"ErrNoCookie",
"{",
"writeErrorAuth",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"err",
"=",
"db",
".",
"Get",
"(",
"&",
"label",
",",
"q",
",",
"uid",
",",
"cookie",
".",
"Value",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"writeErrorAuth",
"(",
"w",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeErrorInternal",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // isValidCSRF ensures that any forms posted to Abot are protected against
// Cross-Site Request Forgery. Without this function, Abot would be vulnerable
// to the attack because tokens are stored client-side in cookies. | [
"isValidCSRF",
"ensures",
"that",
"any",
"forms",
"posted",
"to",
"Abot",
"are",
"protected",
"against",
"Cross",
"-",
"Site",
"Request",
"Forgery",
".",
"Without",
"this",
"function",
"Abot",
"would",
"be",
"vulnerable",
"to",
"the",
"attack",
"because",
"tokens",
"are",
"stored",
"client",
"-",
"side",
"in",
"cookies",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/handlers.go#L1414-L1453 |
4,992 | itsabot/itsabot | shared/language/extract.go | ExtractCurrency | func ExtractCurrency(s string) (int64, error) {
s = regexCurrency.FindString(s)
if len(s) == 0 {
return 0, ErrNotFound
}
val, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, err
}
log.Debug("found value", val)
// Convert parsed float into an int64 with precision of 2 decimal places
return int64(val * 100), nil
} | go | func ExtractCurrency(s string) (int64, error) {
s = regexCurrency.FindString(s)
if len(s) == 0 {
return 0, ErrNotFound
}
val, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, err
}
log.Debug("found value", val)
// Convert parsed float into an int64 with precision of 2 decimal places
return int64(val * 100), nil
} | [
"func",
"ExtractCurrency",
"(",
"s",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"s",
"=",
"regexCurrency",
".",
"FindString",
"(",
"s",
")",
"\n",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"{",
"return",
"0",
",",
"ErrNotFound",
"\n",
"}",
"\n",
"val",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"s",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"val",
")",
"\n",
"// Convert parsed float into an int64 with precision of 2 decimal places",
"return",
"int64",
"(",
"val",
"*",
"100",
")",
",",
"nil",
"\n",
"}"
] | // ExtractCurrency returns an int64 if a currency is found, and throws an
// error if one isn't. | [
"ExtractCurrency",
"returns",
"an",
"int64",
"if",
"a",
"currency",
"is",
"found",
"and",
"throws",
"an",
"error",
"if",
"one",
"isn",
"t",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/extract.go#L30-L42 |
4,993 | itsabot/itsabot | shared/language/extract.go | ExtractCities | func ExtractCities(db *sqlx.DB, in *dt.Msg) ([]dt.City, error) {
// Interface type is used to expand the args in db.Select below.
// Although we're only storing strings, []string{} doesn't work.
var args []interface{}
// Look for "at", "in", "on" prepositions to signal that locations
// follow, skipping everything before
var start int
for i := range in.Stems {
switch in.Stems[i] {
case "at", "in", "on":
start = i
break
}
}
// Prepare sentence for iteration
tmp := regexNonWords.ReplaceAllString(in.Sentence, "")
words := strings.Fields(strings.Title(tmp))
// Iterate through words and bigrams to assemble a DB query
for i := start; i < len(words); i++ {
args = append(args, words[i])
}
bgs := bigrams(words, start)
for i := 0; i < len(bgs); i++ {
args = append(args, bgs[i])
}
cities := []dt.City{}
q := `SELECT name, countrycode FROM cities
WHERE countrycode='US' AND name IN (?)
ORDER BY LENGTH(name) DESC`
query, arguments, err := sqlx.In(q, args)
query = db.Rebind(query)
rows, err := db.Query(query, arguments...)
if err != nil {
return nil, err
}
defer func() {
if err = rows.Close(); err != nil {
log.Info("failed to close db rows.", err)
}
}()
for rows.Next() {
city := dt.City{}
if err = rows.Scan(&city.Name, &city.CountryCode); err != nil {
return nil, err
}
cities = append(cities, city)
}
if err = rows.Err(); err != nil {
return nil, err
}
if len(cities) == 0 {
return nil, ErrNotFound
}
return cities, nil
} | go | func ExtractCities(db *sqlx.DB, in *dt.Msg) ([]dt.City, error) {
// Interface type is used to expand the args in db.Select below.
// Although we're only storing strings, []string{} doesn't work.
var args []interface{}
// Look for "at", "in", "on" prepositions to signal that locations
// follow, skipping everything before
var start int
for i := range in.Stems {
switch in.Stems[i] {
case "at", "in", "on":
start = i
break
}
}
// Prepare sentence for iteration
tmp := regexNonWords.ReplaceAllString(in.Sentence, "")
words := strings.Fields(strings.Title(tmp))
// Iterate through words and bigrams to assemble a DB query
for i := start; i < len(words); i++ {
args = append(args, words[i])
}
bgs := bigrams(words, start)
for i := 0; i < len(bgs); i++ {
args = append(args, bgs[i])
}
cities := []dt.City{}
q := `SELECT name, countrycode FROM cities
WHERE countrycode='US' AND name IN (?)
ORDER BY LENGTH(name) DESC`
query, arguments, err := sqlx.In(q, args)
query = db.Rebind(query)
rows, err := db.Query(query, arguments...)
if err != nil {
return nil, err
}
defer func() {
if err = rows.Close(); err != nil {
log.Info("failed to close db rows.", err)
}
}()
for rows.Next() {
city := dt.City{}
if err = rows.Scan(&city.Name, &city.CountryCode); err != nil {
return nil, err
}
cities = append(cities, city)
}
if err = rows.Err(); err != nil {
return nil, err
}
if len(cities) == 0 {
return nil, ErrNotFound
}
return cities, nil
} | [
"func",
"ExtractCities",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"in",
"*",
"dt",
".",
"Msg",
")",
"(",
"[",
"]",
"dt",
".",
"City",
",",
"error",
")",
"{",
"// Interface type is used to expand the args in db.Select below.",
"// Although we're only storing strings, []string{} doesn't work.",
"var",
"args",
"[",
"]",
"interface",
"{",
"}",
"\n\n",
"// Look for \"at\", \"in\", \"on\" prepositions to signal that locations",
"// follow, skipping everything before",
"var",
"start",
"int",
"\n",
"for",
"i",
":=",
"range",
"in",
".",
"Stems",
"{",
"switch",
"in",
".",
"Stems",
"[",
"i",
"]",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"start",
"=",
"i",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Prepare sentence for iteration",
"tmp",
":=",
"regexNonWords",
".",
"ReplaceAllString",
"(",
"in",
".",
"Sentence",
",",
"\"",
"\"",
")",
"\n",
"words",
":=",
"strings",
".",
"Fields",
"(",
"strings",
".",
"Title",
"(",
"tmp",
")",
")",
"\n\n",
"// Iterate through words and bigrams to assemble a DB query",
"for",
"i",
":=",
"start",
";",
"i",
"<",
"len",
"(",
"words",
")",
";",
"i",
"++",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"words",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"bgs",
":=",
"bigrams",
"(",
"words",
",",
"start",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"bgs",
")",
";",
"i",
"++",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"bgs",
"[",
"i",
"]",
")",
"\n",
"}",
"\n\n",
"cities",
":=",
"[",
"]",
"dt",
".",
"City",
"{",
"}",
"\n",
"q",
":=",
"`SELECT name, countrycode FROM cities\n\t WHERE countrycode='US' AND name IN (?)\n\t ORDER BY LENGTH(name) DESC`",
"\n",
"query",
",",
"arguments",
",",
"err",
":=",
"sqlx",
".",
"In",
"(",
"q",
",",
"args",
")",
"\n",
"query",
"=",
"db",
".",
"Rebind",
"(",
"query",
")",
"\n",
"rows",
",",
"err",
":=",
"db",
".",
"Query",
"(",
"query",
",",
"arguments",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"=",
"rows",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"city",
":=",
"dt",
".",
"City",
"{",
"}",
"\n",
"if",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"city",
".",
"Name",
",",
"&",
"city",
".",
"CountryCode",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"cities",
"=",
"append",
"(",
"cities",
",",
"city",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"rows",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cities",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrNotFound",
"\n",
"}",
"\n",
"return",
"cities",
",",
"nil",
"\n",
"}"
] | // ExtractCities efficiently from a user's message. | [
"ExtractCities",
"efficiently",
"from",
"a",
"user",
"s",
"message",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/extract.go#L168-L226 |
4,994 | itsabot/itsabot | shared/language/extract.go | ExtractEmails | func ExtractEmails(s string) ([]string, error) {
emails := regexEmail.FindAllString(s, -1)
if emails == nil {
return []string{}, ErrNotFound
}
return emails, nil
} | go | func ExtractEmails(s string) ([]string, error) {
emails := regexEmail.FindAllString(s, -1)
if emails == nil {
return []string{}, ErrNotFound
}
return emails, nil
} | [
"func",
"ExtractEmails",
"(",
"s",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"emails",
":=",
"regexEmail",
".",
"FindAllString",
"(",
"s",
",",
"-",
"1",
")",
"\n",
"if",
"emails",
"==",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"ErrNotFound",
"\n",
"}",
"\n",
"return",
"emails",
",",
"nil",
"\n",
"}"
] | // ExtractEmails from a user's message. | [
"ExtractEmails",
"from",
"a",
"user",
"s",
"message",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/extract.go#L229-L235 |
4,995 | itsabot/itsabot | core/scheduled_event.go | sendEvents | func sendEvents(evtChan chan *dt.ScheduledEvent, interval time.Duration) {
t := time.NewTicker(time.Minute)
select {
case now := <-t.C:
sendEventsTick(evtChan, now)
sendEvents(evtChan, interval)
}
} | go | func sendEvents(evtChan chan *dt.ScheduledEvent, interval time.Duration) {
t := time.NewTicker(time.Minute)
select {
case now := <-t.C:
sendEventsTick(evtChan, now)
sendEvents(evtChan, interval)
}
} | [
"func",
"sendEvents",
"(",
"evtChan",
"chan",
"*",
"dt",
".",
"ScheduledEvent",
",",
"interval",
"time",
".",
"Duration",
")",
"{",
"t",
":=",
"time",
".",
"NewTicker",
"(",
"time",
".",
"Minute",
")",
"\n",
"select",
"{",
"case",
"now",
":=",
"<-",
"t",
".",
"C",
":",
"sendEventsTick",
"(",
"evtChan",
",",
"now",
")",
"\n",
"sendEvents",
"(",
"evtChan",
",",
"interval",
")",
"\n",
"}",
"\n",
"}"
] | // sendEvents recursively calls itself to continue running. | [
"sendEvents",
"recursively",
"calls",
"itself",
"to",
"continue",
"running",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/core/scheduled_event.go#L11-L18 |
4,996 | itsabot/itsabot | shared/datatypes/state_machine.go | NewStateMachine | func NewStateMachine(p *Plugin) *StateMachine {
sm := StateMachine{
state: 0,
plugin: p,
}
sm.states = map[string]int{}
sm.resetFn = func(*Msg) {}
return &sm
} | go | func NewStateMachine(p *Plugin) *StateMachine {
sm := StateMachine{
state: 0,
plugin: p,
}
sm.states = map[string]int{}
sm.resetFn = func(*Msg) {}
return &sm
} | [
"func",
"NewStateMachine",
"(",
"p",
"*",
"Plugin",
")",
"*",
"StateMachine",
"{",
"sm",
":=",
"StateMachine",
"{",
"state",
":",
"0",
",",
"plugin",
":",
"p",
",",
"}",
"\n",
"sm",
".",
"states",
"=",
"map",
"[",
"string",
"]",
"int",
"{",
"}",
"\n",
"sm",
".",
"resetFn",
"=",
"func",
"(",
"*",
"Msg",
")",
"{",
"}",
"\n",
"return",
"&",
"sm",
"\n",
"}"
] | // NewStateMachine initializes a stateMachine to its starting state. | [
"NewStateMachine",
"initializes",
"a",
"stateMachine",
"to",
"its",
"starting",
"state",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/state_machine.go#L79-L87 |
4,997 | itsabot/itsabot | shared/datatypes/state_machine.go | LoadState | func (sm *StateMachine) LoadState(in *Msg) {
tmp, err := json.Marshal(sm.state)
if err != nil {
sm.plugin.Log.Info("failed to marshal state for db.", err)
return
}
// Using upsert to either insert and return a value or on conflict to
// update and return a value doesn't work, leading to this longer form.
// Could it be a Postgres bug? This can and should be optimized.
if in.User.ID > 0 {
q := `INSERT INTO states
(key, userid, value, pluginname) VALUES ($1, $2, $3, $4)`
_, err = sm.plugin.DB.Exec(q, StateKey, in.User.ID, tmp,
sm.plugin.Config.Name)
} else {
q := `INSERT INTO states
(key, flexid, flexidtype, value, pluginname) VALUES ($1, $2, $3, $4, $5)`
_, err = sm.plugin.DB.Exec(q, StateKey, in.User.FlexID,
in.User.FlexIDType, tmp, sm.plugin.Config.Name)
}
if err != nil {
if err.Error() != `pq: duplicate key value violates unique constraint "states_userid_pkgname_key_key"` &&
err.Error() != `pq: duplicate key value violates unique constraint "states_flexid_flexidtype_pluginname_key_key"` {
sm.plugin.Log.Info("could not insert value into states.", err)
sm.state = 0
return
}
if in.User.ID > 0 {
q := `SELECT value FROM states
WHERE userid=$1 AND key=$2 AND pluginname=$3`
err = sm.plugin.DB.Get(&tmp, q, in.User.ID, StateKey,
sm.plugin.Config.Name)
} else {
q := `SELECT value FROM states
WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4`
err = sm.plugin.DB.Get(&tmp, q, in.User.FlexID,
in.User.FlexIDType, StateKey, sm.plugin.Config.Name)
}
if err != nil {
sm.plugin.Log.Info("failed to get value from state.", err)
return
}
}
var val int
if err = json.Unmarshal(tmp, &val); err != nil {
sm.plugin.Log.Info("failed unmarshaling state from db.", err)
return
}
sm.state = val
// Have we already entered a state?
sm.stateEntered = sm.plugin.GetMemory(in, stateEnteredKey).Bool()
return
} | go | func (sm *StateMachine) LoadState(in *Msg) {
tmp, err := json.Marshal(sm.state)
if err != nil {
sm.plugin.Log.Info("failed to marshal state for db.", err)
return
}
// Using upsert to either insert and return a value or on conflict to
// update and return a value doesn't work, leading to this longer form.
// Could it be a Postgres bug? This can and should be optimized.
if in.User.ID > 0 {
q := `INSERT INTO states
(key, userid, value, pluginname) VALUES ($1, $2, $3, $4)`
_, err = sm.plugin.DB.Exec(q, StateKey, in.User.ID, tmp,
sm.plugin.Config.Name)
} else {
q := `INSERT INTO states
(key, flexid, flexidtype, value, pluginname) VALUES ($1, $2, $3, $4, $5)`
_, err = sm.plugin.DB.Exec(q, StateKey, in.User.FlexID,
in.User.FlexIDType, tmp, sm.plugin.Config.Name)
}
if err != nil {
if err.Error() != `pq: duplicate key value violates unique constraint "states_userid_pkgname_key_key"` &&
err.Error() != `pq: duplicate key value violates unique constraint "states_flexid_flexidtype_pluginname_key_key"` {
sm.plugin.Log.Info("could not insert value into states.", err)
sm.state = 0
return
}
if in.User.ID > 0 {
q := `SELECT value FROM states
WHERE userid=$1 AND key=$2 AND pluginname=$3`
err = sm.plugin.DB.Get(&tmp, q, in.User.ID, StateKey,
sm.plugin.Config.Name)
} else {
q := `SELECT value FROM states
WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4`
err = sm.plugin.DB.Get(&tmp, q, in.User.FlexID,
in.User.FlexIDType, StateKey, sm.plugin.Config.Name)
}
if err != nil {
sm.plugin.Log.Info("failed to get value from state.", err)
return
}
}
var val int
if err = json.Unmarshal(tmp, &val); err != nil {
sm.plugin.Log.Info("failed unmarshaling state from db.", err)
return
}
sm.state = val
// Have we already entered a state?
sm.stateEntered = sm.plugin.GetMemory(in, stateEnteredKey).Bool()
return
} | [
"func",
"(",
"sm",
"*",
"StateMachine",
")",
"LoadState",
"(",
"in",
"*",
"Msg",
")",
"{",
"tmp",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"sm",
".",
"state",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"sm",
".",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Using upsert to either insert and return a value or on conflict to",
"// update and return a value doesn't work, leading to this longer form.",
"// Could it be a Postgres bug? This can and should be optimized.",
"if",
"in",
".",
"User",
".",
"ID",
">",
"0",
"{",
"q",
":=",
"`INSERT INTO states\n\t\t (key, userid, value, pluginname) VALUES ($1, $2, $3, $4)`",
"\n",
"_",
",",
"err",
"=",
"sm",
".",
"plugin",
".",
"DB",
".",
"Exec",
"(",
"q",
",",
"StateKey",
",",
"in",
".",
"User",
".",
"ID",
",",
"tmp",
",",
"sm",
".",
"plugin",
".",
"Config",
".",
"Name",
")",
"\n",
"}",
"else",
"{",
"q",
":=",
"`INSERT INTO states\n\t\t (key, flexid, flexidtype, value, pluginname) VALUES ($1, $2, $3, $4, $5)`",
"\n",
"_",
",",
"err",
"=",
"sm",
".",
"plugin",
".",
"DB",
".",
"Exec",
"(",
"q",
",",
"StateKey",
",",
"in",
".",
"User",
".",
"FlexID",
",",
"in",
".",
"User",
".",
"FlexIDType",
",",
"tmp",
",",
"sm",
".",
"plugin",
".",
"Config",
".",
"Name",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
".",
"Error",
"(",
")",
"!=",
"`pq: duplicate key value violates unique constraint \"states_userid_pkgname_key_key\"`",
"&&",
"err",
".",
"Error",
"(",
")",
"!=",
"`pq: duplicate key value violates unique constraint \"states_flexid_flexidtype_pluginname_key_key\"`",
"{",
"sm",
".",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"sm",
".",
"state",
"=",
"0",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"in",
".",
"User",
".",
"ID",
">",
"0",
"{",
"q",
":=",
"`SELECT value FROM states\n\t\t\t WHERE userid=$1 AND key=$2 AND pluginname=$3`",
"\n",
"err",
"=",
"sm",
".",
"plugin",
".",
"DB",
".",
"Get",
"(",
"&",
"tmp",
",",
"q",
",",
"in",
".",
"User",
".",
"ID",
",",
"StateKey",
",",
"sm",
".",
"plugin",
".",
"Config",
".",
"Name",
")",
"\n",
"}",
"else",
"{",
"q",
":=",
"`SELECT value FROM states\n\t\t\t WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4`",
"\n",
"err",
"=",
"sm",
".",
"plugin",
".",
"DB",
".",
"Get",
"(",
"&",
"tmp",
",",
"q",
",",
"in",
".",
"User",
".",
"FlexID",
",",
"in",
".",
"User",
".",
"FlexIDType",
",",
"StateKey",
",",
"sm",
".",
"plugin",
".",
"Config",
".",
"Name",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"sm",
".",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"val",
"int",
"\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"tmp",
",",
"&",
"val",
")",
";",
"err",
"!=",
"nil",
"{",
"sm",
".",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sm",
".",
"state",
"=",
"val",
"\n\n",
"// Have we already entered a state?",
"sm",
".",
"stateEntered",
"=",
"sm",
".",
"plugin",
".",
"GetMemory",
"(",
"in",
",",
"stateEnteredKey",
")",
".",
"Bool",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // LoadState upserts state into the database. If there is an existing state for
// a given user and plugin, the stateMachine will load it. If not, the
// stateMachine will insert a starting state into the database. | [
"LoadState",
"upserts",
"state",
"into",
"the",
"database",
".",
"If",
"there",
"is",
"an",
"existing",
"state",
"for",
"a",
"given",
"user",
"and",
"plugin",
"the",
"stateMachine",
"will",
"load",
"it",
".",
"If",
"not",
"the",
"stateMachine",
"will",
"insert",
"a",
"starting",
"state",
"into",
"the",
"database",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/state_machine.go#L109-L163 |
4,998 | itsabot/itsabot | shared/datatypes/state_machine.go | setEntered | func (sm *StateMachine) setEntered(in *Msg) {
sm.stateEntered = true
sm.plugin.SetMemory(in, stateEnteredKey, true)
} | go | func (sm *StateMachine) setEntered(in *Msg) {
sm.stateEntered = true
sm.plugin.SetMemory(in, stateEnteredKey, true)
} | [
"func",
"(",
"sm",
"*",
"StateMachine",
")",
"setEntered",
"(",
"in",
"*",
"Msg",
")",
"{",
"sm",
".",
"stateEntered",
"=",
"true",
"\n",
"sm",
".",
"plugin",
".",
"SetMemory",
"(",
"in",
",",
"stateEnteredKey",
",",
"true",
")",
"\n",
"}"
] | // setEntered is used internally to set a state as having been entered both in
// memory and persisted to the database. This ensures that a stateMachine does
// not run a state's OnEntry function twice. | [
"setEntered",
"is",
"used",
"internally",
"to",
"set",
"a",
"state",
"as",
"having",
"been",
"entered",
"both",
"in",
"memory",
"and",
"persisted",
"to",
"the",
"database",
".",
"This",
"ensures",
"that",
"a",
"stateMachine",
"does",
"not",
"run",
"a",
"state",
"s",
"OnEntry",
"function",
"twice",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/state_machine.go#L248-L251 |
4,999 | itsabot/itsabot | shared/plugin/plugin.go | New | func New(url string) (*dt.Plugin, error) {
if err := core.LoadEnvVars(); err != nil {
log.Fatal(err)
}
db, err := core.ConnectDB("")
if err != nil {
return nil, err
}
// Read plugin.json data from within plugins.go, unmarshal into struct
c := dt.PluginConfig{}
if len(os.Getenv("ABOT_PATH")) > 0 {
p := filepath.Join(os.Getenv("ABOT_PATH"), "plugins.go")
var scn *bufio.Scanner
fi, err := os.OpenFile(p, os.O_RDONLY, 0666)
if os.IsNotExist(err) {
goto makePlugin
}
if err != nil {
return nil, err
}
defer func() {
if err = fi.Close(); err != nil {
log.Info("failed to close file", fi.Name())
return
}
}()
var found bool
var data string
scn = bufio.NewScanner(fi)
for scn.Scan() {
t := scn.Text()
if !found && t != url {
continue
} else if t == url {
found = true
continue
} else if len(t) >= 1 && t[0] == '}' {
data += t
break
}
data += t
}
if err = scn.Err(); err != nil {
return nil, err
}
if len(data) > 0 {
if err = json.Unmarshal([]byte(data), &c); err != nil {
return nil, err
}
if len(c.Name) == 0 {
return nil, ErrMissingPluginName
}
}
}
makePlugin:
l := log.New(c.Name)
l.SetDebug(os.Getenv("ABOT_DEBUG") == "true")
plg := &dt.Plugin{
Trigger: &dt.StructuredInput{},
SetBranches: func(in *dt.Msg) [][]dt.State { return nil },
Events: &dt.PluginEvents{
PostReceive: func(cmd *string) {},
PreProcessing: func(cmd *string, u *dt.User) {},
PostProcessing: func(in *dt.Msg) {},
PreResponse: func(in *dt.Msg, resp *string) {},
},
Config: c,
DB: db,
Log: l,
}
plg.SM = dt.NewStateMachine(plg)
return plg, nil
} | go | func New(url string) (*dt.Plugin, error) {
if err := core.LoadEnvVars(); err != nil {
log.Fatal(err)
}
db, err := core.ConnectDB("")
if err != nil {
return nil, err
}
// Read plugin.json data from within plugins.go, unmarshal into struct
c := dt.PluginConfig{}
if len(os.Getenv("ABOT_PATH")) > 0 {
p := filepath.Join(os.Getenv("ABOT_PATH"), "plugins.go")
var scn *bufio.Scanner
fi, err := os.OpenFile(p, os.O_RDONLY, 0666)
if os.IsNotExist(err) {
goto makePlugin
}
if err != nil {
return nil, err
}
defer func() {
if err = fi.Close(); err != nil {
log.Info("failed to close file", fi.Name())
return
}
}()
var found bool
var data string
scn = bufio.NewScanner(fi)
for scn.Scan() {
t := scn.Text()
if !found && t != url {
continue
} else if t == url {
found = true
continue
} else if len(t) >= 1 && t[0] == '}' {
data += t
break
}
data += t
}
if err = scn.Err(); err != nil {
return nil, err
}
if len(data) > 0 {
if err = json.Unmarshal([]byte(data), &c); err != nil {
return nil, err
}
if len(c.Name) == 0 {
return nil, ErrMissingPluginName
}
}
}
makePlugin:
l := log.New(c.Name)
l.SetDebug(os.Getenv("ABOT_DEBUG") == "true")
plg := &dt.Plugin{
Trigger: &dt.StructuredInput{},
SetBranches: func(in *dt.Msg) [][]dt.State { return nil },
Events: &dt.PluginEvents{
PostReceive: func(cmd *string) {},
PreProcessing: func(cmd *string, u *dt.User) {},
PostProcessing: func(in *dt.Msg) {},
PreResponse: func(in *dt.Msg, resp *string) {},
},
Config: c,
DB: db,
Log: l,
}
plg.SM = dt.NewStateMachine(plg)
return plg, nil
} | [
"func",
"New",
"(",
"url",
"string",
")",
"(",
"*",
"dt",
".",
"Plugin",
",",
"error",
")",
"{",
"if",
"err",
":=",
"core",
".",
"LoadEnvVars",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"db",
",",
"err",
":=",
"core",
".",
"ConnectDB",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Read plugin.json data from within plugins.go, unmarshal into struct",
"c",
":=",
"dt",
".",
"PluginConfig",
"{",
"}",
"\n",
"if",
"len",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
">",
"0",
"{",
"p",
":=",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"var",
"scn",
"*",
"bufio",
".",
"Scanner",
"\n",
"fi",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"p",
",",
"os",
".",
"O_RDONLY",
",",
"0666",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"goto",
"makePlugin",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"=",
"fi",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"fi",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"var",
"found",
"bool",
"\n",
"var",
"data",
"string",
"\n",
"scn",
"=",
"bufio",
".",
"NewScanner",
"(",
"fi",
")",
"\n",
"for",
"scn",
".",
"Scan",
"(",
")",
"{",
"t",
":=",
"scn",
".",
"Text",
"(",
")",
"\n",
"if",
"!",
"found",
"&&",
"t",
"!=",
"url",
"{",
"continue",
"\n",
"}",
"else",
"if",
"t",
"==",
"url",
"{",
"found",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"else",
"if",
"len",
"(",
"t",
")",
">=",
"1",
"&&",
"t",
"[",
"0",
"]",
"==",
"'}'",
"{",
"data",
"+=",
"t",
"\n",
"break",
"\n",
"}",
"\n",
"data",
"+=",
"t",
"\n",
"}",
"\n",
"if",
"err",
"=",
"scn",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"data",
")",
">",
"0",
"{",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"data",
")",
",",
"&",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"c",
".",
"Name",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrMissingPluginName",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"makePlugin",
":",
"l",
":=",
"log",
".",
"New",
"(",
"c",
".",
"Name",
")",
"\n",
"l",
".",
"SetDebug",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
")",
"\n",
"plg",
":=",
"&",
"dt",
".",
"Plugin",
"{",
"Trigger",
":",
"&",
"dt",
".",
"StructuredInput",
"{",
"}",
",",
"SetBranches",
":",
"func",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"[",
"]",
"[",
"]",
"dt",
".",
"State",
"{",
"return",
"nil",
"}",
",",
"Events",
":",
"&",
"dt",
".",
"PluginEvents",
"{",
"PostReceive",
":",
"func",
"(",
"cmd",
"*",
"string",
")",
"{",
"}",
",",
"PreProcessing",
":",
"func",
"(",
"cmd",
"*",
"string",
",",
"u",
"*",
"dt",
".",
"User",
")",
"{",
"}",
",",
"PostProcessing",
":",
"func",
"(",
"in",
"*",
"dt",
".",
"Msg",
")",
"{",
"}",
",",
"PreResponse",
":",
"func",
"(",
"in",
"*",
"dt",
".",
"Msg",
",",
"resp",
"*",
"string",
")",
"{",
"}",
",",
"}",
",",
"Config",
":",
"c",
",",
"DB",
":",
"db",
",",
"Log",
":",
"l",
",",
"}",
"\n",
"plg",
".",
"SM",
"=",
"dt",
".",
"NewStateMachine",
"(",
"plg",
")",
"\n",
"return",
"plg",
",",
"nil",
"\n",
"}"
] | // New builds a Plugin with its trigger, RPC, and configuration settings from
// its plugin.json. | [
"New",
"builds",
"a",
"Plugin",
"with",
"its",
"trigger",
"RPC",
"and",
"configuration",
"settings",
"from",
"its",
"plugin",
".",
"json",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/plugin/plugin.go#L31-L104 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.