使用推送器仅向朋友推送消息

Using Pusher to push messages to friends only

本文关键字:朋友 消息      更新时间:2023-09-26

我已经在基于模型Post的Rails应用程序上设置了基本的Pusher功能,但Pusher更新会发送给所有用户,而我希望只有与发件人"有联系/朋友"的用户才能看到更新。

在视图中使用javascript还是ruby最好地解决这个问题?从控制器,我通过Pusher发送@post.user_id到视图,但在实现以下内容时,我似乎无法使其工作:

后控制器

def index
    # Get the current user's friends
    @friends = current_user.friends.all

    end
end
def create
    @post = current_user.posts.new(post_params)
    @puserid = @post.user_id
    @postuser = User.find_by_id(@puserid)
    @userslug = @postuser.slug
    @ids = current_user.friends.pluck(:id) << current_user.id
    if @post.save
        #flash[:success] = "You have created a new post"
        redirect_to posts_path
        Pusher['worklink'].trigger('update', {
            postcontent: @post.content,
            userid: @post.user_id,
            userslug: @userslug,
            userfirstname: @postuser.firstname,
            userlastname: @postuser.lastname,
            postid: @post.id
            })

    else
        render "new"
    end
end

后索引视图

<script src="https://js.pusher.com/2.2/pusher.min.js"></script>
<script type="text/javascript">
var pusher = new Pusher('<%= Pusher.key %>'); // uses your API KEY
var channel = pusher.subscribe('worklink');
channel.bind('update', function(data) {
var prependLink = "<a href='/profile/" + data.userslug + "'>" + data.userfirstname + " " + data.userlastname + " " + "</a><span class='red small'>New</span>";
var user = data.userid;
$("#comments").prepend(
    "<% if @friends.include?(" + user + ") %><div class='post_box'><div class='post'><p class='username'><b>" + prependLink + "</b></p><p class='post_content'>" + data.postcontent + "</p><div class='post_attributes'><ul><div class='right'><li class='small bold'>0&nbsp;</li><li class='x'><a data-method='post' href='/home/" + data.postid + "/likes' rel='nofollow'><img alt='Tick2' src='/assets/tick2.png'></a></li></div><li class='post_time'>less than a minute ago</li></ul></div></div></div><% end %>");

$('.post p:contains("http://")').html(function(index, html) {
var url = html.match(/(((ftp|https?):'/'/)['-'w@:%_'+.~#?,&'/'/=]+)|((mailto:)?[_.'w-]+@(['w]['w'-]+'.)+[a-zA-Z]{2,3})/g);
$.each(url, function(i, v) {
    html = html.replace(v, '<a href="' + v + '" target="_blank">' + v + '</a>');        
});
return html;
});
});
</script>

有三种不同的通道类型(http://pusher.com/docs/client_api_guide/client_channels):

  • 私人
  • 公共
  • 存在

我想最适合你的是存在,它需要在订阅前进行身份验证,你可以控制是否允许订阅。

此外,您可以参考此代码以获得更多功能示例:https://github.com/tarnfeld/PusherChat-Rails