Utils.pm 2.2 KB

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