zeroclickinfo-goodies/lib/DDG/Goodie/CanadaPost.pm

80 lines
2.2 KiB
Perl
Raw Normal View History

package DDG::Goodie::CanadaPost;
# ABSTRACT: Track a package through Canada Post
use strict;
use DDG::Goodie;
zci is_cached => 1;
zci answer_type => "canadapost";
2013-02-22 07:37:05 -08:00
# Regex for Canada Post.
my $capost_qr = qr/ca(?:nada|)post(?:es|)/io;
2013-02-22 14:42:27 -08:00
triggers query_nowhitespace_nodash => qr/
(?:^$capost_qr.*?([\d]{9,})$)|
(?:^([\d]{9,}).*?$capost_qr$)|
(?:^([A-Z]{2}[\d]{9}CA)$)
2013-02-22 07:37:05 -08:00
/xio;
# Canada post package tracking.
# See http://en.wikipedia.org/wiki/Canada_Post
2013-02-22 14:42:27 -08:00
# See http://www.canadapost.ca/cpotools/apps/track/personal/usingTrack?execution=e3s1#Formats
handle query_nowhitespace_nodash => sub {
my %capost_checksum = (
'1' => 8,
'2' => 6,
'3' => 4,
'4' => 2,
'5' => 3,
'6' => 5,
'7' => 9,
'8' => 7,
);
2013-02-22 07:37:05 -08:00
# If a Canada Post package number (2 for exclusively).
my $is_capost = 0;
# Tracking number.
my $package_number = '';
2014-12-29 18:48:22 -08:00
# Exclusive trigger.
2013-02-22 07:37:05 -08:00
if ($1 || $2) {
$package_number = $1 || $2;
$is_capost = 2;
# No exclusive trigger, do checksum.
} elsif ($3) {
$package_number = uc $3;
my $checksum = 0;
2013-02-22 14:42:27 -08:00
my @chars = split(//, $package_number);
2013-02-22 07:37:05 -08:00
my $length = scalar(@chars);
my $char_count = 0;
my $sum = 0;
2014-10-28 11:36:15 -07:00
2013-02-22 07:37:05 -08:00
foreach my $char (@chars) {
2014-10-28 11:36:15 -07:00
$char_count++;
2013-02-22 07:37:05 -08:00
next if $char_count < 3;
my $weight = $capost_checksum{$char_count - 2};
2013-02-22 07:37:05 -08:00
$sum += $char * $weight;
last if $char_count == 10;
}
2013-02-22 14:42:27 -08:00
$checksum = 11 - ($sum % 11);
2013-02-22 07:37:05 -08:00
$checksum = 0 if $checksum == 10;
$checksum = 5 if $checksum == 11;
2013-02-22 14:42:27 -08:00
if ($checksum eq $chars[10]) {
2013-02-22 07:37:05 -08:00
$is_capost = 2;
}
}
2013-02-22 07:37:05 -08:00
# Only exclusive results right now for CA Post.
if ($is_capost == 2) {
2013-02-22 14:42:27 -08:00
return heading => 'Canada Post Shipment Tracking', html => qq(Track this shipment at <a href="http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=$package_number">Canada Post</a>.);
2013-02-22 07:37:05 -08:00
}
return;
};
1;