File: RootObj.pm

package info (click to toggle)
libcircle-be-perl 0.173320-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 388 kB
  • sloc: perl: 6,042; makefile: 2; sh: 1
file content (601 lines) | stat: -rw-r--r-- 13,789 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
#  You may distribute under the terms of the GNU General Public License
#
#  (C) Paul Evans, 2008-2014 -- leonerd@leonerd.org.uk

package Circle::RootObj;

use strict;
use warnings;
use base qw( Tangence::Object Circle::WindowItem );

our $VERSION = '0.173320';

use Class::Method::Modifiers;

use Carp;
use YAML (); # 'Dump' and 'Load' are a bit generic; we'll call by FQN

use Circle::Rule::Store;
require Circle::GlobalRules;

use Circle::CommandInvocation;

use Module::Pluggable sub_name    => "net_types",
                      search_path => [ "Circle::Net" ],
                      only        => qr/^Circle::Net::\w+$/, # Not inner ones
                      force_search_all_paths => 1;

{
   foreach my $class ( net_types ) {
      ( my $file = "$class.pm" ) =~ s{::}{/}g;
      require $file;
   }
}

use Data::Dump;

use constant CIRCLERC => $ENV{CIRCLERC} || "$ENV{HOME}/.circlerc";

sub _nettype2class
{
   my ( $type ) = @_;

   foreach ( __PACKAGE__->net_types ) {
      my $thistype = eval { $_->NETTYPE };
      if( defined $thistype and $thistype eq $type ) {
         return $_;
      }
   }

   return undef;
}

sub new
{
   my $class = shift;
   my %args = @_;

   my $loop = delete $args{loop} or croak "Need a loop";

   my $self = $class->SUPER::new( %args );

   $self->{loop} = $loop;

   my $rulestore = $self->{rulestore} = Circle::Rule::Store->new();
   Circle::GlobalRules::register( $rulestore );

   my $file = $args{config} // CIRCLERC;
   if( -r $file ) {
      my $config = YAML::LoadFile( $file );
      $self->load_configuration( $config );
   }

   return $self;
}

sub add_network
{
   my $self = shift;
   my ( $class, $name ) = @_;

   my $loop = $self->{loop};

   # Late-loading to support out-of-tree classes so they don't have to declare
   #   in the .tan file
   eval { Tangence::Class->for_perlname( $class ) } or
      eval { $class->DECLARE_TANGENCE } or
      croak "Unknown Tangence::Class for '$class' and can't lazy-load it";

   my $registry = $self->{registry};
   my $newnet = $registry->construct(
      $class,
      tag  => $name,
      root => $self,
      loop => $loop,
   );

   $newnet->subscribe_event( destroy => sub {
      my ( $newnet ) = @_;
      $self->broadcast_sessions( "delete_item", $newnet );
      $self->del_prop_networks( $name );
   } );

   $self->fire_event( "network_added", $newnet );
   $self->add_prop_networks( $name => $newnet );

   $self->broadcast_sessions( "new_item", $newnet );

   return $newnet;
}

sub del_network
{
   my $self = shift;
   my ( $network ) = @_;

   $network->destroy;
}

use Circle::Collection
   name  => 'networks',
   storage => {
      list => sub {
         my $self = shift;
         my $networks = $self->get_prop_networks;
         return map { { name => $_, type => $networks->{$_}->NETTYPE } } sort keys %$networks;
      },

      get => sub {
         my $self = shift;
         my ( $name ) = @_;
         my $network = $self->get_prop_networks->{$name} or return undef;
         return { name => $name, type => $network->NETTYPE };
      },

      add => sub {
         my $self = shift;
         my ( $name, $item ) = @_;

         my $class = _nettype2class( $item->{type} );

         defined $class or die "unrecognised network type '$item->{type}'\n";

         $self->add_network( $class, $name );
      },

      del => sub {
         my $self = shift;
         my ( $name ) = @_;
         my $network = $self->get_prop_networks->{$name} or return;

         $network->connected and die "still connected\n";

         $self->del_network( $network );
      },
   },
   attrs => [
      name => {},
      type => { nomod => 1, default => "irc" },
   ],
   config => {
      type => "hash",
      load => sub {
         my $self = shift;
         my ( $name, $ynode ) = @_;
         $self->get_prop_networks->{$name}->load_configuration( $ynode );
      },
      store => sub {
         my $self = shift;
         my ( $name, $ynode ) = @_;
         $self->get_prop_networks->{$name}->store_configuration( $ynode );
      },
   },
   ;

our %sessions;

sub add_session
{
   my $self = shift;
   my ( $identity, $type ) = @_;

   eval "require $type";
   die $@ if $@;

   my $registry = $self->{registry};

   my $session = $registry->construct(
      $type,
      root => $self,
      identity => $identity,
   );

   return $sessions{$identity} = $session;
}

sub method_get_session
{
   my $self = shift;
   my ( $ctx, $opts ) = @_;

   my $identity = $ctx->stream->identity;

   return $sessions{$identity} if exists $sessions{$identity};
   
   my $type = _session_type( $opts );

   defined $type or die "Cannot identify a session type\n";

   return $self->add_session( $identity, $type );
}

sub broadcast_sessions
{
   my $self = shift;
   my ( $method, @args ) = @_;

   foreach my $session ( values %sessions ) {
      $session->$method( @args ) if $session->can( $method );
   }
}

sub invoke_session
{
   my $self = shift;
   my ( $conn, $method, @args ) = @_;

   my $session = $sessions{$conn->identity};
   return unless $session;

   $session->$method( @args ) if $session->can( $method );
}

sub _session_type
{
   my ( $opts ) = @_;
   my %opts = map { $_ => 1 } @$opts;

   if( $opts{tabs} ) {
      delete $opts{tabs};
      require Circle::Session::Tabbed;
      return Circle::Session::Tabbed::_session_type( \%opts );
   }

   print STDERR "Need Session for options\n";
   print STDERR "  ".join( "|", sort keys %opts )."\n";

   return undef;
}

use Circle::Collection
   name => 'sessions',
   storage => {
      list => sub {
         map { my $class = ref $sessions{$_}; $class =~ s/^Circle::Session:://;
               { name => $_, type => $class } } sort keys %sessions;
      },
   },
   attrs => [
      name => {},
      type => { nomod => 1 },
   ],
   commands => {
      # Disable add modify del
      add => undef, mod => undef, del => undef,
   },
   config => 0,
   ;

sub command_session
   : Command_description("Manage the current session")
{
}

sub command_session_info
   : Command_description("Show information about the session")
   : Command_subof('session')
   : Command_default()
{
   my $self = shift;
   my ( $cinv ) = @_;

   my $identity = $cinv->connection->identity;
   my $session = defined $identity ? $sessions{$identity} : undef;

   unless( defined $session ) {
      $cinv->responderr( "Cannot find a session for this identity" );
      return;
   }

   ( my $type = ref $session ) =~ s/^Circle::Session:://;

   $cinv->respond_table(
      [
         [ Type     => $type ],
         [ Identity => $identity ],
         [ Items    => scalar $session->items ],
      ],
      colsep => ": ",
   );

   return;
}

sub command_session_clonefrom
   : Command_description("Clone items from another session")
   : Command_subof('session')
   : Command_arg('name')
{
   my $self = shift;
   my ( $name, $cinv ) = @_;

   my $identity = $cinv->connection->identity;

   my $destsession = defined $identity ? $sessions{$identity} : undef or
      return $cinv->responderr( "Cannot find a session for this identity" );

   my $srcsession = $sessions{$name} or
      return $cinv->responderr( "Cannot find a session called '$name'" );

   eval { $destsession->clonefrom( $srcsession ); 1 } or
      return $cinv->responderr( "Cannot clone $name into $identity - $@" );

   return;
}

sub command_eval
   : Command_description("Evaluate a perl expression")
   : Command_arg('expr', eatall => 1)
{
   my $self = shift;
   my ( $expr, $cinv ) = @_;

   my $connection = $cinv->connection;

   my $identity = $connection->identity;
   my $session = defined $identity ? $sessions{$identity} : undef;

   my %pad = (
      ROOT    => $self,
      LOOP    => $self->{loop},
      CONN    => $connection,
      ITEM    => $cinv->invocant,
      SESSION => $session,
   );

   my $result = do {
      local $SIG{__WARN__} = sub {
         my $msg = $_[0];
         $msg =~ s/ at \(eval \d+\) line \d+\.$//;
         chomp $msg;
         $cinv->respondwarn( $msg, level => 2 );
      };

      eval join( "", map { "my \$$_ = \$pad{$_}; " } keys %pad ) . "$expr";
   };

   if( $@ ) {
      my $err = $@; chomp $err;
      $cinv->responderr( "Died: $err" );
   }
   else {
      my @lines;

      my $timedout;
      local $SIG{ALRM} = sub { $timedout = 1; die };
      eval {
         alarm(5);
         @lines = split m/\n/, Data::Dump::dump($result);
         alarm(0);
      };

      if( $timedout ) {
         $cinv->responderr( "Failed - took too long to render results. Try something more specific" );
         return;
      }

      if( @lines > 20 ) {
         @lines = ( @lines[0..18], "...", $lines[-1] );
      }

      if( @lines == 1 ) {
         $cinv->respond( "Result: $lines[0]" );
      }
      else {
         $cinv->respond( "Result:" );
         $cinv->respond( "  $_" ) for @lines;
      }
   }

   return;
}

sub command_rerequire
   : Command_description("Rerequire a perl module")
   : Command_arg('module')
{
   my $self = shift;
   my ( $module, $cinv ) = @_;

   # This might be a module name Foo::Bar or a filename Foo/Bar.pm
   my $filename;

   if( $module =~ m/::/ ) {
      ( $filename = $module ) =~ s{::}{/}g;
      $filename .= ".pm";
   }
   elsif( $module =~ m/^(.*)\.pm$/ ) {
      $filename = $module;
      ( $module = $1 ) =~ s{/}{::}g;
   }
   else {
      return $cinv->responderr( "Unable to recognise if $module is a module name or a file name" );
   }

   if( !exists $INC{$filename} ) {
      return $cinv->responderr( "Module $module in file $filename isn't loaded" );
   }

   {
      local $SIG{__WARN__} = sub {
         my $msg = $_[0];
         $msg =~ s/ at \(eval \d+\) line \d+\.$//;
         chomp $msg;
         $cinv->respondwarn( $msg, level => 2 );
      };

      no warnings 'redefine';

      delete $INC{$filename};
      eval { require $filename };
   }

   if( $@ ) {
      my $err = $@; chomp $err;
      $cinv->responderr( "Died: $err" );
   }
   else {
      $cinv->respond( "Reloaded $module from $filename" );
   }

   return;
}

sub commandable_parent
{
   my $self = shift;
   my ( $cinv ) = @_;

   return $sessions{$cinv->connection->identity};
}

sub enumerate_items
{
   my $self = shift;
   my $networks = $self->get_prop_networks;
   return { map { $_->enumerable_name => $_ } values %$networks };
}

sub enumerable_name
{
   return "";
}

sub parent
{
   return undef;
}

sub command_delay
   : Command_description("Run command after some delay")
   : Command_arg('seconds')
   : Command_arg('command', eatall => 1)
{
   my $self = shift;
   my ( $seconds, $text, $cinv ) = @_;

   # TODO: A CommandInvocant subclass that somehow prefixes its output so we
   # know it's delayed output from earlier, so as not to confuse
   my $subinv = $cinv->nest( $text );

   my $cmdname = $subinv->peek_token or
      return $cinv->responderr( "No command given" );

   my $loop = $self->{loop};

   my $id = $loop->enqueue_timer(
      delay => $seconds,
      code => sub {
         eval {
            $subinv->invocant->do_command( $subinv );
         };
         if( $@ ) {
            my $err = $@; chomp $err;
            $cinv->responderr( "Delayed command $cmdname failed - $err" );
         }
      },
   );

   # TODO: Store ID, allow list, cancel, etc...

   return;
}

###
# Configuration management
###

sub command_config
   : Command_description("Save configuration or change details about it")
{
   # The body doesn't matter as it never gets run
}

sub command_config_show
   : Command_description("Show the configuration that would be saved")
   : Command_subof('config')
   : Command_default()
{
   my $self = shift;
   my ( $cinv ) = @_;

   # Since we're only showing config, only fetch it for the invocant
   my $obj = $cinv->invocant;

   unless( $obj->can( "get_configuration" ) ) {
      $cinv->respond( "No configuration" );
      return;
   }

   my $config = YAML::Dump( $obj->get_configuration );

   $cinv->respond( $_ ) for split m/\n/, $config;
   return;
}

sub command_config_save
   : Command_description("Save configuration to disk")
   : Command_subof('config')
{
   my $self = shift;
   my ( $cinv ) = @_;

   my $file = CIRCLERC;
   YAML::DumpFile( $file, $self->get_configuration );

   $cinv->respond( "Configuration written to $file" );
   return;
}

sub command_config_reload
   : Command_description("Reload configuration from disk")
   : Command_subof('config')
{
   my $self = shift;
   my ( $cinv ) = @_;

   my $file = CIRCLERC;
   $self->load_configuration( YAML::LoadFile( $file ) );

   $cinv->respond( "Configuration loaded from $file" );
   return;
}

# For Configurable role
after load_configuration => sub {
   my $self = shift;
   my ( $ynode ) = @_;

   if( my $sessions_ynode = $ynode->{sessions} ) {
      foreach my $sessionname ( keys %$sessions_ynode ) {
         my $sessionnode = $sessions_ynode->{$sessionname};
         my $type = $sessionnode->{type};

         my $session = $self->add_session( $sessionname, "Circle::Session::$type" );
         $session->load_configuration( $sessionnode );
      }
   }
};

after store_configuration => sub {
   my $self = shift;
   my ( $ynode ) = @_;

   my $sessions_ynode = $ynode->{sessions} ||= YAML::Node->new({});
   %$sessions_ynode = ();

   foreach my $identity ( keys %sessions ) {
      my $session = $sessions{$identity};

      my $sessionnode = $session->get_configuration;
      $sessions_ynode->{$identity} = $sessionnode;

      unless( $sessionnode->{type} ) { # exists doesn't quite play ball
         # Ensure it's first
         unshift @{ tied(%$sessionnode)->keys }, 'type'; # I am going to hell for this
         ( $sessionnode->{type} ) = (ref $session) =~ m/^Circle::Session::(.*)$/;
      }
   }
};

0x55AA;