api.cgi 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/local/cpanel/3rdparty/bin/perl
  2. #ACLS:all
  3. package Troglodyne::CGI::API;
  4. use strict;
  5. use warnings;
  6. use Cpanel::LoadModule::Custom ();
  7. use JSON::XS ();
  8. exit run() unless caller();
  9. sub run {
  10. # Load up CGI processing modules
  11. Cpanel::LoadModule::Custom::load_perl_module("Troglodyne::CGI");
  12. my $ret = {
  13. 'metadata' => {
  14. 'input_args' => $args,
  15. },
  16. };
  17. # Process the args
  18. my $args = {};
  19. my $err;
  20. {
  21. local $@;
  22. $args = eval { Troglodyne::CGI::get_args() };
  23. $err = $@;
  24. }
  25. if(!scalar(keys(%$args))) {
  26. $ret->{'result'} = 0;
  27. $ret->{'error'} = "No args detected! $err";
  28. return emit($ret);
  29. }
  30. # XXX Validation plz
  31. # Load route code
  32. my $namespace = "Troglodyne::API::$args->{'module'}";
  33. my ( $loaded, $err, $coderef );
  34. {
  35. local $@;
  36. $loaded = eval {
  37. Cpanel::LoadModule::Custom::load_perl_module($namespace);
  38. };
  39. $err = $@;
  40. $coderef = $namespace->can($args->{'function'});
  41. }
  42. # Get back the datastruct from the called module.
  43. # Yeah, yeah, I know. String eval. XXX
  44. if( $loaded && $coderef ) {
  45. local $@;
  46. my $data = eval { $coderef->($args) };
  47. my $error = $@;
  48. if($data) {
  49. $ret->{'data'} = $data;
  50. $ret->{'result'} = 1;
  51. } else {
  52. $ret->{'result'} = 0;
  53. $ret->{'error'} = $error;
  54. }
  55. } elsif( !$coderef ) {
  56. $ret->{'error'} = "No such function '$args->{'function'}' in $namespace";
  57. $ret->{'result'} = 0;
  58. } else {
  59. $ret->{'error'} = $err;
  60. $ret->{'result'} = 0;
  61. }
  62. return emit($ret);
  63. }
  64. sub emit {
  65. print "Content-type: application/json\r\n\r\n";
  66. print JSON::XS::encode_json($_[0]);
  67. return 0;
  68. }
  69. 1;