Net::SharePoint::Basic - Basic interface to Microsoft SharePoint REST API.
This module provides a basic interface for managing the Shared Documents catalog in the Microsoft SharePoint site via its REST API. In the current version only the following actions are supported:
* generating a connection token
* upload file or string
* download file content and save it
* list contents of folder
* create new folder
* delete file or folder
More actions are expected to be added in the future as well as we plan to increase the versatility of the arguments accepted by this module and the sample implementation of a client, 'sp-client', that comes with it.
The interface is object oriented. A few constants are exported.
The full testing (and naturally the full usage) of the module requires a working SharePoint site configuration. The structure of the configuration file will be described in this manual as well. The sample configuration file provided in this distribution will not work against SharePoint and plays the role of a placeholder only.
use Net::SharePoint::Basic;
my $sp = Net::SharePoint::Basic->new({config_file => 'sharepoint.conf'});
# creates Shared Documents/test
my $response = $sp->makedir({retries => 1}, '/test');
# uploads a string as Shared Documents/test/teststring
$sp->upload({}, '/test/teststring', 'abcd');
# uploads a file 'testfile' into Shared Documents/test/
The following constants (all can be overridden through either configuration file or constructor options) are exported:
=over
=item $DEFAULT_SHAREPOINT_TOKEN_FILE
The default location of the authorization token file (/var/run/sharepoint.token'
=item $DEFAULT_SHAREPOINT_CONFIG_FILE
The default location of the SharePoint portal configuration (/etc/sharepoint.conf)
=item $DEFAULT_RETRIES
The default number of retries to perform a REST action (3)
=item $DEFAULT_CHUNK_SIZE
The default chunk size for uploading large items. (200000000 bytes)
=item $MAX_LOG_SIZE
The maxium number of logged actions to keep (see C<log_it> method (500000)
=back
=head1 CONFIGURATION FILE
The module can work with a configuration file of the following format:
configuration_option <whitespace> value
The lines starting with '#' are ignored. The multiline values can be broken by using a backslash '\' sign. A sample configuration file is provided in the 't/' directory. It will NOT work with a Microsoft SharePoint instance, it is a placeholder file, useful only for internal tests. The default location of the configuration file assumed by the module is /etc/sharepoint.conf . The recognized options in the configuration file are:
* module configuration:
o token_file - where to store the SharePoint token
o max_log_size - maximum log size of $object->{log} (q.v.)
o retries - number of retries
o chunk_size - size of a chunk for upload in chunks of large files
* SharePoint configuration:
o sharepoint_client_id - UUID of this client for SharePoint
o sharepoint_client_secret - client secret for generating the access token
o sharepoint_tenant_id - UUID of the SharePoint tenant
o sharepoint_principal_id - UUID of the SharePoint principal
o sharepoint_host - the hostname of the SharePoint portal
o sharepoint_site - the site to work with in SharePoint
o sharepoint_access_url - URL to request the token from
=cut
=head1 ENVIROMENT VARIABLES
The following environment variables control the SharePoint client's behavior, for the purpose of debugging output:
* NET_SHAREPOINT_VERBOSE - enable verbose output
* NET_SHAREPOINT_DEBUG - enable debug output
=cut
=head1 SUBROUTINES/METHODS
=head2 verbose ($)
Utility function printing some extra messages. Newline is automatically appended.
Parameters: the message to print (if a verbosity setting is on).
Utility function returning the version of the package
Parameters: Do not exit after printing version (optional)
Returns: never.
=cut
subversion (;$) {
print$VERSION, "\n";
exit0 unlessshift;
}
=head2 read_file ($)
Utility function that reads file into a string or dies if the file is not available.
Parameters: the file to read
Returns: the contents of the file as a string
=cut
subread_file ($) {
my$file= shift;
local$/ = undef;
debug "Reading $file";
open(my$mail_fh, '<', $file) or die"Can't read file $file: $!";
my$content= <$mail_fh>;
close$mail_fh;
$content;
}
=head2 write_file ($$;$)
Utility function thgat writes the given string into a file, creating the necessary directories above it if necessary. Dies if the write is unsuccessful.
Parameters: the contents
the file to write
[optional] force binary mode in writing
Returns: the file path that was written.
=cut
subwrite_file ($$;$) {
my$content= shift;
my$file= shift;
my$binary= shift|| 0;
my$dir= dirname($file);
mkpath($dir) unless-d $dir;
openmy$fh, $binary? '>:raw': '>:encoding(utf8)', $fileor die"Couldn't open file $file for writing: $!";
binmode$fhif$binary;
print$fh$content;
close$fh;
verbose "Wrote file $file";
$file;
}
=head2 read_config ($)
Utility function that reads the sharepoint configuration file of whitespace separated values. See the detailed description of C<Configuration File>
Parameters: the configuration file
Returns: Hash of configuration parameters and their values.
=cut
subread_config ($) {
my$config_file= shift;
my$config= {};
open(my$conf_fh, '<', $config_file) or return0;
while(<$conf_fh>) {
nextif/^\#/;
nextunless/\S/;
s/^\s+//;
s/\s+$//;
my($key, $value) = split(/\s+/, $_, 2);
unless($value) {
$config->{$key} = undef;
next;
}
chomp$value;
while($value=~ /\\$/) {
my$extra_value= <$conf_fh>;
nextif$extra_value=~ /^\#/;
nextunless$extra_value=~ /\S/;
$extra_value=~ s/^\s+//;
$extra_value=~ s/\s+$//;
chop$value;
$value=~ s/\s+$//;
$value.= " $extra_value";
}
$config->{$key} = $value;
}
close$conf_fh;
return$config;
}
=head2 new ($;$)
The constructor. Creates the Net::SharePoint::Basic object
Parameters: optional hash with keys corresponding to the configuration file fields. Will override even the given a specific configuration file.
Validates the configuration for the SharePoint client. Checks basic syntactic requirements for the key configuration parameters expected to make connection with the REST API.
Parameters: [optional] a list of extra options that would require to be defined by the application
Returns: Error string if there was an error, empty string otherwise.
$validated.= "SharePoint Site must include 'sites' in the URL\n"
unless$opts->{sharepoint_site}
&& $opts->{sharepoint_site} =~ m|^sites/.+|;
formy$extra_opt(@extra_opts) {
$validated.= "Option $extra_opt must be set according to the app"
unless$opts->{$extra_opt};
}
return$validated;
}
=head2 log_it ($$;$)
Log a message into the object. The messages are stored in the $object->{log} array reference. If the amount of messages exceeds $MAX_LOG_SIZE or $self->{config}{max_log_size} (if set), the older messages are shifted out of the log.
Uploads a file or a string to SharePoint. Initiates the upload in chunks if necessary, generating the zero sized file for it before calling C<upload_in_chunks>
Parameters: the options hash with
type - "file" means we're uploading a file
retries - the number of retries
the SharePoint target. If it's a path ending with '/', basename of the file is being appended.
the item - file or data string
Returns: the HTTP response object if successful.
0 when the upload fails or
when the file is unreadable or
when the upload is of a string and no target filename is specified.
Downloads an object from SharePoint, optionally saving it into a file.
Parameters: the options hashref
save_file - the local path to save (or see target below)
retries - the number of retries
the SharePoint path to download
(optional) the target local path to save. If target (or save_file value) is a directory, use basename of the SharePoint path for filename. The directory tree is created via C<write_file>.
Returns: 0 if download failed
path contents as a string scalar if string is requested
saved path if a file save is requested
=cut
subdownload ($$$;$) {
my$self= shift;
my$opts= shift;
my$item= shift;
my$target= shift|| '';
$opts->{save_file} = $targetif$target;
my$download_url= $self->create_sharepoint_url({
type=> 'download',
object=> basename($item),
folder=> dirname($item),
});
$self->log_it("Download from $download_url", 'debug');
Gets the contents of a given SharePoint folder. Note that you cannot list a file, you need to provide its path (event if it is root), and filter the results. Two API calls are issued, one to list files in the folders, one to list subfolders.
Parameters: the options hashref
path - the path to list
retries - the number of retries
path - (optional) - alternative way to specify path to list
Returns: a decoded JSON structure of the REST API response or
an empty list in case of failure.
For the interpretation of the results for an actual listing, see the print_list_reports subroutine in the example SharePoint client provided in the package.
Returns: the REST API response as returned by C<try()>
Note: any item will be deleted (put to Recycle Bin), even a non-empty folder. If a non-existent item is requested for deletion, the deletion will still return success, but the resulting response will have field $json->{d}{Recycle} set to "00000000-0000-0000-0000-000000000000"
Please report any bugs or feature requests to C<bug-net-sharepoint-simple at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-SharePoint-Basic>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
=head1 SUPPORT
You can find documentation for this module with the perldoc command.
Special thanks to Andre Abramenko L<https://www.pilothouseconsulting.com/> for helping me figure out the REST API when I initially implemented it at VMware.
=head1 LICENSE AND COPYRIGHT
Copyright 2018 VMware.com
This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.