EV-Telegram-TDLib

 view release on metacpan or  search on metacpan

lib/EV/Telegram/TDLib/Users.pm  view on Meta::CPAN

package EV::Telegram::TDLib::Users;

use strict;
use warnings;
use Carp qw(croak);

our $VERSION = '0.04';

=head1 NAME

EV::Telegram::TDLib::Users - user methods for EV::Telegram::TDLib

=head1 DESCRIPTION

One of the mixins L<EV::Telegram::TDLib> inherits from. It has no
interface of its own and is not meant to be used directly: loading the
main module loads this one, and its methods are called on a client.

They are documented together with the rest of the API, under
L<EV::Telegram::TDLib/"Users mixin">.

=cut

sub CLONE_SKIP { 1 }


our %UPDATES = (
    updateUser => \&update_user,
);

sub users { $_[0]{cache}{users} ||= {} }

sub update_user {
    my ($self, $obj) = @_;
    my $user = $obj->{user} or return;
    $self->users->{ $user->{id} } = $user;
    if (my $cb = $self->{on_user}) { $cb->($user) }
}

sub me {
    my ($self, @args) = @_;
    my $cb = ref $args[-1] eq 'CODE' ? pop @args : sub {};
    no_extra('me', 0, \@args);
    $self->send({ '@type' => 'getMe' }, sub {
        my ($user, $err) = @_;
        $self->users->{ $user->{id} } = $user if $user;
        $cb->($user, $err);
    });
    return;
}

sub user {
    my ($self, $id) = @_;
    # a cache read documented to answer undef for a user not yet seen: an
    # undef id answers the same way rather than croaking, and returning early
    # keeps the lookup from warning from inside the module
    return undef unless defined $id;
    $id = 0 + $id if !ref $id && $id =~ /\A\s*[+-]?[0-9]+\s*\z/;
    return $self->users->{$id};
}

sub on_user {
    my ($self, $cb) = @_;
    $self->{on_user} = $cb if @_ > 1;
    return $self->{on_user};
}

# searchPublicChat resolves any public @name; only a private chat carries a
# user behind it, so a channel or group is reported as such rather than undef
sub user_by_username {
    my ($self, @args) = @_;
    my $cb = ref $args[-1] eq 'CODE' ? pop @args : sub {};
    no_extra('user_by_username', 1, \@args);
    my ($name) = @args;
    need('username', $name);
    $name = plain_text('a username', $name);
    $name =~ s/^\@//;
    $self->send({ '@type' => 'searchPublicChat', username => $name }, sub {
        my ($chat, $err) = @_;
        if ($err) { $cb->(undef, $err); return }
        my $uid = $chat->{type}{user_id};
        if (!$uid) {
            $cb->(undef, { '@type' => 'error', code => -1,
                           message => "\@$name is not a user" });
            return;
        }
        $self->send({ '@type' => 'getUser', user_id => 0 + $uid }, sub {
            my ($user, $err) = @_;
            $self->users->{ $user->{id} } = $user if $user;
            $cb->($user, $err);
        });
    });
    return;



( run in 0.456 second using v1.01-cache-2.11-cpan-57ff5998125 )