Utils.pm 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. sub uuid {
  26. return UUID::uuid();
  27. }
  28. #Stuff that isn't in upstream finders
  29. my %extra_types = (
  30. '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  31. );
  32. sub mime_type ($file) {
  33. # Use libmagic and if that doesn't work try guessing based on extension.
  34. my $mt;
  35. my $mf = Mojo::File->new($file);
  36. my $ext = '.' . $mf->extname();
  37. $mt = Plack::MIME->mime_type($ext) if $ext;
  38. $mt ||= $extra_types{$ext} if exists $extra_types{$ext};
  39. return $mt if $mt;
  40. # If all else fails, time for libmagic
  41. state $magic = File::LibMagic->new;
  42. my $maybe_ct = $magic->info_from_filename($file);
  43. $mt = $maybe_ct->{mime_type} if ( is_hashref($maybe_ct) && $maybe_ct->{mime_type} );
  44. return $mt;
  45. }
  46. 1;