From 2fa89b83b1a48165bf56feda84801715c19fd239 Mon Sep 17 00:00:00 2001 From: Ralf Ertzinger Date: Wed, 8 May 2013 19:57:20 +0200 Subject: [PATCH] libvideosite: Add capability to initialize, load and save a config with builtin methods --- libvideosite.pm | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/libvideosite.pm b/libvideosite.pm index 959e61c..01fa7d9 100644 --- a/libvideosite.pm +++ b/libvideosite.pm @@ -17,6 +17,8 @@ use LWP::UserAgent; use Data::Dumper; use File::Basename; use Cwd qw(realpath); +use JSON -support_by_pp; +use File::Temp qw(tempfile); use strict; @ISA = qw(Exporter); @@ -30,6 +32,8 @@ my @grabbers; my @getters; my $getter; my %builtin_config = (); +my $builtin_config_path; +my $builtin_config_default; our $error; # @@ -921,6 +925,29 @@ sub _grabbers { # ============================================== # sub _builtin_config_init { + + if (defined($builtin_config_path)) { + my $filename = File::Spec->catfile($builtin_config_path, 'videosite.json'); + + _debug("Trying to load configuration from %s", $filename); + + if (-r $filename) { + eval { + local $/; + open(CONF, '<', $filename); + %builtin_config = %{JSON->new->utf8->decode()}; + close(CONF); + } or do { + _io("Error loading configuration: %s", $@); + } + }; + } elsif (defined($builtin_config_default)) { + _debug("Initializing builtin config from external default"); + foreach (keys(%{$builtin_config_default})) { + _debug("Setting %s=%s", $_, $builtin_config_default->{$_}); + $builtin_config{$_} = $builtin_config_default->{$_}; + } + } } sub _builtin_config_get { @@ -936,6 +963,23 @@ sub _builtin_config_has { } sub _builtin_config_save { + + if (defined($builtin_config_path)) { + my $filename = File::Spec->catfile($builtin_config_path, 'videosite.json'); + + _debug("Attempting to save config to %s", $filename); + + eval { + my ($tempfile, $tempfn) = tempfile("videosite.json.XXXXXX", dir => $builtin_config_path); + print $tempfile JSON->new->pretty->utf8->encode(\%builtin_config); + close($tempfile); + rename($tempfn, $filename); + } or do { + return 0; + } + } + + return 1; } sub _builtin_config_del { @@ -1034,6 +1078,14 @@ sub register_api { $debug = $a->{_debug}->(); } + if (exists($a->{_config_path})) { + $builtin_config_path = $a->{_config_path}->(); + } + + if (exists($a->{_config_default})) { + $builtin_config_default = $a->{_config_default}->(); + } + @outputstack = ({ewpf => $remote_api->{'io'}, window => ""}); return 1; -- 1.8.3.1