Reddit APIへのリンクを投稿する

Reddit APIへのリンクを投稿する

1. 概要

the seriesのこの2番目の記事では、APIを介してアプリケーションからRedditに投稿するためのいくつかの簡単な機能を構築します。

2. 必要なセキュリティ

まず、セキュリティの側面を邪魔にならないようにしましょう。

Submit a Link to Redditを実行するには、「submit」のscopeを使用してOAuth保護リソースを定義する必要があります。

@Bean
public OAuth2ProtectedResourceDetails reddit() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setId("reddit");
    details.setClientId(clientID);
    details.setClientSecret(clientSecret);
    details.setAccessTokenUri(accessTokenUri);
    details.setUserAuthorizationUri(userAuthorizationUri);
    details.setTokenName("oauth_token");
    details.setScope(Arrays.asList("identity", "submit"));
    details.setGrantType("authorization_code");
    return details;
}

ユーザーアカウント情報にもアクセスする必要があるため、scopeidentity」も指定していることに注意してください。

3. キャプチャは必要ですか?

送信するためにReddithave to fill in a Captchaを初めて使用するユーザー。つまり、Reddit内で特定のカルマしきい値を超える前です。

これらのユーザーの場合、まずCaptchaが必要かどうかを確認する必要があります。

private String needsCaptcha() {
    String result = redditRestTemplate.getForObject(
      "https://oauth.reddit.com/api/needs_captcha.json", String.class);
    return result;
}

private String getNewCaptcha() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity req = new HttpEntity(headers);

    Map param = new HashMap();
    param.put("api_type", "json");

    ResponseEntity result = redditRestTemplate.postForEntity(
      "https://oauth.reddit.com/api/new_captcha", req, String.class, param);
    String[] split = result.getBody().split(""");
    return split[split.length - 2];
}

4. The “Submit Post” Form

Next, let’s create the main form for submitting new posts to Reddit. Submitting a Link requires the following details:

  • title – the title of the article

  • url – the URL of the article

  • subreddit – the sub-reddit to submit the link to

So let’s see how we can display this simple submission page:

@RequestMapping("/post")
public String showSubmissionForm(Model model) throws JsonProcessingException, IOException {
    String needsCaptchaResult = needsCaptcha();
    if (needsCaptchaResult.equalsIgnoreCase("true")) {
        String iden = getNewCaptcha();
        model.addAttribute("iden", iden);
    }
    return "submissionForm";
}

And of course the basic submissionForm.html:

captcha

Now – let’s take a look at the final step – submitting the actual link via the Reddit API.

We’ll POST a submit request to Reddit using the parameters from our submissionForm:

@Controller
@RequestMapping(value = "/api/posts")
public class RedditPostRestController {

    @Autowired
    private RedditService service;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public List submit(@Valid @RequestBody PostDto postDto) {
        return service.submitPost(postDto);
    }
}

Here’s the actual method implementation:

public List submitPost(PostDto postDto) {
    MultiValueMap param1 = constructParams(postDto);
    JsonNode node = redditTemplate.submitPost(param1);
    return parseResponse(node);
}

private MultiValueMap constructParams(PostDto postDto) {
    MultiValueMap param = new LinkedMultiValueMap();
    param.add("title", postDto.getTitle());
    param.add("sr", postDto.getSubreddit());
    param.add("url", postDto.getUrl());
    param.add("iden", postDto.getIden());
    param.add("captcha", postDto.getCaptcha());
    if (postDto.isSendReplies()) {
        param.add("sendReplies", "true");
    }

    param.add("api_type", "json");
    param.add("kind", "link");
    param.add("resubmit", "true");
    param.add("then", "comments");
    return param;
}

And the simple parsing logic, handling the response from the Reddit API:

private List parseResponse(JsonNode node) {
    String result = "";
    JsonNode errorNode = node.get("json").get("errors").get(0);
    if (errorNode != null) {
        for (JsonNode child : errorNode) {
            result = result + child.toString().replaceAll("\"|null", "") + "
"; } return Arrays.asList(result); } else { if ((node.get("json").get("data") != null) && (node.get("json").get("data").get("url") != null)) { return Arrays.asList("Post submitted successfully", node.get("json").get("data").get("url").asText()); } else { return Arrays.asList("Error Occurred while parsing Response"); } } }

All of this is working with a basic DTO:

public class PostDto {
    @NotNull
    private String title;

    @NotNull
    private String url;

    @NotNull
    private String subreddit;

    private boolean sendReplies;

    private String iden;
    private String captcha;
}

Finally – the submissionResponse.html:



    

Hello

Hello

Here

6. 結論

In this quick tutorial we implemented some basic Submit to Reddit functionality – simplistic but fully functional.

In the next part of this case study, we’ll implement a Schedule Post for Later functionality into our app.

このチュートリアルのfull implementationは、the github projectにあります。これはEclipseベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。