Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a plugin for /pony #10422

Merged
merged 1 commit into from
Dec 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions prow/plugins/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ filegroup(
"//prow/plugins/milestonestatus:all-srcs",
"//prow/plugins/override:all-srcs",
"//prow/plugins/owners-label:all-srcs",
"//prow/plugins/pony:all-srcs",
"//prow/plugins/releasenote:all-srcs",
"//prow/plugins/require-matching-label:all-srcs",
"//prow/plugins/requiresig:all-srcs",
Expand Down
39 changes: 39 additions & 0 deletions prow/plugins/pony/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")

go_library(
name = "go_default_library",
srcs = ["pony.go"],
importpath = "k8s.io/test-infra/prow/plugins/pony",
visibility = ["//visibility:public"],
deps = [
"//prow/github:go_default_library",
"//prow/pluginhelp:go_default_library",
"//prow/plugins:go_default_library",
"//vendor/github.com/sirupsen/logrus:go_default_library",
],
)

go_test(
name = "go_default_test",
srcs = ["pony_test.go"],
embed = [":go_default_library"],
deps = [
"//prow/github:go_default_library",
"//prow/github/fakegithub:go_default_library",
"//vendor/github.com/sirupsen/logrus:go_default_library",
],
)

filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)

filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
163 changes: 163 additions & 0 deletions prow/plugins/pony/pony.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package pony adds pony images to issues in response to a /pony comment
package pony

import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"regexp"

"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/plugins"
)

// Only the properties we actually use.
type ponyResult struct {
Pony ponyResultPony `json:"pony"`
}

type ponyResultPony struct {
Representations ponyRepresentations `json:"representations"`
}

type ponyRepresentations struct {
Full string `json:"full"`
Small string `json:"small"`
}

const (
ponyURL = realHerd("https://theponyapi.com/pony.json")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the API with which we will need to be careful? Does it expose user-provided content? Do we run the risk of posting inappropriate images here?

Copy link
Member Author

@Katharine Katharine Dec 13, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All the images returned by this API (which is not the same one discussed previously, though that is its root data source) have been manually reviewed for appropriateness. It should be at least as safe as /meow

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ixdy didn't we just have an oopsie with the cat plugin?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stevekuznetsov yes, there was apparently a bug in which images which were rejected were still available via a direct request. it's supposedly fixed now; all cat images are supposed to be reviewed first as well.

pluginName = "pony"
)

var (
match = regexp.MustCompile(`(?mi)^/(?:pony)(?:\s+(.+?))?\s*$`)
)

func init() {
plugins.RegisterGenericCommentHandler(pluginName, handleGenericComment, helpProvider)
}

func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) {
// The Config field is omitted because this plugin is not configurable.
pluginHelp := &pluginhelp.PluginHelp{
Description: "The pony plugin adds a pony image to an issue in response to the `/pony` command.",
}
pluginHelp.AddCommand(pluginhelp.Command{
Usage: "/(pony) [pony]",
Description: "Add a little pony image to the issue. A particular pony can optionally be named for a picture of that specific pony.",
Featured: false,
WhoCanUse: "Anyone",
Examples: []string{"/pony", "/pony Twilight Sparkle"},
})
return pluginHelp, nil
}

var client = http.Client{}

type githubClient interface {
CreateComment(owner, repo string, number int, comment string) error
}

type herd interface {
readPony(string) (string, error)
}

type realHerd string

func formatURLs(small, full string) string {
return fmt.Sprintf("[![pony image](%s)](%s)", small, full)
}

func (h realHerd) readPony(tags string) (string, error) {
// Omit webm video (the only video type) and anything too far off square.
q := "-webm, aspect_ratio:1~0.5"
if tags != "" {
q += ", " + tags
}
uri := string(h) + "?q=" + url.QueryEscape(q)
resp, err := client.Get(uri)
if err != nil {
return "", fmt.Errorf("failed to make request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("no pony found")
}
var a ponyResult
if err = json.NewDecoder(resp.Body).Decode(&a); err != nil {
return "", fmt.Errorf("failed to decode response: %v", err)
}

embedded := a.Pony.Representations.Small
tooBig, err := github.ImageTooBig(embedded)
if err != nil {
return "", fmt.Errorf("couldn't fetch pony for size check: %v", err)
}
if tooBig {
return "", fmt.Errorf("the pony is too big")
}
return formatURLs(a.Pony.Representations.Small, a.Pony.Representations.Full), nil
}

func handleGenericComment(pc plugins.Agent, e github.GenericCommentEvent) error {
return handle(pc.GitHubClient, pc.Logger, &e, ponyURL)
}

func handle(gc githubClient, log *logrus.Entry, e *github.GenericCommentEvent, p herd) error {
// Only consider new comments.
if e.Action != github.GenericCommentActionCreated {
return nil
}
// Make sure they are requesting a pony
mat := match.FindStringSubmatch(e.Body)
if mat == nil {
return nil
}

tag := mat[1]
org := e.Repo.Owner.Login
repo := e.Repo.Name
number := e.Number

for i := 0; i < 5; i++ {
resp, err := p.readPony(tag)
if err != nil {
log.WithError(err).Println("Failed to get a pony")
continue
}
return gc.CreateComment(org, repo, number, plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, resp))
}

var msg string
if tag != "" {
msg = "Couldn't find a pony matching that query."
} else {
msg = "https://theponyapi.com appears to be down"
}
if err := gc.CreateComment(org, repo, number, plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, msg)); err != nil {
log.WithError(err).Error("Failed to leave comment")
}

return errors.New("could not find a valid pony image")
}
Loading