1. 概要

このケーススタディの以前のパーツでは、RedditAPIを使用して簡単なアプリとOAuth認証プロセスを設定しました。

Redditで便利なものを構築しましょう–後者のスケジューリング投稿のサポート。

2. ユーザーと投稿

まず、UserPostの2つの主要なエンティティを作成しましょう。 User は、ユーザー名といくつかの追加のOauth情報を追跡します。

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false)
    private String username;

    private String accessToken;
    private String refreshToken;
    private Date tokenExpiration;

    private boolean needCaptcha;

    // standard setters and getters
}

次へ– Post エンティティ– Redditへのリンクを送信するために必要な情報を保持します: title URL subreddit 、…など。

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false) private String title;
    @Column(nullable = false) private String subreddit;
    @Column(nullable = false) private String url;
    private boolean sendReplies;

    @Column(nullable = false) private Date submissionDate;

    private boolean isSent;

    private String submissionResponse;

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private User user;
    // standard setters and getters
}

3. 永続性レイヤー

永続性にはSpring DataJPAを使用するので、リポジトリのよく知られたインターフェイス定義を除いて、ここで確認することはそれほど多くありません。

  • UserRepository:
public interface UserRepository extends JpaRepository<User, Long> {

    User findByUsername(String username);

    User findByAccessToken(String token);
}
  • PostRepository:
public interface PostRepository extends JpaRepository<Post, Long> {

    List<Post> findBySubmissionDateBeforeAndIsSent(Date date, boolean isSent);

    List<Post> findByUser(User user);
}

4. スケジューラー

アプリのスケジューリングの側面については、すぐに使用できるSpringサポートも活用します。

1分ごとに実行するタスクを定義しています。 これは、Redditに送信される投稿を検索するだけです。

public class ScheduledTasks {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    
    private OAuth2RestTemplate redditRestTemplate;
    
    @Autowired
    private PostRepository postReopsitory;

    @Scheduled(fixedRate = 1 * 60 * 1000)
    public void reportCurrentTime() {
        List<Post> posts = 
          postReopsitory.findBySubmissionDateBeforeAndIsSent(new Date(), false);
        for (Post post : posts) {
            submitPost(post);
        }
    }

    private void submitPost(Post post) {
        try {
            User user = post.getUser();
            DefaultOAuth2AccessToken token = 
              new DefaultOAuth2AccessToken(user.getAccessToken());
            token.setRefreshToken(new DefaultOAuth2RefreshToken((user.getRefreshToken())));
            token.setExpiration(user.getTokenExpiration());
            redditRestTemplate.getOAuth2ClientContext().setAccessToken(token);
            
            UsernamePasswordAuthenticationToken userAuthToken = 
              new UsernamePasswordAuthenticationToken(
              user.getUsername(), token.getValue(), 
              Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
            SecurityContextHolder.getContext().setAuthentication(userAuthToken);

            MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
            param.add("api_type", "json");
            param.add("kind", "link");
            param.add("resubmit", "true");
            param.add("then", "comments");
            param.add("title", post.getTitle());
            param.add("sr", post.getSubreddit());
            param.add("url", post.getUrl());
            if (post.isSendReplies()) {
                param.add(RedditApiConstants.SENDREPLIES, "true");
            }

            JsonNode node = redditRestTemplate.postForObject(
              "https://oauth.reddit.com/api/submit", param, JsonNode.class);
            JsonNode errorNode = node.get("json").get("errors").get(0);
            if (errorNode == null) {
                post.setSent(true);
                post.setSubmissionResponse("Successfully sent");
                postReopsitory.save(post);
            } else {
                post.setSubmissionResponse(errorNode.toString());
                postReopsitory.save(post);
            }
        } catch (Exception e) {
            logger.error("Error occurred", e);
        }
    }
}

何か問題が発生した場合、投稿は送信済みとしてマークされないことに注意してください。したがって、次のサイクルは1分後に再度送信を試みます

5. ログインプロセス

いくつかのセキュリティ固有の情報を保持する新しいユーザーエンティティでは、その情報を保存するために単純なログインプロセスを変更する必要があります

@RequestMapping("/login")
public String redditLogin() {
    JsonNode node = redditRestTemplate.getForObject(
      "https://oauth.reddit.com/api/v1/me", JsonNode.class);
    loadAuthentication(node.get("name").asText(), redditRestTemplate.getAccessToken());
    return "redirect:home.html";
}

そしてloadAuthentication()

private void loadAuthentication(String name, OAuth2AccessToken token) {
    User user = userReopsitory.findByUsername(name);
    if (user == null) {
        user = new User();
        user.setUsername(name);
    }

    if (needsCaptcha().equalsIgnoreCase("true")) {
        user.setNeedCaptcha(true);
    } else {
        user.setNeedCaptcha(false);
    }

    user.setAccessToken(token.getValue());
    user.setRefreshToken(token.getRefreshToken().getValue());
    user.setTokenExpiration(token.getExpiration());
    userReopsitory.save(user);

    UsernamePasswordAuthenticationToken auth = 
      new UsernamePasswordAuthenticationToken(user, token.getValue(), 
      Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
    SecurityContextHolder.getContext().setAuthentication(auth);
}

ユーザーがまだ存在しない場合、ユーザーがどのように自動的に作成されるかに注意してください。 これにより、「Login with Reddit」プロセスにより、最初のログイン時にシステムにローカルユーザーが作成されます。

6. スケジュールページ

次へ–新しい投稿のスケジュールを許可するページを見てみましょう。

@RequestMapping("/postSchedule")
public String showSchedulePostForm(Model model) {
    boolean isCaptchaNeeded = getCurrentUser().isCaptchaNeeded();
    if (isCaptchaNeeded) {
        model.addAttribute("msg", "Sorry, You do not have enought karma");
        return "submissionResponse";
    }
    return "schedulePostForm";
}
private User getCurrentUser() {
    return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

schedulePostForm.html

<form>
    <input name="title" />
    <input name="url" />
    <input name="subreddit" />
    <input type="checkbox" name="sendreplies" value="true"/> 
    <input name="submissionDate">
    <button type="submit" onclick="schedulePost()">Schedule</button>
</form>

<script>
function schedulePost(){
    var data = {};
    $('form').serializeArray().map(function(x){data[x.name] = x.value;});
    $.ajax({
        url: 'api/scheduledPosts',
        data: JSON.stringify(data),
        type: 'POST',
        contentType:'application/json',
        success: function(result) { window.location.href="scheduledPosts"; },
        error: function(error) { alert(error.responseText); }   
    }); 
}
</script> 
</body> 
</html>

キャプチャを確認する必要があることに注意してください。 これは、–ユーザーのカルマが10未満の場合–キャプチャを入力しないと投稿をスケジュールできないためです。

7. 投稿

スケジュールフォームが送信されると、投稿情報が検証され、永続化され、後でスケジューラーによって取得されます。

@RequestMapping(value = "/api/scheduledPosts", method = RequestMethod.POST)
@ResponseBody
public Post schedule(@RequestBody Post post) {
    if (submissionDate.before(new Date())) {
        throw new InvalidDateException("Scheduling Date already passed");
    }

    post.setUser(getCurrentUser());
    post.setSubmissionResponse("Not sent yet");
    return postReopsitory.save(post);
}

8. 予定されている投稿のリスト

次に、スケジュールされた投稿を取得するための簡単なRESTAPIを実装しましょう。

@RequestMapping(value = "/api/scheduledPosts")
@ResponseBody
public List<Post> getScheduledPosts() {
    User user = getCurrentUser();
    return postReopsitory.findByUser(user);
}

そして、これらのスケジュールされた投稿をフロントエンドに表示する簡単で迅速な方法:

<table>
    <thead><tr><th>Post title</th><th>Submission Date</th></tr></thead>
</table>

<script>
$(function(){
    $.get("api/scheduledPosts", function(data){
        $.each(data, function( index, post ) {
            $('.table').append('<tr><td>'+post.title+'</td><td>'+
              post.submissionDate+'</td></tr>');
        });
    });
});
</script>

9. スケジュールされた投稿を編集する

次へ–スケジュールされた投稿を編集する方法を見てみましょう。

フロントエンドから始めましょう–まず、非常に単純なMVC操作です。

@RequestMapping(value = "/editPost/{id}", method = RequestMethod.GET)
public String showEditPostForm() {
    return "editPostForm";
}

単純なAPIの後、これを使用するフロントエンドは次のとおりです。

<form>
    <input type="hidden" name="id" />
    <input name="title" />
    <input name="url" />
    <input name="subreddit" />
    <input type="checkbox" name="sendReplies" value="true"/>
    <input name="submissionDate">
    <button type="submit" onclick="editPost()">Save Changes</button>
</form>

<script>
$(function() {
   loadPost();
});

function loadPost(){ 
    var arr = window.location.href.split("/"); 
    var id = arr[arr.length-1]; 
    $.get("../api/scheduledPosts/"+id, function (data){ 
        $.each(data, function(key, value) { 
            $('*[name="'+key+'"]').val(value); 
        });
    }); 
}
function editPost(){
    var id = $("#id").val();
    var data = {};
    $('form').serializeArray().map(function(x){data[x.name] = x.value;});
	$.ajax({
            url: "../api/scheduledPosts/"+id,
            data: JSON.stringify(data),
            type: 'PUT',
            contentType:'application/json'
            }).done(function() {
    	        window.location.href="../scheduledPosts";
            }).fail(function(error) {
    	        alert(error.responseText);
        }); 
}
</script>

それでは、 RESTAPIを見てみましょう。

@RequestMapping(value = "/api/scheduledPosts/{id}", method = RequestMethod.GET) 
@ResponseBody 
public Post getPost(@PathVariable("id") Long id) { 
    return postReopsitory.findOne(id); 
}

@RequestMapping(value = "/api/scheduledPosts/{id}", method = RequestMethod.PUT) 
@ResponseStatus(HttpStatus.OK) 
public void updatePost(@RequestBody Post post, @PathVariable Long id) { 
    if (post.getSubmissionDate().before(new Date())) { 
        throw new InvalidDateException("Scheduling Date already passed"); 
    } 
    post.setUser(getCurrentUser()); 
    postReopsitory.save(post); 
}

10. 投稿のスケジュールを解除/削除する

また、スケジュールされた投稿の簡単な削除操作も提供します。

@RequestMapping(value = "/api/scheduledPosts/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void deletePost(@PathVariable("id") Long id) {
    postReopsitory.delete(id);
}

クライアント側からの呼び出し方法は次のとおりです。

<a href="#" onclick="confirmDelete(${post.getId()})">Delete</a>

<script>
function confirmDelete(id) {
    if (confirm("Do you really want to delete this post?") == true) {
    	deletePost(id);
    } 
}

function deletePost(id){
	$.ajax({
	    url: 'api/scheduledPosts/'+id,
	    type: 'DELETE',
	    success: function(result) {
	    	window.location.href="scheduledPosts"
	    }
	});
}
</script>

11. 結論

Redditのケーススタディのこの部分では、Reddit APIを使用して、重要な機能の最初のビットである投稿のスケジューリングを構築しました。

これは、特に時間に敏感なReddit送信を考えると、真面目なRedditユーザーにとって非常に便利な機能です。

次へ– Redditでコンテンツに賛成するのに役立つさらに便利な機能を構築します–機械学習の提案。

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