Skip to content

Instantly share code, notes, and snippets.

@dolmen
Created January 4, 2016 15:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dolmen/ba1a35fe0841880a3175 to your computer and use it in GitHub Desktop.
Save dolmen/ba1a35fe0841880a3175 to your computer and use it in GitHub Desktop.
Using Google Sheets from Perl 5
#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
use GSheets;
use Term::Prompt 'prompt';
my $oauth2 = $GSheets::OAUTH2;
my $url = $oauth2->authorize_url();
#you will need to put code here and receive token
print "Get code here: $url\n";
my $code = prompt('x', 'Code: ', '', '');
say "<<$code>>";
my $token = $oauth2->get_access_token($code) or die "((($@)))\n";
use Data::Dumper 'Dumper';
say "------------------";
print do {
local $Data::Dumper::Indent = 1;
local $Data::Dumper::Purity = 0;
local $Data::Dumper::Terse = 1;
local $Data::Dumper::Sortkeys = 1;
local $Data::Dumper::Quotekeys = 0;
Dumper($token->session_freeze)
};
t::lib::GSheets::save_token;
package GSheets;
use strict;
use warnings;
use Net::Google::DataAPI::Auth::OAuth2 0.05;
use Net::OAuth2::AccessToken;
use Path::Tiny;
use JSON::XS;
my $CLIENT_ID = 'FIXME';
my $CLIENT_SECRET = 'FIXME';
our $OAUTH2 = Net::Google::DataAPI::Auth::OAuth2->new(
client_id => $CLIENT_ID,
client_secret => $CLIENT_SECRET,
scope => ['https://spreadsheets.google.com/feeds/'],
);
# À chaque renouvellement du token, le nouveau sera sauvegardé
$OAUTH2->oauth2_webserver->{NOPW_auto_save} = \&save_token;
our $DIR = $ENV{'HOME'}.'/.local/share/perl5-GSheets';
our $TOKEN_FILE = path("$DIR/token.json");
sub load_token ()
{
unless ($TOKEN_FILE->is_file) {
die "You must run $^X GSheets-renew.pl";
}
my $token_data = decode_json $TOKEN_FILE->slurp_utf8;
my $token = Net::OAuth2::AccessToken->session_thaw(
$token_data,
auto_refresh => 1,
profile => $OAUTH2->oauth2_webserver,
);
$OAUTH2->access_token($token);
}
sub save_token ()
{
print STDERR "Saving token...\n";
my $token = $OAUTH2->access_token;
my $json = encode_json($token->session_freeze);
require File::Path;
File::Path::make_path(
$t::lib::GSheets::DIR,
{
mode => 0700,
});
my $umask = umask 077;
$TOKEN_FILE->spew_utf8($json);
umask $umask;
}
sub revoke_token ()
{
$TOKEN_FILE->unlink;
}
sub connect ()
{
load_token;
require Net::Google::Spreadsheets;
Net::Google::Spreadsheets->new(auth => $OAUTH2);
}
sub list_docs ()
{
my $gs = t::lib::GSheets::connect;
map { ($_->id, $_->title) } $gs->spreadsheets
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment