[31733] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 2996 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sat Jun 19 09:09:30 2010

Date: Sat, 19 Jun 2010 06:09:06 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Sat, 19 Jun 2010     Volume: 11 Number: 2996

Today's topics:
    Re: count the number of element in an array that are gr <rvtol+usenet@xs4all.nl>
    Re: MIME::Lite and SMTPS (smtp.gmail.com) <anfi@onet.eu>
    Re: MIME::Lite and SMTPS (smtp.gmail.com) <apeiron@isuckatdomains.net.invalid>
    Re: Newbie: Where to get support for basic Perl problem <clive_long@yahoo.com>
    Re: Newbie: Where to get support for basic Perl problem <clive_long@yahoo.com>
    Re: problem sending email using MIME::Lite from gmail's <apeiron@isuckatdomains.net.invalid>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Sat, 19 Jun 2010 11:26:36 +0200
From: "Dr.Ruud" <rvtol+usenet@xs4all.nl>
Subject: Re: count the number of element in an array that are greater than some  values?
Message-Id: <4c1c8d4d$0$22937$e4fe514c@news.xs4all.nl>

Peng Yu wrote:

> I'm wondering what is the shortest code to count the number of element
> in an array that are greater than some values. I'm just not familiar
> with perl enough to know what is the best way.
> 
> A for-loop is the easiest way to think of.
> 
> I also come up with the following way. But I'm not sure how to simply
> it in one line. I'm sure that there are better ways. Would you please
> let me know so that I can understand the expressive power of perl?
> 
> @new_array=grep { $_ > 5 } @array;
> $#new_array+1

Per is a strongely typed language.
One type dimension is scalar-array/hash (context).
Another type dimension is enforced by operators (casting).


Example:

perl -wle '
     my $odds = grep $_ % 2,
                     map rand($_),
                       ( 314.15927 ) x 50;
     print $odds;
'
30

-- 
Ruud


------------------------------

Date: Sat, 19 Jun 2010 09:18:21 +0200
From: Andrzej Adam Filip <anfi@onet.eu>
Subject: Re: MIME::Lite and SMTPS (smtp.gmail.com)
Message-Id: <er9kb1bls0+A6J@edward.huge.strangled.net>

Ben Morrow <ben@morrow.me.uk> wrote:
> Quoth Ted Byers <r.ted.byers@gmail.com>:
>> On Jun 17, 5:59.pm, Andrzej Adam Filip <a...@onet.eu> wrote:
>> >
>> > *Test* the hack below to make MIME::Lite use Net::SMTP::TLS instead of
>> > Net::SMTP:
>> >
>> > use MIME::Lite;
>> > use Net::SMTP::TLS;
>> > BEGIN { @MIME::Lite::SMTP::ISA = qw(Net::SMTP::TLS); }
>>
>> Thanks,  that changes things.  But I get a different error:
>> 
>> Can't locate object method "supports" via package "MIME::Lite::SMTP"
>> at C:/Perl/site/lib/MIME/Lite.pm line 2872, <GEN3> line 7.
>
> MIME::Lite is using the undocumented Net::SMTP method ->supports. This
> is arguably a bug in MIME::Lite; 
> OTOH changind a class's @ISA behind its back isn't very polite either.

I do agree that "external messing with ISA is not very polite" :-)

Another *dirty* hack to test is to make Net::SMTP use IO::Socket::SSL
instead of IO::Socket::INET and use SMTPS connection to SMTPS (465)
port [AFAIR I have been able to make Net::NNTP "support" NNTPS but I
have conducted a little more than basic tests ].

use MIME::Lite;
use Net::SMTP;
BEGIN { grep{ s/^IO::Socket::INET$/IO::Socket::SSL/ || 1 } @Net::SMTP::ISA }
 ...
MIME::Lite->send('smtp','smtp.gmail.com',Port=>465,...);

-- 
[pl>en Andrew] Andrzej Adam Filip : anfi@onet.eu : Andrzej.Filip@gmail.com
Genius is pain.
  -- John Lennon


------------------------------

Date: Sat, 19 Jun 2010 10:50:57 +0000 (UTC)
From: Chris Nehren <apeiron@isuckatdomains.net.invalid>
Subject: Re: MIME::Lite and SMTPS (smtp.gmail.com)
Message-Id: <hvi7eh$a23$2@news.eternal-september.org>

On 2010-06-19, Andrzej Adam Filip scribbled these curious markings:
> use MIME::Lite;
> use Net::SMTP;
> BEGIN { grep{ s/^IO::Socket::INET$/IO::Socket::SSL/ || 1 } @Net::SMTP::ISA }
> ...
> MIME::Lite->send('smtp','smtp.gmail.com',Port=>465,...);

Why monkeypatch when there are robust libraries already written to do
the job?

Also, you're abusing grep for side effects.

-- 
Thanks and best regards,
Chris Nehren
Unless noted, all content I post is CC-BY-SA.


------------------------------

Date: Sat, 19 Jun 2010 05:09:38 -0700 (PDT)
From: Clive <clive_long@yahoo.com>
Subject: Re: Newbie: Where to get support for basic Perl problem?
Message-Id: <c1553455-40e8-4e4a-8e0f-3dc7c50831ed@y11g2000yqm.googlegroups.com>

{quote=3D
I have no knowledge of this software you are trying to install but it
looks like you need to install some modules from cpan! }

Maybe =96 but as I wrote the module Tiny.pm is in the search list

{quote=3D
I dunno what that Tiny.pm might be, but it is not the one that is
being looked for.
It first looks for a *directory* named UUID under one of the
listed @INC dirs, then it looks for a file named Tiny.pm
inside of that UUID/ directory. }

Yes, I understand.
The INC statement has the following references

[10-06-19 09:40:57.7131] main::init (400) Warning: Can't locate UUID/
Tiny.pm in @INC
(@INC contains:
<< Snipped lots of CPAN libraries >>
/mnt/freenasmount/Slimnas/squeezebox/CPAN
/mnt/freenasmount/Slimnas/squeezebox
/usr/local/lib/perl5/5.8.9/BSDPAN
<< snip /usr/local libraries
 at /mnt/freenasmount/Slimnas/squeezebox/slimserver.pl line 400.

When I look in
/mnt/freenasmount/Slimnas/squeezebox/CPAN/UUID library on the FreeNAS
server, then =93module=94 Tiny.pm IS in there =96 so why isn't it being
found and loaded? (I'm not sure if =93found=94 =93Loaded=94 are the correct
Perl terms)


{quote=3D
Definitely Perl libraries are missing, or are in the wrong place and
can't be found. =A0But what you say about Tiny.pm actually being in one
of the libraries in the @INC path (like a system path but for Perl
modules) suggests some mis-configuration on installation. }
OK =96 but do you have a suggestion where I can look for more info to
isolate the problem?

{quote=3D

Have you seen where it says "If you have any questions or problems,
don't hesitate to contact me in the Squeezebox Server forums. " at the
bottom of the installation page you referred to? =A0Might be better to
post there first to eliminate Squeezebox-specific problems and narrow
it down to Perl. }
Yes, as in my first post, I gave the link to my posting of the problem
on the squeezebox forum.  The author of the script responded (see, in
the thread) but since then has not come up with a solution. I have to
work on the assumption he can't help me diagnose my particular
problem. So, no criticism of him, I'm casting around for others who
may have stronger Perl knowledge to help diagnose the problem, which
is why I posted here with a link back to the work I have done so far.

{quote=3D
I googled a bit and I found reference to a "build-perl-modules.pl"
script (I know nothing about Squeezebox either) ... maybe there's an
extra step in some environments. }
I very much appreciate your comments but you have left me stumped as
to what to do next.


------------------------------

Date: Sat, 19 Jun 2010 06:00:21 -0700 (PDT)
From: Clive <clive_long@yahoo.com>
Subject: Re: Newbie: Where to get support for basic Perl problem?
Message-Id: <4a695ea6-101e-4baa-919d-3918f281a7bc@w12g2000yqj.googlegroups.com>

I don't know if the following will help but I think this is the
script, slimserver.pl, being executed

#!/usr/bin/perl -w

# Squeezebox Server Copyright 2001-2009 Logitech.
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License,
# version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#

require 5.008_001;
use strict;
use warnings;

use constant SLIM_SERVICE =3D> 0;
use constant SCANNER      =3D> 0;
use constant RESIZER      =3D> 0;
use constant TRANSCODING  =3D> ( grep { /--notranscoding/ } @ARGV ) ?
0 : 1;
use constant PERFMON      =3D> ( grep { /--perfwarn/ } @ARGV ) ? 1 : 0;
use constant DEBUGLOG     =3D> ( grep { /--no(?:debug|info)log/ }
@ARGV ) ? 0 : 1;
use constant INFOLOG      =3D> ( grep { /--noinfolog/ } @ARGV ) ? 0 : 1;
use constant SB1SLIMP3SYNC=3D> ( grep { /--nosb1slimp3sync/ } @ARGV ) ?
0 : 1;
use constant WEBUI        =3D> ( grep { /--noweb/ } @ARGV ) ? 0 : 1;
use constant ISWINDOWS    =3D> ( $^O =3D~ /^m?s?win/i ) ? 1 : 0;
use constant ISMAC        =3D> ( $^O =3D~ /darwin/i ) ? 1 : 0;

use Config;
my %check_inc;
$ENV{PERL5LIB} =3D join $Config{path_sep}, grep { !$check_inc{$_}++ }
@INC;

# This package section is used for the windows service version of the
application,
# as built with ActiveState's PerlSvc
package PerlSvc;

our %Config =3D (
	DisplayName =3D> 'Squeezebox Server',
	Description =3D> "Squeezebox Server - streaming music server",
	ServiceName =3D> "squeezesvc",
	StartNow    =3D> 0,
);

sub Startup {
	# Tell PerlSvc to bundle these modules
	if (0) {
		require 'auto/Compress/Raw/Zlib/autosplit.ix';
	}

	# added to workaround a problem with 5.8 and perlsvc.
	# $SIG{BREAK} =3D sub {} if RunningAsService();
	main::initOptions();
	main::init();

	# here's where your startup code will go
	while (ContinueRun() && !main::idle()) { }

	main::stopServer();
}

sub Install {

	my($Username,$Password);

	use Getopt::Long;

	Getopt::Long::GetOptions(
		'username=3Ds' =3D> \$Username,
		'password=3Ds' =3D> \$Password,
	);

	main::initLogging();

	if ((defined $Username) && ((defined $Password) && length($Password) !
=3D 0)) {
		my @infos;
		my ($host, $user);

		# use the localhost '.' by default, unless user has defined "domain
\username"
		if ($Username =3D~ /(.+)\\(.+)/) {
			$host =3D $1;
			$user =3D $2;
		}
		else {
			$host =3D '.';
			$user =3D $Username;
		}

		# configure user to be used to run the server
		my $grant =3D PerlSvc::extract_bound_file('grant.exe');
		if ($host && $user && $grant && !`$grant add SeServiceLogonRight
$user`) {
			$Config{UserName} =3D "$host\\$user";
			$Config{Password} =3D $Password;
		}
	}
}

sub Interactive {
	main::main();
}

sub Remove {
	# add your additional remove messages or functions here
	main::initLogging();
}

sub Help {
	main::showUsage();
	main::initLogging();
}

package main;

use FindBin qw($Bin);
use lib $Bin;

our @argv;

BEGIN {
	# With EV, only use select backend
	# I have seen segfaults with poll, and epoll is not stable
	$ENV{LIBEV_FLAGS} =3D 1;

	# set the AnyEvent model to our subclassed version when PERFMON is
enabled
	$ENV{PERL_ANYEVENT_MODEL} =3D 'PerfMonEV' if main::PERFMON;
	$ENV{PERL_ANYEVENT_MODEL} ||=3D 'EV';

	# save argv
	@argv =3D @ARGV;

	use Slim::bootstrap;
	use Slim::Utils::OSDetect;

	Slim::bootstrap->loadModules();
};

use File::Slurp;
use Getopt::Long;
use File::Spec::Functions qw(:ALL);
use POSIX qw(setsid);
use Time::HiRes;
use EV;
use AnyEvent;

# Force XML::Simple to use XML::Parser for speed. This is done
# here so other packages don't have to worry about it. If we
# don't have XML::Parser installed, we fall back to PurePerl.
#
# Only use XML::Simple 2.15 an above, which has support for pass-by-
ref
use XML::Simple qw(2.15);

eval {
	local($^W) =3D 0;      # Suppress warning from Expat.pm re
File::Spec::load()
	require XML::Parser;
};

if (!$@) {
	$XML::Simple::PREFERRED_PARSER =3D 'XML::Parser';
}

use Slim::Utils::Log;
use Slim::Utils::Prefs;
use Slim::Utils::Misc;
use Slim::Buttons::Common;
use Slim::Buttons::Home;
use Slim::Buttons::Power;
use Slim::Buttons::Search;
use Slim::Buttons::ScreenSaver;
use Slim::Utils::PluginManager;
use Slim::Buttons::Synchronize;
use Slim::Buttons::Input::Text;
use Slim::Buttons::Input::Time;
use Slim::Buttons::Input::List;
use Slim::Buttons::Input::Choice;
use Slim::Buttons::Input::Bar;
use Slim::Buttons::Settings;
use Slim::Player::Client;
use Slim::Control::Request;
use Slim::Web::HTTP;
use Slim::Hardware::IR;
use Slim::Menu::TrackInfo;
use Slim::Menu::AlbumInfo;
use Slim::Menu::ArtistInfo;
use Slim::Menu::GenreInfo;
use Slim::Menu::YearInfo;
use Slim::Menu::SystemInfo;
use Slim::Menu::PlaylistInfo;
use Slim::Menu::FolderInfo;
use Slim::Menu::GlobalSearch;
use Slim::Music::Info;
use Slim::Music::Import;
use Slim::Utils::OSDetect;
use Slim::Player::Playlist;
use Slim::Player::Sync;
use Slim::Player::Source;
use Slim::Utils::Cache;
use Slim::Utils::Scanner;
use Slim::Utils::Scheduler;
use Slim::Networking::Async::DNS;
use Slim::Networking::Select;
use Slim::Networking::SqueezeNetwork;
use Slim::Networking::UDP;
use Slim::Control::Stdio;
use Slim::Utils::Strings qw(string);
use Slim::Utils::Timers;
use Slim::Utils::Update;
use Slim::Networking::Slimproto;
use Slim::Networking::SimpleAsyncHTTP;
use Slim::Utils::Firmware;
use Slim::Control::Jive;
use Slim::Formats::RemoteMetadata;

if ( SB1SLIMP3SYNC ) {
	require Slim::Player::SB1SliMP3Sync;
}

if ( DEBUGLOG ) {
	require Data::Dump;
	require Slim::Utils::PerlRunTime;
}

my $sqlHelperClass =3D Slim::Utils::OSDetect->getOS()->sqlHelperClass();
eval "use $sqlHelperClass";
die $@ if $@;

our @AUTHORS =3D (
	'Sean Adams',
	'Vidur Apparao',
	'Dean Blackketter',
	'Kevin Deane-Freeman',
	'Andy Grundman',
	'Amos Hayes',
	'Michael Herger',
	'Christopher Key',
	'Ben Klaas',
	'Mark Langston',
	'Eric Lyons',
	'Scott McIntyre',
	'Robert Moser',
	'Felix M=C3=BCller',
	'Dave Nanian',
	'Jacob Potter',
	'Sam Saffron',
	'Roy M. Silvernail',
	'Adrian Smith',
	'Richard Smith',
	'Max Spicer',
	'Dan Sully',
	'Richard Titmuss',
	'Alan Young'
);

my $prefs        =3D preferences('server');

our $VERSION     =3D '7.5.0';
our $REVISION    =3D undef;
our $BUILDDATE   =3D undef;
our $audiodir    =3D undef;
our $playlistdir =3D undef;
our $httpport    =3D undef;

our (
	$inInit,
	$cachedir,
	$user,
	$group,
	$cliaddr,
	$cliport,
	$daemon,
	$diag,
	$help,
	$httpaddr,
	$lastlooptime,
	$logfile,
	$logdir,
	$logconf,
	$debug,
	$LogTimestamp,
	$localClientNetAddr,
	$localStreamAddr,
	$newVersion,
	$pidfile,
	$prefsfile,
	$priority,
	$quiet,
	$nosetup,
	$noserver,
	$noupnp,
	$noweb,     # used in scanner to prevent loading of Slim::Web::Pages
etc.
	$notranscoding,
	$nodebuglog,
	$noinfolog,
	$nosb1slimp3sync,
	$stdio,
	$stop,
	$perfwarn,
	$failsafe,
	$checkstrings,
	$charset,
	$d_startup, # Needed for Slim::bootstrap
);

sub init {
	$inInit =3D 1;

	# Can only have one of NYTPROF and Object-Leak at a time
	if ( $ENV{OBJECT_LEAK} ) {
		require Devel::Leak::Object;
		Devel::Leak::Object->import(qw(GLOBAL_bless));
		$SIG{USR2} =3D sub {
			Devel::Leak::Object::status();
			warn "Dumping objects...\n";
		};
	}

	# initialize the process and daemonize, etc...
	srand();

	($REVISION, $BUILDDATE) =3D Slim::Utils::Misc::parseRevision();

	my $log =3D logger('server');

	$log->error("Starting Squeezebox Server (v$VERSION, r$REVISION,
$BUILDDATE) perl $]");

	if ($diag) {
		eval "use diagnostics";
	}

	# force a charset from the command line
	$Slim::Utils::Unicode::lc_ctype =3D $charset if $charset;

	Slim::Utils::OSDetect::init();

	# initialize Squeezebox Server subsystems
	initSettings();

	# Redirect STDERR to the log file.
	tie *STDERR, 'Slim::Utils::Log::Trapper';

	main::INFOLOG && $log->info("Squeezebox Server OS Specific init...");

	unless (main::ISWINDOWS) {
		$SIG{'HUP'} =3D \&initSettings;
	}

	if (Slim::Utils::Misc::runningAsService()) {
		$SIG{'QUIT'} =3D \&Slim::bootstrap::ignoresigquit;
	} else {
		$SIG{'QUIT'} =3D \&Slim::bootstrap::sigquit;
	}

	$SIG{__WARN__} =3D sub { msg($_[0]) };

	# Uncomment to enable crash debugging.
	#$SIG{__DIE__} =3D \&Slim::Utils::Misc::bt;

	# Start/stop profiler during runtime (requires Devel::NYTProf)
	# and NYTPROF env var set to 'start=3Dno'
	if ( $ENV{NYTPROF} && $INC{'Devel/NYTProf.pm'} && $ENV{NYTPROF} =3D~ /
start=3Dno/ ) {
		$SIG{USR1} =3D sub {
			DB::enable_profile();
			warn "Profiling enabled...\n";
		};

		$SIG{USR2} =3D sub {
			DB::disable_profile();
			warn "Profiling disabled...\n";
		};
	}

	# background if requested
	if (!main::ISWINDOWS && $daemon) {

		main::INFOLOG && $log->info("Squeezebox Server daemonizing...");
		daemonize();

	} else {

		save_pid_file();
	}

	# leave a mark for external tools
	$failsafe ? $prefs->set('failsafe', 1) : $prefs->remove('failsafe');

	# Change UID/GID after the pid & logfiles have been opened.
	unless (Slim::Utils::OSDetect::getOS->dontSetUserAndGroup() ||
defined($user) eq "root") {
		main::INFOLOG && $log->info("Squeezebox Server settings effective
user and group if requested...");
		changeEffectiveUserAndGroup();
	}

	# Set priority, command line overrides pref
	if (defined $priority) {
		Slim::Utils::Misc::setPriority($priority);
	} else {
		Slim::Utils::Misc::setPriority( $prefs->get('serverPriority') );
	}

	# Generate a UUID for this SC instance on first-run
	if ( !$prefs->get('server_uuid') ) {
		require UUID::Tiny;
		$prefs->set( server_uuid =3D>
UUID::Tiny::create_UUID_as_string( UUID::Tiny::UUID_V4() ) );
	}

	main::INFOLOG && $log->info("Squeezebox Server binary search path
init...");
	Slim::Utils::OSDetect::getOS->initSearchPath();

	# Find plugins and process any new ones now so we can load their
strings
	main::INFOLOG && $log->info("Squeezebox Server PluginManager
init...");
	Slim::Utils::PluginManager->init();

	main::INFOLOG && $log->info("Squeezebox Server strings init...");
	Slim::Utils::Strings::init();

	if ( $sqlHelperClass ) {
		main::INFOLOG && $log->info("Squeezebox Server SQL init...");
		$sqlHelperClass->init();
	}

	main::INFOLOG && $log->info("Async DNS init...");
	Slim::Networking::Async::DNS->init;

	main::INFOLOG && $log->info("Async HTTP init...");
	Slim::Networking::Async::HTTP->init;
	Slim::Networking::SimpleAsyncHTTP->init;

	main::INFOLOG && $log->info("Firmware init...");
	Slim::Utils::Firmware->init;

	main::INFOLOG && $log->info("Squeezebox Server Info init...");
	Slim::Music::Info::init();

	# Load the relevant importers - necessary to ensure that
Slim::Schema::init() is called.
	if ($prefs->get('audiodir')) {
		require Slim::Music::MusicFolderScan;
		Slim::Music::MusicFolderScan->init();
	}
	if ($prefs->get('playlistdir')) {
		require Slim::Music::PlaylistFolderScan;
		Slim::Music::PlaylistFolderScan->init();
	}
	initClass('Slim::Plugin::iTunes::Importer') if
Slim::Utils::PluginManager->isConfiguredEnabled('iTunes');
	initClass('Slim::Plugin::MusicMagic::Importer') if
Slim::Utils::PluginManager->isConfiguredEnabled('MusicMagic');

	main::INFOLOG && $log->info("Squeezebox Server IR init...");
	Slim::Hardware::IR::init();

	main::INFOLOG && $log->info("Squeezebox Server Request init...");
	Slim::Control::Request::init();

	main::INFOLOG && $log->info("Squeezebox Server Buttons init...");
	Slim::Buttons::Common::init();

	if ($stdio) {
		main::INFOLOG && $log->info("Squeezebox Server Stdio init...");
		Slim::Control::Stdio::init(\*STDIN, \*STDOUT);
	}

	main::INFOLOG && $log->info("UDP init...");
	Slim::Networking::UDP::init();

	main::INFOLOG && $log->info("Slimproto Init...");
	Slim::Networking::Slimproto::init();

	main::INFOLOG && $log->info("Cache init...");
	Slim::Utils::Cache->init();

	main::INFOLOG && $log->info("SqueezeNetwork Init...");
	Slim::Networking::SqueezeNetwork->init();

	unless ( $noupnp || $prefs->get('noupnp') ) {
		main::INFOLOG && $log->info("UPnP init...");
		require Slim::Utils::UPnPMediaServer;
		Slim::Utils::UPnPMediaServer::init();
	}

	main::INFOLOG && $log->info("Squeezebox Server HTTP init...");
	Slim::Web::HTTP::init();

	if (main::TRANSCODING) {
		main::INFOLOG && $log->info("Source conversion init..");
		require Slim::Player::TranscodingHelper;
		Slim::Player::TranscodingHelper::init();
	}

	if (WEBUI && !$nosetup) {
		main::INFOLOG && $log->info("Squeezebox Server Web Settings
init...");
		require Slim::Web::Setup;
		Slim::Web::Setup::initSetup();
	}

	main::INFOLOG && $log->info('Menu init...');
	Slim::Menu::TrackInfo->init();
	Slim::Menu::AlbumInfo->init();
	Slim::Menu::ArtistInfo->init();
	Slim::Menu::GenreInfo->init();
	Slim::Menu::YearInfo->init();
	Slim::Menu::SystemInfo->init();
	Slim::Menu::PlaylistInfo->init();
	Slim::Menu::FolderInfo->init();
	Slim::Menu::GlobalSearch->init();

	main::INFOLOG && $log->info('Squeezebox Server Alarms init...');
	Slim::Utils::Alarm->init();

	# load plugins before Jive init so MusicIP hooks to cached artist/
genre queries from Jive->init() will take root
	main::INFOLOG && $log->info("Squeezebox Server Load Plugins...");
	Slim::Utils::PluginManager->load();

	main::INFOLOG && $log->info("Squeezebox Server Jive init...");
	Slim::Control::Jive->init();

	main::INFOLOG && $log->info("Remote Metadata init...");
	Slim::Formats::RemoteMetadata->init();

	# Reinitialize logging, as plugins may have been added.
	if (Slim::Utils::Log->needsReInit) {

		Slim::Utils::Log->reInit;
	}

	main::INFOLOG && $log->info("Squeezebox Server checkDataSource...");
	checkDataSource();

	# regular server has a couple more initial operations.
	main::INFOLOG && $log->info("Squeezebox Server persist
playlists...");

	if ($prefs->get('persistPlaylists')) {

		Slim::Control::Request::subscribe(
			\&Slim::Player::Playlist::modifyPlaylistCallback, [['playlist']]
		);
	}

	# pull in the memory usage module if requested.
	if (main::INFOLOG && logger('server.memory')->is_info) {

		Slim::bootstrap::tryModuleLoad('Slim::Utils::MemoryUsage');

		if ($@) {

			logError("Couldn't load Slim::Utils::MemoryUsage: [$@]");

		} else {

			Slim::Utils::MemoryUsage->init();
		}
	}

	if ( main::PERFMON ) {
		main::INFOLOG && $log->info("Squeezebox Server Perfwarn init...");
		require Slim::Utils::PerfMon;
		Slim::Utils::PerfMon->init($perfwarn);
	}

	Slim::Utils::Timers::setTimer(
		undef,
		time() + 30,
		\&Slim::Utils::Update::checkVersion,
	);

	main::INFOLOG && $log->info("Squeezebox Server HTTP enable...");
	Slim::Web::HTTP::init2();

	# otherwise, get ready to loop
	$lastlooptime =3D Time::HiRes::time();

	$inInit =3D 0;

	main::INFOLOG && $log->info("Squeezebox Server done init...");
}

sub main {

	# command line options
	initOptions();

	# all other initialization
	init();

	while (!idle()) {}

	stopServer();
}

sub idle {
	# No idle processing during startup
	return if $inInit;

	my $now =3D EV::now;

	# check for time travel (i.e. If time skips backwards for DST or
clock drift adjustments)
	if ( $now < $lastlooptime || ( $now - $lastlooptime > 300 ) ) {
		# For all clients that support RTC, we need to adjust their clocks
		for my $client ( Slim::Player::Client::clients() ) {
			if ( $client->hasRTCAlarm ) {
				$client->setRTCTime;
			}
		}
	}

	$lastlooptime =3D $now;

	# This flag indicates we have pending IR or request events to handle
	my $pendingEvents =3D 0;

	# process IR queue
	$pendingEvents =3D Slim::Hardware::IR::idle();

	if ( !$pendingEvents ) {
		# empty notifcation queue, only if no IR events are pending
		$pendingEvents =3D Slim::Control::Request::checkNotifications();

		if ( !main::SLIM_SERVICE && !$pendingEvents ) {
			# run scheduled tasks, only if no other events are pending
			# XXX: need a way to not call this unless someone is using
Scheduler
			Slim::Utils::Scheduler::run_tasks();
		}
	}

	if ( $pendingEvents ) {
		# Some notifications are still pending, run the loop in non-blocking
mode
		Slim::Networking::IO::Select::loop( EV::LOOP_NONBLOCK );
	}
	else {
		# No events are pending, run the loop until we get a select event
		Slim::Networking::IO::Select::loop( EV::LOOP_ONESHOT );
	}

	return $::stop;
}

sub idleStreams {
	my $timeout =3D shift || 0;

	# No idle processing during startup
	return if $inInit;

	# Loop once without blocking
	Slim::Networking::IO::Select::loop( EV::LOOP_NONBLOCK );
}

sub showUsage {
	print <<EOF;
Usage: $0 [--diag] [--daemon] [--stdio]
          [--logdir <logpath>]
          [--logfile <logfilepath|syslog>]
          [--user <username>]
          [--group <groupname>]
          [--httpport <portnumber> [--httpaddr <listenip>]]
          [--cliport <portnumber> [--cliaddr <listenip>]]
          [--priority <priority>]
          [--prefsdir <prefspath> [--pidfile <pidfilepath>]]
          [--perfmon] [--perfwarn=3D<threshold> | --perfwarn <warn
options>]
          [--checkstrings] [--charset <charset>]
          [--noweb] [--notranscoding] [--nosb1slimp3sync]
          [--logging <logging-spec>] [--noinfolog | --nodebuglog]

    --help           =3D> Show this usage information.
    --cachedir       =3D> Directory for Squeezebox Server to save cached
music and web data
    --diag           =3D> Use diagnostics, shows more verbose errors.
                        Also slows down library processing
considerably
    --logdir         =3D> Specify folder location for log file
    --logfile        =3D> Specify a file for error logging.  Specify
'syslog' to log to syslog.
    --noLogTimestamp =3D> Don't add timestamp to log output
    --daemon         =3D> Run the server in the background.
                        This may only work on Unix-like systems.
    --stdio          =3D> Use standard in and out as a command line
interface
                        to the server
    --user           =3D> Specify the user that server should run as.
                        Only usable if server is started as root.
                        This may only work on Unix-like systems.
    --group          =3D> Specify the group that server should run as.
                        Only usable if server is started as root.
                        This may only work on Unix-like systems.
    --httpport       =3D> Activate the web interface on the specified
port.
                        Set to 0 in order disable the web server.
    --httpaddr       =3D> Activate the web interface on the specified IP
address.
    --cliport        =3D> Activate the command line interface TCP/IP
interface
                        on the specified port. Set to 0 in order
disable the
                        command line interface server.
    --cliaddr        =3D> Activate the command line interface TCP/IP
                        interface on the specified IP address.
    --prefsdir       =3D> Specify the location of the preferences
directory
    --pidfile        =3D> Specify where a process ID file should be
stored
    --quiet          =3D> Minimize the amount of text output
    --playeraddr     =3D> Specify the _server's_ IP address to use to
connect
                        to Slim players
    --priority       =3D> set process priority from -20 (high) to 20
(low)
    --streamaddr     =3D> Specify the _server's_ IP address to use to
connect
                        to streaming audio sources
    --nodebuglog     =3D> Disable all debug-level logging (compiled
out).
    --noinfolog      =3D> Disable all debug-level & info-level logging
(compiled out).
    --nosetup        =3D> Disable setup via http.
    --noserver       =3D> Disable web access server settings, but leave
player settings accessible.
                        Settings changes are not preserved.
    --noweb          =3D> Disable web interface. JSON-RPC, Comet, and
artwork web APIs are still enabled.
    --nosb1slimp3sync=3D> Disable support for SliMP3s, SB1s and
associated synchronization
    --notranscoding  =3D> Disable transcoding support.
    --noupnp         =3D> Disable UPnP subsystem
    --perfmon        =3D> Enable internal server performance monitoring
    --perfwarn       =3D> Generate log messages if internal tasks take
longer than specified threshold
    --failsafe       =3D> Don't load plugins
    --checkstrings   =3D> Enable reloading of changed string files for
plugin development
    --charset        =3D> Force a character set to be used, eg. utf8 on
Linux devices
                        which don't have full utf8 locale installed
    --logging        =3D> Enable logging for the specified comma
separated categories

Commands may be sent to the server through standard in and will be
echoed via
standard out.  See complete documentation for details on the command
syntax.
EOF
}

sub initOptions {
	my $logging;

	$LogTimestamp =3D 1;

	my $gotOptions =3D GetOptions(
		'user=3Ds'        =3D> \$user,
		'group=3Ds'       =3D> \$group,
		'cliaddr=3Ds'     =3D> \$cliaddr,
		'cliport=3Ds'     =3D> \$cliport,
		'daemon'        =3D> \$daemon,
		'diag'          =3D> \$diag,
		'help'          =3D> \$help,
		'httpaddr=3Ds'    =3D> \$httpaddr,
		'httpport=3Ds'    =3D> \$httpport,
		'logfile=3Ds'     =3D> \$logfile,
		'logdir=3Ds'      =3D> \$logdir,
		'logconfig=3Ds'   =3D> \$logconf,
		'debug=3Ds'       =3D> \$debug,
		'logging=3Ds'     =3D> \$logging,
		'LogTimestamp!' =3D> \$LogTimestamp,
		'cachedir=3Ds'    =3D> \$cachedir,
		'pidfile=3Ds'     =3D> \$pidfile,
		'playeraddr=3Ds'  =3D> \$localClientNetAddr,
		'priority=3Di'    =3D> \$priority,
		'stdio'	        =3D> \$stdio,
		'streamaddr=3Ds'  =3D> \$localStreamAddr,
		'prefsfile=3Ds'   =3D> \$prefsfile,
		# prefsdir is parsed by Slim::Utils::Prefs prior to initOptions
being run
		'quiet'	        =3D> \$quiet,
		'nodebuglog'    =3D> \$nodebuglog,
		'noinfolog'     =3D> \$noinfolog,
		'nosetup'       =3D> \$nosetup,
		'noserver'      =3D> \$noserver,
		'noupnp'        =3D> \$noupnp,
		'nosb1slimp3sync'=3D> \$nosb1slimp3sync,
		'notranscoding' =3D> \$notranscoding,
		'noweb'         =3D> \$noweb,
		'failsafe'      =3D> \$failsafe,
		'perfwarn=3Ds'    =3D> \$perfwarn,  # content parsed by PerfMon if set
		'checkstrings'  =3D> \$checkstrings,
		'charset=3Ds'     =3D> \$charset,
		'd_startup'     =3D> \$d_startup, # Needed for Slim::bootstrap
	);

	initLogging();

	# make --logging and --debug synonyms, but prefer --logging
	$debug =3D $logging if ($logging);

	if ($help || !$gotOptions) {
		showUsage();
		exit(1);
	}
}

sub initLogging {
	# open the log files
	Slim::Utils::Log->init({
		'logconf' =3D> $logconf,
		'logdir'  =3D> $logdir,
		'logfile' =3D> $logfile,
		'logtype' =3D> 'server',
		'debug'   =3D> $debug,
	});
}

sub initClass {
	my $class =3D shift;

	Slim::bootstrap::tryModuleLoad($class);

	if ($@) {
		logError("Couldn't load $class: $@");
	} else {
		$class->initPlugin;
	}
}

sub initSettings {

	Slim::Utils::Prefs::init();

	# options override existing preferences
	if (defined($cachedir)) {
		$prefs->set('cachedir', $cachedir);
		$prefs->set('librarycachedir', $cachedir);
	}

	if (defined($httpport)) {
		$prefs->set('httpport', $httpport);
	}

	if (defined($cliport)) {
		preferences('plugin.cli')->set('cliport', $cliport);
	}

	if (defined($prefs->get('cachedir')) && $prefs->get('cachedir') ne
'') {

		$cachedir =3D $prefs->get('cachedir');
		$cachedir =3D Slim::Utils::Misc::fixPath($cachedir);
		$cachedir =3D Slim::Utils::Misc::pathFromFileURL($cachedir);
		$cachedir =3D~ s|[/\\]$||;

		# Make sure cachedir exists
		Slim::Utils::Prefs::makeCacheDir($cachedir);

		$prefs->set('cachedir',$cachedir);
		$prefs->set('librarycachedir',$cachedir);
	}

	Slim::Utils::Prefs::makeCacheDir();
}

sub daemonize {
	my ($pid, $log);

	if (!defined($pid =3D fork())) {

		die "Can't fork: $!";
	}

	if ($pid) {
		save_pid_file($pid);

		# don't clean up the pidfile!
		$pidfile =3D undef;
		exit;
	}

	if (!setsid) {
		die "Can't start a new session: $!";
	}

	open STDOUT, '>>/dev/null';

	# On Leopard, GD will crash because you can't run CoreServices code
in a forked child,
	# so we have to exec as well.
	if ( $^O =3D~ /darwin/ ) {
		@argv =3D grep { $_ ne '--daemon' } @argv;
		exec $^X . ' "' . $0 . '" ' . join( ' ', @argv );
		exit;
	}
}

sub changeEffectiveUserAndGroup {

	# If we're not root and need to change user and group then die with a
	# suitable message, else there's nothing more to do, so return.
	if ($> !=3D 0) {

		if (defined($user) || defined($group)) {

			my $uname =3D getpwuid($>);
			print STDERR "Current user is $uname\n";
			print STDERR "Must run as root to change effective user or group.
\n";

			die "Aborting";

		} else {

			return;

		}

	}

	my ($uid, $pgid, @sgids, $gid);

	# Don't allow the server to be started as root.
	# MySQL can't be run as root, and it's generally a bad idea anyways.
	# Try starting as 'squeezeboxserver' instead.
	if (!defined($user)) {
		$user =3D 'squeezeboxserver';
		print STDERR "Squeezebox Server must not be run as root!  Trying
user $user instead.\n";
	}


	# Get the uid and primary group id for the $user.
	($uid, $pgid) =3D (getpwnam($user))[2,3];

	if (!defined ($uid)) {
		die "User $user not found.\n";
	}


	# Get the supplementary groups to which $user belongs

	setgrent();

	while (my @grp =3D getgrent()) {
		if ($grp[3] =3D~ m/\b$user\b/){ push @sgids, $grp[2] }
	}

	endgrent();

	# If a group was specified, get the gid of it and add it to the
	# list of supplementary groups.
	if (defined($group)) {
		$gid =3D getgrnam($group);

		if (!defined $gid) {
			die "Group $group not found.\n";
		} else {
			push @sgids, $gid;
		}
	}

	# Check that we're definately not trying to start as root, e.g. if
	# we were passed '--user root' or any other used with uid 0.
	if ($uid =3D=3D 0) {
		print STDERR "Squeezebox Server must not be run as root! Only do
this if you know what you're doing!!\n";
	}


	# Change effective group. Need to do this while still root, so do
group first

	# $) is a space separated list that begins with the effective gid
then lists
	# any supplementary group IDs, so compare against that.  On some
systems
	# no supplementary group IDs are present at system startup or at all.

	# We need to pass $pgid twice because setgroups only gets called if
there's
	# more than one value.  For example, if we did:
	# $) =3D "1234"
	# then the effective primary group would become 1234, but we'd retain
any
	# previously set supplementary groups.  To become a member of just
1234, the
	# correct way is to do:
	# $) =3D "1234 1234"

	undef $!;
	$) =3D "$pgid $pgid " . join (" ", @sgids);

	if ( $! ) {
		die "Unable to set effective group(s) to $group ($gid) is: $): $!
\n";
	}

	# Finally, change effective user id.

	undef $!;
	$> =3D $uid;

	if ( $! ) {
		die "Unable to set effective user to $user, ($uid)!\n";
	}

	logger('server')->info("Running as uid: $> / gid: $)");
}

sub checkDataSource {

	my $audiodir =3D $prefs->get('audiodir');

	if (defined $audiodir && $audiodir =3D~ m|[/\\]$|) {
		$audiodir =3D~ s|[/\\]$||;
		$prefs->set('audiodir',$audiodir);
	}

	return if !Slim::Schema::hasLibrary();

	if (Slim::Schema->schemaUpdated || Slim::Schema->count('Track',
{ 'me.audio' =3D> 1 }) =3D=3D 0) {

		logWarning("Schema updated or no tracks in the database, initiating
scan.");

		Slim::Control::Request::executeRequest(undef, ['wipecache']);
	}
}

sub forceStopServer {
	$::stop =3D 1;
}

#------------------------------------------
#
# Clean up resources and exit.
#
sub stopServer {
	my $restart =3D shift;

	logger('')->info( 'Squeezebox Server ' . ($restart ?
'restarting...' : 'shutting down.') );

	$::stop =3D 1;

	cleanup();

	if ($restart
		&& Slim::Utils::OSDetect->getOS()->canRestartServer()
		&& !main::ISWINDOWS)
	{
		exec($^X, $0, @argv);
	}

	exit();
}

sub cleanup {

	# Bug 11827, export tracks_persistent data for future use
	if ($INC{'Slim/Schema/TrackPersistent.pm'}) {

		my ($dir) =3D Slim::Utils::OSDetect::dirsFor('prefs');
		logger('')->info("Exporting persistent track data to $dir");

		Slim::Schema::TrackPersistent->export(
			catfile( $dir, 'tracks_persistent.json' )
		);
	}

	logger('')->info("Squeezebox Server cleaning up.");

	$::stop =3D 1;

	# Make sure to flush anything in the database to disk.
	if ($INC{'Slim/Schema.pm'} && Slim::Schema->storage) {

		if (Slim::Music::Import->stillScanning()) {
			logger('')->info("Cancel running scanner.");
			Slim::Music::Import->abortScan();
		}

		Slim::Schema->forceCommit;
		Slim::Schema->disconnect;
	}

	Slim::Utils::PluginManager->shutdownPlugins();

	Slim::Utils::Prefs::writeAll();

	if ($prefs->get('persistPlaylists')) {
		Slim::Control::Request::unsubscribe(
			\&Slim::Player::Playlist::modifyPlaylistCallback);
	}

	$sqlHelperClass->cleanup;

	remove_pid_file();
}

sub save_pid_file {
	my $process_id =3D shift || $$;

	logger('')->info("Squeezebox Server saving pid file.");

	if (defined $pidfile) {
		File::Slurp::write_file($pidfile, $process_id);
	}
}

sub remove_pid_file {
	 if (defined $pidfile) {
	 	unlink $pidfile;
	 }
}

sub END {

	Slim::bootstrap::theEND();
}

# start up the server if we're not running as a service.
if (!defined($PerlSvc::VERSION)) {
	main()
}

__END__


------------------------------

Date: Sat, 19 Jun 2010 10:44:17 +0000 (UTC)
From: Chris Nehren <apeiron@isuckatdomains.net.invalid>
Subject: Re: problem sending email using MIME::Lite from gmail's stmp server
Message-Id: <hvi721$a23$1@news.eternal-september.org>

On 2010-06-19, Ted Byers scribbled these curious markings:
> $html_template =~ s/>NAME</>$first_name</;

All the improvements Ben helpfully suggested, plus:

Don't parse or modify html with regular expressions! See one of
HTML::Parser's subclasses: HTML::TokeParser, HTML::TokeParser::Simple,
HTML::TreeBuilder(::Xpath)?, HTML::TableExtract, etc. See also
http://is.gd/cVdG0.  If your response begins "that's
overkill.  i only want to..." you are wrong, see also
http://tinyurl.com/ydb4j9j

(yes, a bot factoid)

Email::MIME::Kit makes it really, really easy to use templates to
generate your HTML. If you want to stick to something resembling HTML,
try HTML::Mason. If the idea of including logic in your templates makes
it hard for you to sleep at night, see Template Toolkit. The
Email::MIME::Kit::Renderer namespace on CPAN provides many ways to
render HTML messages.

> When I save the html as a local file, it appears as it is supposed to
> appear regardless of whether I use Firefox or MS IE.

If it appears as it should outside of Gmail, it's a Gmail rendering
issue, and I don't think there's much you can do about it. Perhaps you
can report it to their support (*ha*!) and they'll fix it in a later
release (*ROFL*).

-- 
Thanks and best regards,
Chris Nehren
Unless noted, all content I post is CC-BY-SA.


------------------------------

Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>


Administrivia:

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

Back issues are available via anonymous ftp from
ftp://cil-www.oce.orst.edu/pub/perl/old-digests. 

#For other requests pertaining to the digest, send mail to
#perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
#sending perl questions to the -request address, I don't have time to
#answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V11 Issue 2996
***************************************


home help back first fref pref prev next nref lref last post