Utils.pm 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package Trog::Utils;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures state};
  6. use UUID;
  7. use HTTP::Tiny::UNIX();
  8. use Plack::MIME;
  9. use Mojo::File;
  10. use File::LibMagic;
  11. use Ref::Util qw{is_hashref};
  12. use Trog::Log qw{WARN};
  13. use Trog::Config();
  14. # Deal with Params which may or may not be arrays
  15. sub coerce_array ($param) {
  16. my $p = $param || [];
  17. $p = [$param] if $param && ( ref $param ne 'ARRAY' );
  18. return $p;
  19. }
  20. sub strip_and_trunc ($s) {
  21. return unless $s;
  22. $s =~ s/<[^>]*>//g;
  23. return substr $s, 0, 280;
  24. }
  25. # Instruct the parent to restart. Normally this is HUP, but nginx-unit decides to be special.
  26. # Don't do anything if running NOHUP=1, which is useful when doing bulk operations
  27. sub restart_parent {
  28. return if $ENV{NOHUP};
  29. if ( $ENV{PSGI_ENGINE} && $ENV{PSGI_ENGINE} eq 'nginx-unit' ) {
  30. my $conf = Trog::Config->get();
  31. my $nginx_socket = $conf->param('nginx-unit.socket');
  32. my $client = HTTP::Tiny::UNIX->new();
  33. my $res = $client->request( 'GET', "http:$nginx_socket//control/applications/tcms/restart" );
  34. WARN("could not reload application (got $res->{status} from nginx-unit)!") unless $res->{status} == 200;
  35. return 1;
  36. }
  37. my $parent = getppid;
  38. kill 'HUP', $parent;
  39. }
  40. sub uuid {
  41. return UUID::uuid();
  42. }
  43. #Stuff that isn't in upstream finders
  44. my %extra_types = (
  45. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  46. );
  47. sub mime_type ($file) {
  48. # Use libmagic and if that doesn't work try guessing based on extension.
  49. my $mt;
  50. my $mf = Mojo::File->new($file);
  51. my $ext = '.' . $mf->extname();
  52. $mt = Plack::MIME->mime_type($ext) if $ext;
  53. $mt ||= $extra_types{$ext} if exists $extra_types{$ext};
  54. return $mt if $mt;
  55. # If all else fails, time for libmagic
  56. state $magic = File::LibMagic->new;
  57. my $maybe_ct = $magic->info_from_filename($file);
  58. $mt = $maybe_ct->{mime_type} if ( is_hashref($maybe_ct) && $maybe_ct->{mime_type} );
  59. return $mt;
  60. }
  61. 1;