repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/transactional_timeline_test.rb | test/transactional_timeline_test.rb | require File.dirname(__FILE__) + '/helper'
class TransactionalTimelineTest < Test::Unit::TestCase
multiple_contexts "authenticated_using_oauth_context", "authenticated_using_api_key_context" do
setup do
@client_id = "87y8d7qyw8d7yq8w7ydwqwd"
@message_id = "ddc697c7-0788-4df3-a71a-a7cb935f00bd"
@before_id = 'e2e270e6-fbce-11e4-97fc-a7cf717ca157'
@after_id = 'e96fc6ca-fbce-11e4-949f-c3ccd6a68863'
@smart_email_id = 'bb4a6ebb-663d-42a0-bdbe-60512cf30a01'
end
should "get statistics with the default parameters" do
stub_get(@auth, "transactional/statistics", "tx_statistics_classic.json")
response = CreateSend::Transactional::Timeline.new(@auth).statistics
response.Sent.should be == 1000
response.Opened.should be == 300
end
should "get statistics filtered by date and classic group" do
stub_get(@auth, "transactional/statistics?from=2015-01-01&to=2015-06-30&timezone=client&group=Password%20Reset", "tx_statistics_classic.json")
response = CreateSend::Transactional::Timeline.new(@auth).statistics(
"from" => "2015-01-01",
"to" => "2015-06-30",
"timezone" => "client",
"group" => "Password Reset"
)
response.Query.TimeZone.should be == "(GMT+10:00) Canberra, Melbourne, Sydney"
response.Query.Group.should be == "Password Reset"
response.Sent.should be == 1000
end
should "get statistics filtered by date and smart email" do
stub_get(@auth, "transactional/statistics?from=2015-01-01&to=2015-06-30&timezone=utc&smartEmailID=#{@smart_email_id}", "tx_statistics_smart.json")
response = CreateSend::Transactional::Timeline.new(@auth).statistics(
"from" => "2015-01-01",
"to" => "2015-06-30",
"timezone" => "utc",
"smartEmailID" => "bb4a6ebb-663d-42a0-bdbe-60512cf30a01"
)
response.Query.TimeZone.should be == "UTC"
response.Query.SmartEmailID.should be == "bb4a6ebb-663d-42a0-bdbe-60512cf30a01"
response.Sent.should be == 1000
end
should "get the message timeline with default parameters" do
stub_get(@auth, "transactional/messages", "tx_messages.json")
response = CreateSend::Transactional::Timeline.new(@auth).messages
response.length.should be == 3
response[0].MessageID.should be == "ddc697c7-0788-4df3-a71a-a7cb935f00bd"
response[0].Status.should be == "Delivered"
end
should "get the message timeline for a smart email" do
stub_get(@auth, "transactional/messages?status=all&count=200&sentBeforeID=#{@before_id}&sentAfterID=#{@after_id}&smartEmailID=#{@smart_email_id}&clientID=#{@client_id}", "tx_messages_smart.json")
response = CreateSend::Transactional::Timeline.new(@auth).messages(
"status" => 'all',
"count" => 200,
"sentBeforeID" => @before_id,
"sentAfterID" => @after_id,
"smartEmailID" => @smart_email_id,
"clientID" => @client_id
)
response.length.should be == 1
response[0].MessageID.should be == "ddc697c7-0788-4df3-a71a-a7cb935f00bd"
response[0].Status.should be == "Delivered"
end
should "get the message timeline for a classic group" do
stub_get(@auth, "transactional/messages?status=all&count=200&sentBeforeID=#{@before_id}&sentAfterID=#{@after_id}&group=Password%20Reset&clientID=#{@client_id}", "tx_messages_classic.json")
response = CreateSend::Transactional::Timeline.new(@auth).messages(
"status" => 'all',
"count" => 200,
"sentBeforeID" => @before_id,
"sentAfterID" => @after_id,
"group" => 'Password Reset',
"clientID" => @client_id
)
response.length.should be == 1
response[0].Group.should be == "Password Reset"
response[0].Status.should be == "Delivered"
end
should "get the message details" do
stub_get(@auth, "transactional/messages/#{@message_id}", "tx_message_details.json")
response = CreateSend::Transactional::Timeline.new(@auth).details(@message_id)
response.TotalOpens.should be == 1
response.TotalClicks.should be == 1
end
should "get the message details with statistics" do
stub_get(@auth, "transactional/messages/#{@message_id}?statistics=true", "tx_message_details_with_statistics.json")
response = CreateSend::Transactional::Timeline.new(@auth).details(@message_id, :statistics => true)
response.Opens.length.should be == 1
response.Clicks.length.should be == 1
end
should "resend a message" do
stub_post(@auth, "transactional/messages/#{@message_id}/resend", "tx_send_single.json")
response = CreateSend::Transactional::Timeline.new(@auth).resend(@message_id)
response.length.should be == 1
response[0].MessageID.should be == "0cfe150d-d507-11e4-84a7-c31e5b59881d"
response[0].Recipient.should be == "\"Bob Sacamano\" <bob@example.com>"
response[0].Status.should be == "Received"
end
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/transactional_classic_email_test.rb | test/transactional_classic_email_test.rb | require File.dirname(__FILE__) + '/helper'
class TransactionalClassicEmailTest < Test::Unit::TestCase
multiple_contexts "authenticated_using_oauth_context", "authenticated_using_api_key_context" do
setup do
@client_id = "87y8d7qyw8d7yq8w7ydwqwd"
@email = CreateSend::Transactional::ClassicEmail.new @auth, @client_id
end
should "send classic email to one recipient" do
stub_post(@auth, "transactional/classicemail/send", "tx_send_single.json")
email = {
"From" => "George <george@example.com>",
"Subject" => "Thanks for signing up to Vandelay Industries",
"To" => "Bob Sacamano <bob@example.com>",
"HTML" => "<h1>Welcome</h1><a href='http://example.com/'>Click here</a>",
"Group" => 'Ruby test group'
}
response = CreateSend::Transactional::ClassicEmail.new(@auth).send(email)
response.length.should be == 1
response[0].Recipient.should be == "\"Bob Sacamano\" <bob@example.com>"
end
should "send classic email to with all the options" do
stub_post(@auth, "transactional/classicemail/send", "tx_send_multiple.json")
email = {
"From" => "T-Bone <tbone@example.com>",
"ReplyTo" => "george@example.com",
"Subject" => "Thanks for signing up to Vandelay Industries",
"To" => [
"Bob Sacamano <bob@example.com>",
"Newman <newman@example.com>",
],
"CC" => [],
"BCC" => [],
"HTML" => "<h1>Welcome</h1><a href='http://example.com/'>Click here</a>",
"Text" => "Instead of using the auto-generated text from the HTML, you can supply your own.",
"Attachments" => [
"Name" => "filename.gif",
"Type" => "image/gif",
"Content" => "R0lGODlhIAAgAKIAAP8AAJmZADNmAMzMAP//AAAAAP///wAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMwMTQgNzkuMTU2Nzk3LCAyMDE0LzA4LzIwLTA5OjUzOjAyICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxNCAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDowNzZGOUNGOUVDRDIxMUU0ODM2RjhGMjNCMTcxN0I2RiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDowNzZGOUNGQUVDRDIxMUU0ODM2RjhGMjNCMTcxN0I2RiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjA3NkY5Q0Y3RUNEMjExRTQ4MzZGOEYyM0IxNzE3QjZGIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjA3NkY5Q0Y4RUNEMjExRTQ4MzZGOEYyM0IxNzE3QjZGIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+Af/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIBwYFBAMCAQAAIfkEAAAAAAAsAAAAACAAIAAAA5loutz+MKpSpIWU3r1KCBW3eYQmWgWhmiemEgPbNqk6xDOd1XGYV77UzTfbTWC4nAHYQRKLu1VSuXxlpsodAFDAZrfcIbXDFXqhNacoQ3vZpuxHSJZ2zufyTqcunugdd00vQ0F4chQCAgYCaTcxiYuMMhGJFG89kYpFl5MzkoRPnpJskFSaDqctRoBxHEQsdGs0f7Qjq3utDwkAOw=="
],
"Group" => "Ruby test group",
"AddRecipientsToListID" => "6d0366fcee146ab9bdaf3247446bbfdd"
}
response = CreateSend::Transactional::ClassicEmail.new(@auth).send(email)
response.length.should be == 2
response[1].Recipient.should be == "\"Newman\" <newman@example.com>"
end
should "get the list of classic groups" do
stub_get(@auth, "transactional/classicemail/groups", "tx_classicemail_groups.json")
response = CreateSend::Transactional::ClassicEmail.new(@auth).groups
response.length.should be == 3
response[0].Group.should be == "Password Reset"
end
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/subscriber_test.rb | test/subscriber_test.rb | require File.dirname(__FILE__) + '/helper'
class SubscriberTest < Test::Unit::TestCase
multiple_contexts "authenticated_using_oauth_context", "authenticated_using_api_key_context" do
setup do
@list_id = "d98h2938d9283d982u3d98u88"
@subscriber = CreateSend::Subscriber.new @auth, @list_id, "subscriber@example.com"
end
should "get a subscriber by list id and email address" do
email = "subscriber@example.com"
stub_get(@auth, "subscribers/#{@list_id}.json?email=#{ERB::Util.url_encode(email)}&includetrackingpreference=false", "subscriber_details.json")
subscriber = CreateSend::Subscriber.get @auth, @list_id, email
subscriber.EmailAddress.should be == email
subscriber.Name.should be == "Subscriber One"
subscriber.Date.should be == "2010-10-25 10:28:00"
subscriber.MobileNumber.should be == "+61423153526"
subscriber.ListJoinedDate.should be == "2010-10-25 10:28:00"
subscriber.State.should be == "Active"
subscriber.CustomFields.size.should be == 3
subscriber.CustomFields.first.Key.should be == 'website'
subscriber.CustomFields.first.Value.should be == 'http://example.com'
subscriber.ReadsEmailWith.should be == "Gmail"
end
should "get a subscriber with track and sms preference information" do
email = "subscriber@example.com"
stub_get(@auth, "subscribers/#{@list_id}.json?email=#{ERB::Util.url_encode(email)}&includetrackingpreference=true", "subscriber_details_with_track_and_sms_pref.json")
subscriber = CreateSend::Subscriber.get @auth, @list_id, email, true
subscriber.EmailAddress.should be == email
subscriber.Name.should be == "Subscriber One"
subscriber.MobileNumber.should be == "+61423153526"
subscriber.ConsentToTrack.should be == "Yes"
subscriber.ConsentToSendSms.should be == "No"
end
should "add a subscriber without custom fields" do
stub_post(@auth, "subscribers/#{@list_id}.json", "add_subscriber.json")
email_address = CreateSend::Subscriber.add @auth, @list_id, "subscriber@example.com", "Subscriber", [], true, "Yes"
email_address.should be == "subscriber@example.com"
end
should "add a subscriber with custom fields" do
stub_post(@auth, "subscribers/#{@list_id}.json", "add_subscriber.json")
custom_fields = [ { :Key => 'website', :Value => 'http://example.com/' } ]
email_address = CreateSend::Subscriber.add @auth, @list_id, "subscriber@example.com", "Subscriber", custom_fields, true, "Yes"
email_address.should be == "subscriber@example.com"
end
should "add a subscriber with custom fields including multi-option fields" do
stub_post(@auth, "subscribers/#{@list_id}.json", "add_subscriber.json")
custom_fields = [ { :Key => 'multioptionselectone', :Value => 'myoption' },
{ :Key => 'multioptionselectmany', :Value => 'firstoption' },
{ :Key => 'multioptionselectmany', :Value => 'secondoption' } ]
email_address = CreateSend::Subscriber.add @auth, @list_id, "subscriber@example.com", "Subscriber", custom_fields, true, "Yes"
email_address.should be == "subscriber@example.com"
end
should "update a subscriber with custom fields" do
email = "subscriber@example.com"
new_email = "new_email_address@example.com"
stub_put(@auth, "subscribers/#{@list_id}.json?email=#{ERB::Util.url_encode(email)}", nil)
custom_fields = [ { :Key => 'website', :Value => 'http://example.com/' } ]
@subscriber.update new_email, "Subscriber", custom_fields, true, "Yes"
@subscriber.email_address.should be == new_email
end
should "update a subscriber with custom fields including the clear option" do
email = "subscriber@example.com"
new_email = "new_email_address@example.com"
stub_put(@auth, "subscribers/#{@list_id}.json?email=#{ERB::Util.url_encode(email)}", nil)
custom_fields = [ { :Key => 'website', :Value => '', :Clear => true } ]
@subscriber.update new_email, "Subscriber", custom_fields, true, "No"
@subscriber.email_address.should be == new_email
end
should "import many subscribers at once" do
stub_post(@auth, "subscribers/#{@list_id}/import.json", "import_subscribers.json")
subscribers = [
{ :EmailAddress => "example+1@example.com", :Name => "Example One" },
{ :EmailAddress => "example+2@example.com", :Name => "Example Two" },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three" },
]
import_result = CreateSend::Subscriber.import @auth, @list_id, subscribers, true
import_result.FailureDetails.size.should be == 0
import_result.TotalUniqueEmailsSubmitted.should be == 3
import_result.TotalExistingSubscribers.should be == 0
import_result.TotalNewSubscribers.should be == 3
import_result.DuplicateEmailsInSubmission.size.should be == 0
end
should "import many subscribers at once, and start subscription-based autoresponders" do
stub_post(@auth, "subscribers/#{@list_id}/import.json", "import_subscribers.json")
subscribers = [
{ :EmailAddress => "example+1@example.com", :Name => "Example One" },
{ :EmailAddress => "example+2@example.com", :Name => "Example Two" },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three" },
]
import_result = CreateSend::Subscriber.import @auth, @list_id, subscribers, true, true
import_result.FailureDetails.size.should be == 0
import_result.TotalUniqueEmailsSubmitted.should be == 3
import_result.TotalExistingSubscribers.should be == 0
import_result.TotalNewSubscribers.should be == 3
import_result.DuplicateEmailsInSubmission.size.should be == 0
end
should "import many subscribers at once with custom fields, including the clear option" do
stub_post(@auth, "subscribers/#{@list_id}/import.json", "import_subscribers.json")
subscribers = [
{ :EmailAddress => "example+1@example.com", :Name => "Example One", :CustomFields => [ { :Key => 'website', :Value => '', :Clear => true } ] },
{ :EmailAddress => "example+2@example.com", :Name => "Example Two", :CustomFields => [ { :Key => 'website', :Value => '', :Clear => false } ] },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three", :CustomFields => [ { :Key => 'website', :Value => '', :Clear => false } ] },
]
import_result = CreateSend::Subscriber.import @auth, @list_id, subscribers, true
import_result.FailureDetails.size.should be == 0
import_result.TotalUniqueEmailsSubmitted.should be == 3
import_result.TotalExistingSubscribers.should be == 0
import_result.TotalNewSubscribers.should be == 3
import_result.DuplicateEmailsInSubmission.size.should be == 0
end
should "import many subscribers at once with partial success" do
# Stub request with 400 Bad Request as the expected response status
stub_post(@auth, "subscribers/#{@list_id}/import.json", "import_subscribers_partial_success.json", 400)
subscribers = [
{ :EmailAddress => "example+1@example", :Name => "Example One" },
{ :EmailAddress => "example+2@example.com", :Name => "Example Two" },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three" },
]
import_result = CreateSend::Subscriber.import @auth, @list_id, subscribers, true
import_result.FailureDetails.size.should be == 1
import_result.FailureDetails.first.EmailAddress.should be == "example+1@example"
import_result.FailureDetails.first.Code.should be == 1
import_result.FailureDetails.first.Message.should be == "Invalid Email Address"
import_result.TotalUniqueEmailsSubmitted.should be == 3
import_result.TotalExistingSubscribers.should be == 2
import_result.TotalNewSubscribers.should be == 0
import_result.DuplicateEmailsInSubmission.size.should be == 0
end
should "raise a BadRequest error if the import _completely_ fails because of a bad request" do
# Stub request with 400 Bad Request as the expected response status
stub_post(@auth, "subscribers/#{@list_id}/import.json", "custom_api_error.json", 400)
subscribers = [
{ :EmailAddress => "example+1@example", :Name => "Example One" },
{ :EmailAddress => "example+2@example.com", :Name => "Example Two" },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three" },
]
lambda { CreateSend::Subscriber.import @auth, @list_id, subscribers,
true }.should raise_error(CreateSend::BadRequest)
end
should "unsubscribe a subscriber" do
stub_post(@auth, "subscribers/#{@subscriber.list_id}/unsubscribe.json", nil)
@subscriber.unsubscribe
end
should "get a subscriber's history" do
stub_get(@auth, "subscribers/#{@subscriber.list_id}/history.json?email=#{ERB::Util.url_encode(@subscriber.email_address)}", "subscriber_history.json")
history = @subscriber.history
history.size.should be == 1
history.first.Name.should be == "Campaign One"
history.first.Type.should be == "Campaign"
history.first.ID.should be == "fc0ce7105baeaf97f47c99be31d02a91"
history.first.Actions.size.should be == 6
history.first.Actions.first.Event.should be == "Open"
history.first.Actions.first.Date.should be == "2010-10-12 13:18:00"
history.first.Actions.first.IPAddress.should be == "192.168.126.87"
history.first.Actions.first.Detail.should be == ""
end
should "delete a subscriber" do
stub_delete(@auth, "subscribers/#{@subscriber.list_id}.json?email=#{ERB::Util.url_encode(@subscriber.email_address)}", nil)
@subscriber.delete
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/client_test.rb | test/client_test.rb | require File.dirname(__FILE__) + '/helper'
class ClientTest < Test::Unit::TestCase
multiple_contexts "authenticated_using_oauth_context", "authenticated_using_api_key_context" do
setup do
@client = CreateSend::Client.new(@auth, '321iuhiuhi1u23hi2u3')
@client.client_id.should be == '321iuhiuhi1u23hi2u3'
end
should "create a client" do
stub_post(@auth, "clients.json", "create_client.json")
client_id = CreateSend::Client.create @auth, "Client Company Name", "(GMT+10:00) Canberra, Melbourne, Sydney", "Australia"
client_id.parsed_response.should be == "32a381c49a2df99f1d0c6f3c112352b9"
end
should "get details of a client" do
stub_get(@auth, "clients/#{@client.client_id}.json", "client_details.json")
cl = @client.details
cl.ApiKey.should be == "639d8cc27198202f5fe6037a8b17a29a59984b86d3289bc9"
cl.BasicDetails.ClientID.should be == "4a397ccaaa55eb4e6aa1221e1e2d7122"
cl.BasicDetails.ContactName.should be == "Client One (contact)"
cl.AccessDetails.Username.should be == "clientone"
cl.AccessDetails.AccessLevel.should be == 23
cl.BillingDetails.MonthlyScheme.should be == "Basic"
cl.BillingDetails.Credits.should be == 500
end
should "get all campaigns" do
stub_get(@auth, "clients/#{@client.client_id}/campaigns.json?page=1&pagesize=1000&orderdirection=desc&sentfromdate=&senttodate=&tags=", "campaigns.json")
campaigns = @client.campaigns
campaigns.Results.size.should be == 2
campaigns.ResultsOrderedBy be == 'sentdate'
campaigns.OrderDirection be == 'desc'
campaigns.PageNumber be == 1
campaigns.PageSize be == 1000
campaigns.RecordsOnThisPage be == 2
campaigns.TotalNumberOfRecords be == 2
campaigns.NumberOfPages be == 1
campaign = campaigns.Results.first
campaign.CampaignID.should be == 'fc0ce7105baeaf97f47c99be31d02a91'
campaign.WebVersionURL.should be == 'http://createsend.com/t/r-765E86829575EE2C'
campaign.WebVersionTextURL.should be == 'http://createsend.com/t/r-765E86829575EE2C/t'
campaign.Subject.should be == 'Campaign One'
campaign.Name.should be == 'Campaign One'
campaign.SentDate.should be == '2010-10-12 12:58:00'
campaign.TotalRecipients.should be == 2245
campaign.FromName.should be == 'My Name'
campaign.FromEmail.should be == 'myemail@example.com'
campaign.ReplyTo.should be == 'myemail@example.com'
campaign.Tags.should be == []
end
should "get scheduled campaigns" do
stub_get(@auth, "clients/#{@client.client_id}/scheduled.json", "scheduled_campaigns.json")
campaigns = @client.scheduled
campaigns.size.should be == 2
campaign = campaigns.first
campaign.DateScheduled.should be == "2011-05-25 10:40:00"
campaign.ScheduledTimeZone.should be == "(GMT+10:00) Canberra, Melbourne, Sydney"
campaign.CampaignID.should be == "827dbbd2161ea9989fa11ad562c66937"
campaign.Name.should be == "Magic Issue One"
campaign.Subject.should be == "Magic Issue One"
campaign.DateCreated.should be == "2011-05-24 10:37:00"
campaign.PreviewURL.should be == "http://createsend.com/t/r-DD543521A87C9B8B"
campaign.PreviewTextURL.should be == "http://createsend.com/t/r-DD543521A87C9B8B/t"
campaign.FromName.should be == 'My Name'
campaign.FromEmail.should be == 'myemail@example.com'
campaign.ReplyTo.should be == 'myemail@example.com'
campaign.Tags.should be == ['tagexample']
end
should "get all drafts" do
stub_get(@auth, "clients/#{@client.client_id}/drafts.json", "drafts.json")
drafts = @client.drafts
drafts.size.should be == 2
draft = drafts.first
draft.CampaignID.should be == '7c7424792065d92627139208c8c01db1'
draft.Name.should be == 'Draft One'
draft.Subject.should be == 'Draft One'
draft.DateCreated.should be == '2010-08-19 16:08:00'
draft.PreviewURL.should be == 'http://createsend.com/t/r-E97A7BB2E6983DA1'
draft.PreviewTextURL.should be == 'http://createsend.com/t/r-E97A7BB2E6983DA1/t'
draft.FromName.should be == 'My Name'
draft.FromEmail.should be == 'myemail@example.com'
draft.ReplyTo.should be == 'myemail@example.com'
draft.Tags.should be == ['tagexample']
end
should "get all client tags" do
stub_get(@auth, "clients/#{@client.client_id}/tags.json", "tags.json")
tags = @client.tags
tags.size.should be == 2
tag = tags.first
tag.Name.should be == 'Tag One'
tag.NumberOfCampaigns.should be == '120'
end
should "get all lists" do
stub_get(@auth, "clients/#{@client.client_id}/lists.json", "lists.json")
lists = @client.lists
lists.size.should be == 2
lists.first.ListID.should be == 'a58ee1d3039b8bec838e6d1482a8a965'
lists.first.Name.should be == 'List One'
end
should "get all lists to which a subscriber with a particular email address belongs" do
email = "valid@example.com"
stub_get(@auth, "clients/#{@client.client_id}/listsforemail.json?email=#{ERB::Util.url_encode(email)}", "listsforemail.json")
lists = @client.lists_for_email(email)
lists.size.should be == 2
lists.first.ListID.should be == 'ab4a2b57c7c8f1ba62f898a1af1a575b'
lists.first.ListName.should be == 'List Number One'
lists.first.SubscriberState.should be == 'Active'
lists.first.DateSubscriberAdded.should be == '2012-08-20 22:32:00'
end
should "get all segments for a client" do
stub_get(@auth, "clients/#{@client.client_id}/segments.json", "segments.json")
segments = @client.segments
segments.size.should be == 2
segments.first.ListID.should be == 'a58ee1d3039b8bec838e6d1482a8a965'
segments.first.SegmentID.should be == '46aa5e01fd43381863d4e42cf277d3a9'
segments.first.Title.should be == 'Segment One'
end
should "get suppression list" do
stub_get(@auth, "clients/#{@client.client_id}/suppressionlist.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc", "suppressionlist.json")
res = @client.suppressionlist
res.ResultsOrderedBy.should be == "email"
res.OrderDirection.should be == "asc"
res.PageNumber.should be == 1
res.PageSize.should be == 1000
res.RecordsOnThisPage.should be == 5
res.TotalNumberOfRecords.should be == 5
res.NumberOfPages.should be == 1
res.Results.size.should be == 5
res.Results.first.SuppressionReason.should be == "Unsubscribed"
res.Results.first.EmailAddress.should be == "example+1@example.com"
res.Results.first.Date.should be == "2010-10-26 10:55:31"
res.Results.first.State.should be == "Suppressed"
end
should "suppress a single email address" do
email = "example@example.com"
stub_post(@auth, "clients/#{@client.client_id}/suppress.json", nil)
@client.suppress email
end
should "suppress multiple email address" do
stub_post(@auth, "clients/#{@client.client_id}/suppress.json", nil)
@client.suppress [ "one@example.com", "two@example.com" ]
end
should "unsuppress an email address" do
email = "example@example.com"
stub_put(@auth, "clients/#{@client.client_id}/unsuppress.json?email=#{ERB::Util.url_encode(email)}", nil)
@client.unsuppress email
end
should "get all people" do
stub_get(@auth, "clients/#{@client.client_id}/people.json", "people.json")
people = @client.people
people.size.should be == 2
people.first.EmailAddress.should be == "person1@blackhole.com"
people.first.Name.should be == "Person One"
people.first.Status.should be == "Active"
people.first.AccessLevel.should be == 31
end
should "get all templates" do
stub_get(@auth, "clients/#{@client.client_id}/templates.json", "templates.json")
templates = @client.templates
templates.size.should be == 2
templates.first.TemplateID.should be == '5cac213cf061dd4e008de5a82b7a3621'
templates.first.Name.should be == 'Template One'
end
should "set primary contact" do
email = 'person@blackhole.com'
stub_put(@auth, "clients/#{@client.client_id}/primarycontact.json?email=#{ERB::Util.url_encode(email)}", 'client_set_primary_contact.json')
result = @client.set_primary_contact email
result.EmailAddress.should be == email
end
should "get primary contact" do
stub_get(@auth, "clients/#{@client.client_id}/primarycontact.json", 'client_get_primary_contact.json')
result = @client.get_primary_contact
result.EmailAddress.should be == 'person@blackhole.com'
end
should "set basics" do
stub_put(@auth, "clients/#{@client.client_id}/setbasics.json", nil)
@client.set_basics "Client Company Name", "(GMT+10:00) Canberra, Melbourne, Sydney", "Australia"
end
should "set payg billing" do
stub_put(@auth, "clients/#{@client.client_id}/setpaygbilling.json", nil)
@client.set_payg_billing "CAD", true, true, 150
end
should "set monthly billing (implicit)" do
stub_put(@auth, "clients/#{@client.client_id}/setmonthlybilling.json", nil)
@client.set_monthly_billing "CAD", true, 150
request = FakeWeb.last_request.body
request.include?("\"Currency\":\"CAD\"").should be == true
request.include?("\"ClientPays\":true").should be == true
request.include?("\"MarkupPercentage\":150").should be == true
request.include?("\"MonthlyScheme\":null").should be == true
end
should "set monthly billing (basic)" do
stub_put(@auth, "clients/#{@client.client_id}/setmonthlybilling.json", nil)
@client.set_monthly_billing "CAD", true, 150, "Basic"
request = FakeWeb.last_request.body
request.include?("\"Currency\":\"CAD\"").should be == true
request.include?("\"ClientPays\":true").should be == true
request.include?("\"MarkupPercentage\":150").should be == true
request.include?("\"MonthlyScheme\":\"Basic\"").should be == true
end
should "set monthly billing (unlimited)" do
stub_put(@auth, "clients/#{@client.client_id}/setmonthlybilling.json", nil)
@client.set_monthly_billing "CAD", false, 120, "Unlimited"
request = FakeWeb.last_request.body
request.include?("\"Currency\":\"CAD\"").should be == true
request.include?("\"ClientPays\":false").should be == true
request.include?("\"MarkupPercentage\":120").should be == true
request.include?("\"MonthlyScheme\":\"Unlimited\"").should be == true
end
should "transfer credits to a client" do
stub_post(@auth, "clients/#{@client.client_id}/credits.json", "transfer_credits.json")
result = @client.transfer_credits 200, false
result.AccountCredits.should be == 800
result.ClientCredits.should be == 200
end
should "delete a client" do
stub_delete(@auth, "clients/#{@client.client_id}.json", nil)
@client.delete
end
should "get all journeys" do
stub_get(@auth, "clients/#{@client.client_id}/journeys.json", "journeys.json")
lists = @client.journeys
lists.size.should be == 3
lists.first.ListID.should be == 'a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a'
lists.first.Name.should be == 'Journey One'
lists.first.Status.should be == 'Not started'
end
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/segment_test.rb | test/segment_test.rb | require File.dirname(__FILE__) + '/helper'
class SegmentTest < Test::Unit::TestCase
multiple_contexts "authenticated_using_oauth_context", "authenticated_using_api_key_context" do
setup do
@segment = CreateSend::Segment.new @auth, '98y2e98y289dh89h938389'
end
should "create a new segment" do
list_id = "2983492834987394879837498"
rule_groups = [ { :Rules => [ { :RuleType => "EmailAddress", :Clause => "CONTAINS example.com" } ] } ]
stub_post(@auth, "segments/#{list_id}.json", "create_segment.json")
res = CreateSend::Segment.create @auth, list_id, "new segment title", rule_groups
res.should be == "0246c2aea610a3545d9780bf6ab89006"
end
should "update a segment" do
rules = [ { :Rules => [ { :RuleType => "Name", :Clause => "PROVIDED" } ] } ]
stub_put(@auth, "segments/#{@segment.segment_id}.json", nil)
@segment.update "new title for segment", rules
end
should "add a rule group to a segment" do
rule_group = [ { :RuleType => "EmailAddress", :Clause => "CONTAINS @hello.com" } ]
stub_post(@auth, "segments/#{@segment.segment_id}/rules.json", nil)
@segment.add_rule_group rule_group
end
should "get the active subscribers for a particular segment in the list" do
min_date = "2010-01-01"
stub_get(@auth, "segments/#{@segment.segment_id}/active.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}&includetrackingpreference=false",
"segment_subscribers.json")
res = @segment.subscribers min_date
res.ResultsOrderedBy.should be == "email"
res.OrderDirection.should be == "asc"
res.PageNumber.should be == 1
res.PageSize.should be == 1000
res.RecordsOnThisPage.should be == 2
res.TotalNumberOfRecords.should be == 2
res.NumberOfPages.should be == 1
res.Results.size.should be == 2
res.Results.first.EmailAddress.should be == "personone@example.com"
res.Results.first.Name.should be == "Person One"
res.Results.first.Date.should be == "2010-10-27 13:13:00"
res.Results.first.ListJoinedDate.should be == "2010-10-27 13:13:00"
res.Results.first.State.should be == "Active"
res.Results.first.CustomFields.should be == []
end
should "delete a segment" do
stub_delete(@auth, "segments/#{@segment.segment_id}.json", nil)
@segment.delete
end
should "get the details of a segment" do
stub_get(@auth, "segments/#{@segment.segment_id}.json", "segment_details.json")
res = @segment.details
res.ActiveSubscribers.should be == 0
res.RuleGroups.size.should be == 2
res.RuleGroups.first.Rules.size.should be == 1
res.RuleGroups.first.Rules.first.RuleType.should be == "EmailAddress"
res.RuleGroups.first.Rules.first.Clause.should be == "CONTAINS @hello.com"
res.ListID.should be == "2bea949d0bf96148c3e6a209d2e82060"
res.SegmentID.should be == "dba84a225d5ce3d19105d7257baac46f"
res.Title.should be == "My Segment"
end
should "clear a segment's rules" do
stub_delete(@auth, "segments/#{@segment.segment_id}/rules.json", nil)
@segment.clear_rules
end
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/campaign_test.rb | test/campaign_test.rb | require File.dirname(__FILE__) + '/helper'
class CampaignTest < Test::Unit::TestCase
multiple_contexts "authenticated_using_oauth_context", "authenticated_using_api_key_context" do
setup do
@campaign = CreateSend::Campaign.new @auth, '787y87y87y87y87y87y87'
end
should "create a campaign" do
client_id = '87y8d7qyw8d7yq8w7ydwqwd'
stub_post(@auth, "campaigns/#{client_id}.json", "create_campaign.json")
campaign_id = CreateSend::Campaign.create @auth, client_id, "subject", "name", "g'day", "good.day@example.com", "good.day@example.com",
"http://example.com/campaign.html", "http://example.com/campaign.txt", [ '7y12989e82ue98u2e', 'dh9w89q8w98wudwd989' ],
[ 'y78q9w8d9w8ud9q8uw', 'djw98quw9duqw98uwd98' ]
request = FakeWeb.last_request.body
request.include?("\"TextUrl\":\"http://example.com/campaign.txt\"").should be == true
campaign_id.should be == "787y87y87y87y87y87y87"
end
should "create a campaign with a nil text_url param" do
client_id = '87y8d7qyw8d7yq8w7ydwqwd'
stub_post(@auth, "campaigns/#{client_id}.json", "create_campaign.json")
campaign_id = CreateSend::Campaign.create @auth, client_id, "subject", "name", "g'day", "good.day@example.com", "good.day@example.com",
"http://example.com/campaign.html", nil, [ '7y12989e82ue98u2e', 'dh9w89q8w98wudwd989' ],
[ 'y78q9w8d9w8ud9q8uw', 'djw98quw9duqw98uwd98' ]
request = FakeWeb.last_request.body
request.include?("\"TextUrl\":null").should be == true
campaign_id.should be == "787y87y87y87y87y87y87"
end
should "create a campaign from a template" do
template_content = {
:Singlelines => [
{
:Content => "This is a heading",
:Href => "http://example.com/"
}
],
:Multilines => [
{
:Content => "<p>This is example</p><p>multiline \
<a href=\"http://example.com\">content</a>...</p>"
}
],
:Images => [
{
:Content => "http://example.com/image.png",
:Alt => "This is alt text for an image",
:Href => "http://example.com/"
}
],
:Repeaters => [
{
:Items => [
{
:Layout => "My layout",
:Singlelines => [
{
:Content => "This is a repeater heading",
:Href => "http://example.com/"
}
],
:Multilines => [
{
:Content => "<p>This is example</p><p>multiline \
<a href=\"http://example.com\">content</a>...</p>"
}
],
:Images => [
{
:Content => "http://example.com/repeater-image.png",
:Alt => "This is alt text for a repeater image",
:Href => "http://example.com/"
}
]
}
]
}
]
}
# template_content as defined above would be used to fill the content of
# a template with markup similar to the following:
#
# <html>
# <head><title>My Template</title></head>
# <body>
# <p><singleline>Enter heading...</singleline></p>
# <div><multiline>Enter description...</multiline></div>
# <img id="header-image" editable="true" width="500" />
# <repeater>
# <layout label="My layout">
# <div class="repeater-item">
# <p><singleline></singleline></p>
# <div><multiline></multiline></div>
# <img editable="true" width="500" />
# </div>
# </layout>
# </repeater>
# <p><unsubscribe>Unsubscribe</unsubscribe></p>
# </body>
# </html>
client_id = '87y8d7qyw8d7yq8w7ydwqwd'
stub_post(@auth, "campaigns/#{client_id}/fromtemplate.json", "create_campaign.json")
campaign_id = CreateSend::Campaign.create_from_template @auth, client_id, "subject", "name", "g'day", "good.day@example.com", "good.day@example.com",
[ '7y12989e82ue98u2e', 'dh9w89q8w98wudwd989' ], [ 'y78q9w8d9w8ud9q8uw', 'djw98quw9duqw98uwd98' ],
"7j8uw98udowy12989e8298u2e", template_content
campaign_id.should be == "787y87y87y87y87y87y87"
end
should "send a preview of a draft campaign to a single recipient" do
stub_post(@auth, "campaigns/#{@campaign.campaign_id}/sendpreview.json", nil)
@campaign.send_preview "test+89898u9@example.com", "random"
end
should "send a preview of a draft campaign to multiple recipients" do
stub_post(@auth, "campaigns/#{@campaign.campaign_id}/sendpreview.json", nil)
@campaign.send_preview [ "test+89898u9@example.com", "test+787y8y7y8@example.com" ], "random"
end
should "send a campaign" do
stub_post(@auth, "campaigns/#{@campaign.campaign_id}/send.json", nil)
@campaign.send "confirmation@example.com"
end
should "unschedule a campaign" do
stub_post(@auth, "campaigns/#{@campaign.campaign_id}/unschedule.json", nil)
@campaign.unschedule
end
should "delete a campaign" do
stub_delete(@auth, "campaigns/#{@campaign.campaign_id}.json", nil)
@campaign.delete
end
should "get the summary for a campaign" do
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/summary.json", "campaign_summary.json")
summary = @campaign.summary
summary.Name.should be == "Campaign Name"
summary.Recipients.should be == 5
summary.TotalOpened.should be == 10
summary.Clicks.should be == 0
summary.Unsubscribed.should be == 0
summary.Bounced.should be == 0
summary.UniqueOpened.should be == 5
summary.Mentions.should be == 23
summary.Forwards.should be == 11
summary.Likes.should be == 32
summary.WebVersionURL.should be == "http://createsend.com/t/r-3A433FC72FFE3B8B"
summary.WebVersionTextURL.should be == "http://createsend.com/t/r-3A433FC72FFE3B8B/t"
summary.WorldviewURL.should be == "http://client.createsend.com/reports/wv/r/3A433FC72FFE3B8B"
summary.SpamComplaints.should be == 23
end
should "get the email client usage for a campaign" do
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/emailclientusage.json", "email_client_usage.json")
ecu = @campaign.email_client_usage
ecu.size.should be == 6
ecu.first.Client.should be == "iOS Devices"
ecu.first.Version.should be == "iPhone"
ecu.first.Percentage.should be == 19.83
ecu.first.Subscribers.should be == 7056
end
should "get the lists and segments for a campaign" do
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/listsandsegments.json", "campaign_listsandsegments.json")
ls = @campaign.lists_and_segments
ls.Lists.size.should be == 1
ls.Segments.size.should be == 1
ls.Lists.first.Name.should be == "List One"
ls.Lists.first.ListID.should be == "a58ee1d3039b8bec838e6d1482a8a965"
ls.Segments.first.Title.should be == "Segment for campaign"
ls.Segments.first.ListID.should be == "2bea949d0bf96148c3e6a209d2e82060"
ls.Segments.first.SegmentID.should be == "dba84a225d5ce3d19105d7257baac46f"
end
should "get the recipients for a campaign" do
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/recipients.json?pagesize=20&orderfield=email&page=1&orderdirection=asc", "campaign_recipients.json")
res = @campaign.recipients page=1, page_size=20
res.ResultsOrderedBy.should be == "email"
res.OrderDirection.should be == "asc"
res.PageNumber.should be == 1
res.PageSize.should be == 20
res.RecordsOnThisPage.should be == 20
res.TotalNumberOfRecords.should be == 2200
res.NumberOfPages.should be == 110
res.Results.size.should be == 20
res.Results.first.EmailAddress.should be == "subs+6g76t7t0@example.com"
res.Results.first.ListID.should be == "a994a3caf1328a16af9a69a730eaa706"
end
should "get the opens for a campaign" do
min_date = "2010-01-01"
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/opens.json?page=1&pagesize=1000&orderfield=date&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}", "campaign_opens.json")
opens = @campaign.opens min_date
opens.Results.size.should be == 5
opens.Results.first.EmailAddress.should be == "subs+6576576576@example.com"
opens.Results.first.ListID.should be == "512a3bc577a58fdf689c654329b50fa0"
opens.Results.first.Date.should be == "2010-10-11 08:29:00"
opens.Results.first.IPAddress.should be == "192.168.126.87"
opens.Results.first.Latitude.should be == -33.8683
opens.Results.first.Longitude.should be == 151.2086
opens.Results.first.City.should be == "Sydney"
opens.Results.first.Region.should be == "New South Wales"
opens.Results.first.CountryCode.should be == "AU"
opens.Results.first.CountryName.should be == "Australia"
opens.ResultsOrderedBy.should be == "date"
opens.OrderDirection.should be == "asc"
opens.PageNumber.should be == 1
opens.PageSize.should be == 1000
opens.RecordsOnThisPage.should be == 5
opens.TotalNumberOfRecords.should be == 5
opens.NumberOfPages.should be == 1
end
should "get the subscriber clicks for a campaign" do
min_date = "2010-01-01"
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/clicks.json?page=1&pagesize=1000&orderfield=date&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}", "campaign_clicks.json")
clicks = @campaign.clicks min_date
clicks.Results.size.should be == 3
clicks.Results.first.EmailAddress.should be == "subs+6576576576@example.com"
clicks.Results.first.URL.should be == "http://video.google.com.au/?hl=en&tab=wv"
clicks.Results.first.ListID.should be == "512a3bc577a58fdf689c654329b50fa0"
clicks.Results.first.Date.should be == "2010-10-11 08:29:00"
clicks.Results.first.IPAddress.should be == "192.168.126.87"
clicks.Results.first.Latitude.should be == -33.8683
clicks.Results.first.Longitude.should be == 151.2086
clicks.Results.first.City.should be == "Sydney"
clicks.Results.first.Region.should be == "New South Wales"
clicks.Results.first.CountryCode.should be == "AU"
clicks.Results.first.CountryName.should be == "Australia"
clicks.ResultsOrderedBy.should be == "date"
clicks.OrderDirection.should be == "asc"
clicks.PageNumber.should be == 1
clicks.PageSize.should be == 1000
clicks.RecordsOnThisPage.should be == 3
clicks.TotalNumberOfRecords.should be == 3
clicks.NumberOfPages.should be == 1
end
should "get the unsubscribes for a campaign" do
min_date = "2010-01-01"
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/unsubscribes.json?page=1&pagesize=1000&orderfield=date&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}", "campaign_unsubscribes.json")
unsubscribes = @campaign.unsubscribes min_date
unsubscribes.Results.size.should be == 1
unsubscribes.Results.first.EmailAddress.should be == "subs+6576576576@example.com"
unsubscribes.Results.first.ListID.should be == "512a3bc577a58fdf689c654329b50fa0"
unsubscribes.Results.first.Date.should be == "2010-10-11 08:29:00"
unsubscribes.Results.first.IPAddress.should be == "192.168.126.87"
unsubscribes.ResultsOrderedBy.should be == "date"
unsubscribes.OrderDirection.should be == "asc"
unsubscribes.PageNumber.should be == 1
unsubscribes.PageSize.should be == 1000
unsubscribes.RecordsOnThisPage.should be == 1
unsubscribes.TotalNumberOfRecords.should be == 1
unsubscribes.NumberOfPages.should be == 1
end
should "get the spam complaints for a campaign" do
min_date = "2010-01-01"
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/spam.json?page=1&pagesize=1000&orderfield=date&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}", "campaign_spam.json")
spam = @campaign.spam min_date
spam.Results.size.should be == 1
spam.Results.first.EmailAddress.should be == "subs+6576576576@example.com"
spam.Results.first.ListID.should be == "512a3bc577a58fdf689c654329b50fa0"
spam.Results.first.Date.should be == "2010-10-11 08:29:00"
spam.ResultsOrderedBy.should be == "date"
spam.OrderDirection.should be == "asc"
spam.PageNumber.should be == 1
spam.PageSize.should be == 1000
spam.RecordsOnThisPage.should be == 1
spam.TotalNumberOfRecords.should be == 1
spam.NumberOfPages.should be == 1
end
should "get the bounces for a campaign" do
min_date = "2010-01-01"
stub_get(@auth, "campaigns/#{@campaign.campaign_id}/bounces.json?page=1&pagesize=1000&orderfield=date&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}", "campaign_bounces.json")
bounces = @campaign.bounces min_date
bounces.Results.size.should be == 2
bounces.Results.first.EmailAddress.should be == "asdf@softbouncemyemail.com"
bounces.Results.first.ListID.should be == "654523a5855b4a440bae3fb295641546"
bounces.Results.first.BounceType.should be == "Soft"
bounces.Results.first.Date.should be == "2010-07-02 16:46:00"
bounces.Results.first.Reason.should be == "Bounce - But No Email Address Returned "
bounces.ResultsOrderedBy.should be == "date"
bounces.OrderDirection.should be == "asc"
bounces.PageNumber.should be == 1
bounces.PageSize.should be == 1000
bounces.RecordsOnThisPage.should be == 2
bounces.TotalNumberOfRecords.should be == 2
bounces.NumberOfPages.should be == 1
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/helper.rb | test/helper.rb | require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
])
SimpleCov.start
require 'test/unit'
require 'pathname'
require 'shoulda/context'
require 'matchy'
require 'fakeweb'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'createsend'
FakeWeb.allow_net_connect = %r[^https?://coveralls.io]
def fixture_file(filename)
return '' if filename == ''
file_path = File.expand_path(File.dirname(__FILE__) + '/fixtures/' + filename)
File.read(file_path)
end
def createsend_url(auth, url)
if not url =~ /^http/
auth_section = ''
auth_section = "#{auth[:api_key]}:x@" if auth and auth.has_key? :api_key
result = "https://#{auth_section}api.createsend.com/api/v3.3/#{url}"
else
result = url
end
result
end
def stub_request(method, auth, url, filename, status=nil)
options = {:body => ""}
options.merge!({:body => fixture_file(filename)}) if filename
options.merge!({:status => status}) if status
options.merge!(:content_type => "application/json; charset=utf-8")
createsend_url = createsend_url(auth, url)
FakeWeb.register_uri(method, createsend_url, options)
end
def stub_get(*args); stub_request(:get, *args) end
def stub_post(*args); stub_request(:post, *args) end
def stub_put(*args); stub_request(:put, *args) end
def stub_delete(*args); stub_request(:delete, *args) end
def multiple_contexts(*contexts, &blk)
contexts.each do |context|
send(context, &blk)
end
end
def authenticated_using_oauth_context(&blk)
context "when an api caller is authenticated using oauth" do
setup do
@access_token = 'joidjo2i3joi3je'
@refresh_token = 'j89u98eu9e8ufe'
@auth = {:access_token => @access_token, :refresh_token => @refresh_token}
end
merge_block(&blk)
end
end
def authenticated_using_api_key_context(&blk)
context "when an api caller is authenticated using an api key" do
setup do
@api_key = '123123123123123123123'
@auth = {:api_key => @api_key}
end
merge_block(&blk)
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/transactional_smart_email_test.rb | test/transactional_smart_email_test.rb | require File.dirname(__FILE__) + '/helper'
class TransactionalSmartEmailTest < Test::Unit::TestCase
multiple_contexts "authenticated_using_oauth_context", "authenticated_using_api_key_context" do
setup do
@client_id = "87y8d7qyw8d7yq8w7ydwqwd"
@smart_email_id = "bcf40510-f968-11e4-ab73-bf67677cc1f4"
@email = CreateSend::Transactional::SmartEmail.new @auth, @smart_email_id
end
should "get the list of smart emails" do
stub_get(@auth, "transactional/smartemail", "tx_smartemails.json")
response = CreateSend::Transactional::SmartEmail.list(@auth)
response.length.should be == 2
response[0].ID.should be == "1e654df2-f484-11e4-970c-6c4008bc7468"
response[0].Name.should be == "Welcome email"
response[0].Status.should be == "Active"
end
should "get the list of active smart emails using a client ID" do
stub_get(@auth, "transactional/smartemail?status=active&client=#{@client_id}", "tx_smartemails.json")
response = CreateSend::Transactional::SmartEmail.list(@auth, { :client => @client_id, :status => 'active'} )
response.length.should be == 2
response[0].ID.should be == "1e654df2-f484-11e4-970c-6c4008bc7468"
response[0].Name.should be == "Welcome email"
response[0].Status.should be == "Active"
end
should "get the details of smart email" do
stub_get(@auth, "transactional/smartemail/#{@smart_email_id}", "tx_smartemail_details.json")
response = CreateSend::Transactional::SmartEmail.new(@auth, @smart_email_id).details
response.Name.should be == "Reset Password"
response.Status.should be == "active"
response.Properties.ReplyTo.should be == "joe@example.com"
end
should "send smart email to one recipient" do
stub_post(@auth, "transactional/smartemail/#{@smart_email_id}/send", "tx_send_single.json")
email = {
"To" => "Bob Sacamano <bob@example.com>",
"Data" => {
"anEmailVariable" => 'foo',
"anotherEmailVariable" => 'bar'
}
}
response = CreateSend::Transactional::SmartEmail.new(@auth, @smart_email_id).send(email)
response.length.should be == 1
response[0].MessageID.should be == "0cfe150d-d507-11e4-84a7-c31e5b59881d"
response[0].Recipient.should be == "\"Bob Sacamano\" <bob@example.com>"
response[0].Status.should be == "Received"
end
should "send smart email to multiple recipients with all the options" do
stub_post(@auth, "transactional/smartemail/#{@smart_email_id}/send", "tx_send_multiple.json")
email = {
"To" => [
"Bob Sacamano <bob@example.com>",
"Newman <newman@example.com>",
],
"CC" => [],
"BCC" => [],
"Data" => {
"anEmailVariable" => 'foo',
"anotherEmailVariable" => 'bar'
},
"Attachments" => [
"Name" => "filename.gif",
"Type" => "image/gif",
"Content" => "R0lGODlhIAAgAKIAAP8AAJmZADNmAMzMAP//AAAAAP///wAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMwMTQgNzkuMTU2Nzk3LCAyMDE0LzA4LzIwLTA5OjUzOjAyICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxNCAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDowNzZGOUNGOUVDRDIxMUU0ODM2RjhGMjNCMTcxN0I2RiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDowNzZGOUNGQUVDRDIxMUU0ODM2RjhGMjNCMTcxN0I2RiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjA3NkY5Q0Y3RUNEMjExRTQ4MzZGOEYyM0IxNzE3QjZGIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjA3NkY5Q0Y4RUNEMjExRTQ4MzZGOEYyM0IxNzE3QjZGIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+Af/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIBwYFBAMCAQAAIfkEAAAAAAAsAAAAACAAIAAAA5loutz+MKpSpIWU3r1KCBW3eYQmWgWhmiemEgPbNqk6xDOd1XGYV77UzTfbTWC4nAHYQRKLu1VSuXxlpsodAFDAZrfcIbXDFXqhNacoQ3vZpuxHSJZ2zufyTqcunugdd00vQ0F4chQCAgYCaTcxiYuMMhGJFG89kYpFl5MzkoRPnpJskFSaDqctRoBxHEQsdGs0f7Qjq3utDwkAOw=="
],
"AddRecipientsToListID" => true
}
response = CreateSend::Transactional::SmartEmail.new(@auth, @smart_email_id).send(email)
response.length.should be == 2
response[1].MessageID.should be == "0cfe150d-d507-11e4-b579-a64eb0d9c74d"
response[1].Recipient.should be == "\"Newman\" <newman@example.com>"
response[1].Status.should be == "Received"
end
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/test/list_test.rb | test/list_test.rb | require File.dirname(__FILE__) + '/helper'
class ListTest < Test::Unit::TestCase
multiple_contexts "authenticated_using_oauth_context", "authenticated_using_api_key_context" do
setup do
@client_id = "87y8d7qyw8d7yq8w7ydwqwd"
@list_id = "e3c5f034d68744f7881fdccf13c2daee"
@list = CreateSend::List.new @auth, @list_id
end
should "create a list without passing in unsubscribe setting" do
stub_post(@auth, "lists/#{@client_id}.json", "create_list.json")
list_id = CreateSend::List.create @auth, @client_id, "List One", "", false, ""
list_id.should be == "e3c5f034d68744f7881fdccf13c2daee"
end
should "create a list passing in unsubscribe setting" do
stub_post(@auth, "lists/#{@client_id}.json", "create_list.json")
list_id = CreateSend::List.create @auth, @client_id, "List One", "", false, "", "OnlyThisList"
list_id.should be == "e3c5f034d68744f7881fdccf13c2daee"
end
should "update a list without passing in unsubscribe setting" do
stub_put(@auth, "lists/#{@list.list_id}.json", nil)
@list.update "List One Renamed", "", false, ""
end
should "update a list passing in unsubscribe setting" do
stub_put(@auth, "lists/#{@list.list_id}.json", nil)
@list.update "List One Renamed", "", false, "", "OnlyThisList"
end
should "update a list passing in unsubscribe setting and suppression list options" do
stub_put(@auth, "lists/#{@list.list_id}.json", nil)
@list.update "List One Renamed", "", false, "", "OnlyThisList", true, true
end
should "delete a list" do
stub_delete(@auth, "lists/#{@list.list_id}.json", nil)
@list.delete
end
should "create a custom field" do
stub_post(@auth, "lists/#{@list.list_id}/customfields.json", "create_custom_field.json")
personalisation_tag = @list.create_custom_field "new date field", "Date"
request = FakeWeb.last_request.body
request.include?("\"FieldName\":\"new date field\"").should be == true
request.include?("\"DataType\":\"Date\"").should be == true
request.include?("\"Options\":[]").should be == true
request.include?("\"VisibleInPreferenceCenter\":true").should be == true
personalisation_tag.should be == "[newdatefield]"
end
should "create a custom field with options and visible_in_preference_center" do
stub_post(@auth, "lists/#{@list.list_id}/customfields.json", "create_custom_field.json")
options = ["one", "two"]
personalisation_tag = @list.create_custom_field("newsletter format",
"MultiSelectOne", options, false)
request = FakeWeb.last_request.body
request.include?("\"FieldName\":\"newsletter format\"").should be == true
request.include?("\"DataType\":\"MultiSelectOne\"").should be == true
request.include?("\"Options\":[\"one\",\"two\"]").should be == true
request.include?("\"VisibleInPreferenceCenter\":false").should be == true
personalisation_tag.should be == "[newdatefield]"
end
should "update a custom field" do
key = "[mycustomfield]"
stub_put(@auth, "lists/#{@list.list_id}/customfields/#{ERB::Util.url_encode(key)}.json", "update_custom_field.json")
personalisation_tag = @list.update_custom_field key, "my renamed custom field", true
request = FakeWeb.last_request.body
request.include?("\"FieldName\":\"my renamed custom field\"").should be == true
request.include?("\"VisibleInPreferenceCenter\":true").should be == true
personalisation_tag.should be == "[myrenamedcustomfield]"
end
should "delete a custom field" do
custom_field_key = "[newdatefield]"
stub_delete(@auth, "lists/#{@list.list_id}/customfields/#{ERB::Util.url_encode(custom_field_key)}.json", nil)
@list.delete_custom_field custom_field_key
end
should "update the options of a multi-optioned custom field" do
custom_field_key = "[newdatefield]"
new_options = [ "one", "two", "three" ]
stub_put(@auth, "lists/#{@list.list_id}/customfields/#{ERB::Util.url_encode(custom_field_key)}/options.json", nil)
@list.update_custom_field_options custom_field_key, new_options, true
end
should "get the details of a list" do
stub_get(@auth, "lists/#{@list.list_id}.json", "list_details.json")
details = @list.details
details.ConfirmedOptIn.should be == false
details.Title.should be == "a non-basic list :)"
details.UnsubscribePage.should be == ""
details.ListID.should be == "2fe4c8f0373ce320e2200596d7ef168f"
details.ConfirmationSuccessPage.should be == ""
details.UnsubscribeSetting.should be == "AllClientLists"
end
should "get the custom fields for a list" do
stub_get(@auth, "lists/#{@list.list_id}/customfields.json", "custom_fields.json")
cfs = @list.custom_fields
cfs.size.should be == 3
cfs.first.FieldName.should be == "website"
cfs.first.Key.should be == "[website]"
cfs.first.DataType.should be == "Text"
cfs.first.FieldOptions.should be == []
cfs.first.VisibleInPreferenceCenter.should be == true
end
should "get the segments for a list" do
stub_get(@auth, "lists/#{@list.list_id}/segments.json", "segments.json")
segments = @list.segments
segments.size.should be == 2
segments.first.ListID.should be == 'a58ee1d3039b8bec838e6d1482a8a965'
segments.first.SegmentID.should be == '46aa5e01fd43381863d4e42cf277d3a9'
segments.first.Title.should be == 'Segment One'
end
should "get the stats for a list" do
stub_get(@auth, "lists/#{@list.list_id}/stats.json", "list_stats.json")
stats = @list.stats
stats.TotalActiveSubscribers.should be == 6
stats.TotalUnsubscribes.should be == 2
stats.TotalDeleted.should be == 0
stats.TotalBounces.should be == 0
end
should "get the active subscribers for a list" do
min_date = "2010-01-01"
stub_get(@auth, "lists/#{@list.list_id}/active.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}&includetrackingpreference=false&includesmspreference=false",
"active_subscribers.json")
res = @list.active min_date
res.ResultsOrderedBy.should be == "email"
res.OrderDirection.should be == "asc"
res.PageNumber.should be == 1
res.PageSize.should be == 1000
res.RecordsOnThisPage.should be == 5
res.TotalNumberOfRecords.should be == 5
res.NumberOfPages.should be == 1
res.Results.size.should be == 5
res.Results.first.EmailAddress.should be == "subs+7t8787Y@example.com"
res.Results.first.Name.should be =="Person One"
res.Results.first.Date.should be == "2010-10-25 10:28:00"
res.Results.first.ListJoinedDate.should be == "2010-10-25 10:28:00"
res.Results.first.State.should be == "Active"
res.Results.first.CustomFields.size.should be == 5
res.Results.first.CustomFields[0].Key.should be == "website"
res.Results.first.CustomFields[0].Value.should be == "http://example.com"
res.Results.first.CustomFields[1].Key.should be == "multi select field"
res.Results.first.CustomFields[1].Value.should be == "option one"
res.Results.first.CustomFields[2].Key.should be == "multi select field"
res.Results.first.CustomFields[2].Value.should be == "option two"
res.Results.first.ReadsEmailWith.should be == "Gmail"
end
should "get the unconfirmed subscribers for a list" do
min_date = "2010-01-01"
stub_get(@auth, "lists/#{@list.list_id}/unconfirmed.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}&includetrackingpreference=true&includesmspreference=true",
"unconfirmed_subscribers.json")
res = @list.unconfirmed(min_date, 1, 1000, "email", "asc", true, include_sms_preference:true)
res.ResultsOrderedBy.should be == "email"
res.OrderDirection.should be == "asc"
res.PageNumber.should be == 1
res.PageSize.should be == 1000
res.RecordsOnThisPage.should be == 2
res.TotalNumberOfRecords.should be == 2
res.NumberOfPages.should be == 1
res.Results.size.should be == 2
res.Results.first.EmailAddress.should be == "subs+7t8787Y@example.com"
res.Results.first.Name.should be =="Unconfirmed One"
res.Results.first.Date.should be =="2010-10-25 10:28:00"
res.Results.first.ListJoinedDate.should be =="2010-10-25 10:28:00"
res.Results.first.State.should be == "Unconfirmed"
res.Results.first.ConsentToTrack.should be == "Yes"
res.Results.first.ConsentToSendSms.should be == "No"
end
should "get the unsubscribed subscribers for a list" do
min_date = "2010-01-01"
stub_get(@auth, "lists/#{@list.list_id}/unsubscribed.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}&includetrackingpreference=false&includesmspreference=false",
"unsubscribed_subscribers.json")
res = @list.unsubscribed min_date
res.ResultsOrderedBy.should be == "email"
res.OrderDirection.should be == "asc"
res.PageNumber.should be == 1
res.PageSize.should be == 1000
res.RecordsOnThisPage.should be == 5
res.TotalNumberOfRecords.should be == 5
res.NumberOfPages.should be == 1
res.Results.size.should be == 5
res.Results.first.EmailAddress.should be == "subscriber@example.com"
res.Results.first.Name.should be == "Unsub One"
res.Results.first.Date.should be == "2010-10-25 13:11:00"
res.Results.first.ListJoinedDate.should be == "2010-10-25 13:11:00"
res.Results.first.State.should be == "Unsubscribed"
res.Results.first.CustomFields.size.should be == 0
res.Results.first.ReadsEmailWith.should be == "Gmail"
end
should "get the deleted subscribers for a list" do
min_date = "2010-01-01"
stub_get(@auth, "lists/#{@list.list_id}/deleted.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}&includetrackingpreference=false&includesmspreference=false",
"deleted_subscribers.json")
res = @list.deleted min_date
res.ResultsOrderedBy.should be == "email"
res.OrderDirection.should be == "asc"
res.PageNumber.should be == 1
res.PageSize.should be == 1000
res.RecordsOnThisPage.should be == 5
res.TotalNumberOfRecords.should be == 5
res.NumberOfPages.should be == 1
res.Results.size.should be == 5
res.Results.first.EmailAddress.should be == "subscriber@example.com"
res.Results.first.Name.should be == "Deleted One"
res.Results.first.Date.should be == "2010-10-25 13:11:00"
res.Results.first.ListJoinedDate.should be == "2010-10-25 13:11:00"
res.Results.first.State.should be == "Deleted"
res.Results.first.CustomFields.size.should be == 0
res.Results.first.ReadsEmailWith.should be == "Gmail"
end
should "get the bounced subscribers for a list" do
min_date = "2010-01-01"
stub_get(@auth, "lists/#{@list.list_id}/bounced.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{ERB::Util.url_encode(min_date)}&includetrackingpreference=false&includesmspreference=false",
"bounced_subscribers.json")
res = @list.bounced min_date
res.ResultsOrderedBy.should be == "email"
res.OrderDirection.should be == "asc"
res.PageNumber.should be == 1
res.PageSize.should be == 1000
res.RecordsOnThisPage.should be == 1
res.TotalNumberOfRecords.should be == 1
res.NumberOfPages.should be == 1
res.Results.size.should be == 1
res.Results.first.EmailAddress.should be == "bouncedsubscriber@example.com"
res.Results.first.Name.should be == "Bounced One"
res.Results.first.Date.should be == "2010-10-25 13:11:00"
res.Results.first.ListJoinedDate.should be == "2010-10-25 13:11:00"
res.Results.first.State.should be == "Bounced"
res.Results.first.CustomFields.size.should be == 0
res.Results.first.ReadsEmailWith.should be == ""
end
should "get the webhooks for a list" do
stub_get(@auth, "lists/#{@list.list_id}/webhooks.json", "list_webhooks.json")
hooks = @list.webhooks
hooks.size.should be == 2
hooks.first.WebhookID.should be == "943678317049bc13"
hooks.first.Events.size.should be == 1
hooks.first.Events.first.should be == "Deactivate"
hooks.first.Url.should be == "http://www.postbin.org/d9w8ud9wud9w"
hooks.first.Status.should be == "Active"
hooks.first.PayloadFormat.should be == "Json"
end
should "create a webhook for a list" do
stub_post(@auth, "lists/#{@list.list_id}/webhooks.json", "create_list_webhook.json")
webhook_id = @list.create_webhook ["Unsubscribe", "Spam"], "http://example.com/unsub", "json"
webhook_id.should be == "6a783d359bd44ef62c6ca0d3eda4412a"
end
should "test a webhook for a list" do
webhook_id = "jiuweoiwueoiwueowiueo"
stub_get(@auth, "lists/#{@list.list_id}/webhooks/#{webhook_id}/test.json", nil)
@list.test_webhook webhook_id
end
should "delete a webhook for a list" do
webhook_id = "jiuweoiwueoiwueowiueo"
stub_delete(@auth, "lists/#{@list.list_id}/webhooks/#{webhook_id}.json", nil)
@list.delete_webhook webhook_id
end
should "activate a webhook for a list" do
webhook_id = "jiuweoiwueoiwueowiueo"
stub_put(@auth, "lists/#{@list.list_id}/webhooks/#{webhook_id}/activate.json", nil)
@list.activate_webhook webhook_id
end
should "de-activate a webhook for a list" do
webhook_id = "jiuweoiwueoiwueowiueo"
stub_put(@auth, "lists/#{@list.list_id}/webhooks/#{webhook_id}/deactivate.json", nil)
@list.deactivate_webhook webhook_id
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend.rb | lib/createsend.rb | libdir = File.dirname(__FILE__)
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
require 'createsend/version'
require 'createsend/createsend'
require 'createsend/client'
require 'createsend/campaign'
require 'createsend/list'
require 'createsend/segment'
require 'createsend/subscriber'
require 'createsend/template'
require 'createsend/person'
require 'createsend/administrator'
require 'createsend/transactional_classic_email'
require 'createsend/transactional_smart_email'
require 'createsend/transactional_timeline'
require 'createsend/journey'
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/version.rb | lib/createsend/version.rb | module CreateSend
VERSION = "6.1.2" unless defined?(CreateSend::VERSION)
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/transactional_timeline.rb | lib/createsend/transactional_timeline.rb | module CreateSend
module Transactional
class Timeline < CreateSend
attr_reader :client_id
def initialize(auth, client_id = nil)
@auth = auth
@client_id = client_id
super
end
def messages(options = {})
options = add_client_id(options)
response = get "/transactional/messages", { :query => options }
response.map{|item| Hashie::Mash.new(item)}
end
def statistics(options = {})
options = add_client_id(options)
response = get "/transactional/statistics", { :query => options }
Hashie::Mash.new(response)
end
def details(message_id, options = {})
options = add_client_id(options)
response = get "/transactional/messages/#{message_id}", { :query => options }
Hashie::Mash.new(response)
end
def resend(message_id)
response = post "/transactional/messages/#{message_id}/resend"
response.map{|item| Hashie::Mash.new(item)}
end
private
def add_client_id(options)
options['clientID'] = @client_id if @client_id
options
end
end
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/createsend.rb | lib/createsend/createsend.rb | require 'cgi'
require 'uri'
require 'httparty'
require 'hashie'
require 'json'
module CreateSend
USER_AGENT_STRING = "createsend-ruby-#{VERSION}-#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}-#{RUBY_PLATFORM}"
# Represents a CreateSend API error. Contains specific data about the error.
class CreateSendError < StandardError
attr_reader :data
def initialize(data)
@data = data
# @data should contain Code, Message and optionally ResultData
extra = @data.ResultData ? "\nExtra result data: #{@data.ResultData}" : ""
super "The CreateSend API responded with the following error"\
" - #{@data.Code}: #{@data.Message}#{extra}"
end
end
# Raised for HTTP response codes of 400...500
class ClientError < StandardError; end
# Raised for HTTP response codes of 500...600
class ServerError < StandardError; end
# Raised for HTTP response code of 400
class BadRequest < CreateSendError; end
# Raised for HTTP response code of 401
class Unauthorized < CreateSendError; end
# Raised for HTTP response code of 404
class NotFound < ClientError; end
# Raised for HTTP response code of 429
class TooManyRequests < ClientError; end
# Raised for HTTP response code of 401, specifically when an OAuth token
# in invalid (Code: 120, Message: 'Invalid OAuth Token')
class InvalidOAuthToken < Unauthorized; end
# Raised for HTTP response code of 401, specifically when an OAuth token
# has expired (Code: 121, Message: 'Expired OAuth Token')
class ExpiredOAuthToken < Unauthorized; end
# Raised for HTTP response code of 401, specifically when an OAuth token
# has been revoked (Code: 122, Message: 'Revoked OAuth Token')
class RevokedOAuthToken < Unauthorized; end
# Provides high level CreateSend functionality/data you'll probably need.
class CreateSend
include HTTParty
default_timeout 120
attr_reader :auth_details
# Specify cert authority file for cert validation
ssl_ca_file File.expand_path(File.join(File.dirname(__FILE__), 'cacert.pem'))
# Set a custom user agent string to be used when instances of
# CreateSend::CreateSend make API calls.
#
# user_agent - The user agent string to use in the User-Agent header when
# instances of this class make API calls. If set to nil, the
# default value of CreateSend::USER_AGENT_STRING will be used.
def self.user_agent(user_agent)
headers({'User-Agent' => user_agent || USER_AGENT_STRING})
end
# Get the authorization URL for your application, given the application's
# client_id, redirect_uri, scope, and optional state data.
def self.authorize_url(client_id, redirect_uri, scope, state=nil)
qs = "client_id=#{CGI.escape(client_id.to_s)}"
qs << "&redirect_uri=#{CGI.escape(redirect_uri.to_s)}"
qs << "&scope=#{CGI.escape(scope.to_s)}"
qs << "&state=#{CGI.escape(state.to_s)}" if state
"#{@@oauth_base_uri}?#{qs}"
end
# Exchange a provided OAuth code for an OAuth access token, 'expires in'
# value, and refresh token.
def self.exchange_token(client_id, client_secret, redirect_uri, code)
body = "grant_type=authorization_code"
body << "&client_id=#{CGI.escape(client_id.to_s)}"
body << "&client_secret=#{CGI.escape(client_secret.to_s)}"
body << "&redirect_uri=#{CGI.escape(redirect_uri.to_s)}"
body << "&code=#{CGI.escape(code.to_s)}"
options = {:body => body}
response = HTTParty.post(@@oauth_token_uri, options)
if response.has_key? 'error' and response.has_key? 'error_description'
err = "Error exchanging code for access token: "
err << "#{response['error']} - #{response['error_description']}"
raise err
end
r = Hashie::Mash.new(response)
[r.access_token, r.expires_in, r.refresh_token]
end
# Refresh an OAuth access token, given an OAuth refresh token.
# Returns a new access token, 'expires in' value, and refresh token.
def self.refresh_access_token(refresh_token)
options = {
:body => "grant_type=refresh_token&refresh_token=#{CGI.escape(refresh_token)}" }
response = HTTParty.post(@@oauth_token_uri, options)
if response.has_key? 'error' and response.has_key? 'error_description'
err = "Error refreshing access token: "
err << "#{response['error']} - #{response['error_description']}"
raise err
end
r = Hashie::Mash.new(response)
[r.access_token, r.expires_in, r.refresh_token]
end
def initialize(*args)
if args.size > 0
auth args.first # Expect auth details as first argument
end
end
@@base_uri = "https://api.createsend.com/api/v3.3"
@@oauth_base_uri = "https://api.createsend.com/oauth"
@@oauth_token_uri = "#{@@oauth_base_uri}/token"
headers({
'User-Agent' => USER_AGENT_STRING,
'Content-Type' => 'application/json; charset=utf-8'
})
base_uri @@base_uri
# Authenticate using either OAuth or an API key.
def auth(auth_details)
@auth_details = auth_details
end
# Refresh the current OAuth token using the current refresh token.
def refresh_token
if not @auth_details or
not @auth_details.has_key? :refresh_token or
not @auth_details[:refresh_token]
raise '@auth_details[:refresh_token] does not contain a refresh token.'
end
access_token, expires_in, refresh_token =
self.class.refresh_access_token @auth_details[:refresh_token]
auth({
:access_token => access_token,
:refresh_token => refresh_token})
[access_token, expires_in, refresh_token]
end
# Gets your clients.
def clients
response = get('/clients.json')
response.map{|item| Hashie::Mash.new(item)}
end
# Get your billing details.
def billing_details
response = get('/billingdetails.json')
Hashie::Mash.new(response)
end
# Gets valid countries.
def countries
response = get('/countries.json')
response.parsed_response
end
# Gets the current date in your account's timezone.
def systemdate
response = get('/systemdate.json')
Hashie::Mash.new(response)
end
# Gets valid timezones.
def timezones
response = get('/timezones.json')
response.parsed_response
end
# Gets the administrators for the account.
def administrators
response = get('/admins.json')
response.map{|item| Hashie::Mash.new(item)}
end
# Gets the primary contact for the account.
def get_primary_contact
response = get('/primarycontact.json')
Hashie::Mash.new(response)
end
# Set the primary contect for the account.
def set_primary_contact(email)
options = { :query => { :email => email } }
response = put("/primarycontact.json", options)
Hashie::Mash.new(response)
end
# Get a URL which initiates a new external session for the user with the
# given email.
# Full details: http://www.campaignmonitor.com/api/account/#single_sign_on
#
# email - The email address of the Campaign Monitor user for whom
# the login session should be created.
# chrome - Which 'chrome' to display - Must be either "all",
# "tabs", or "none".
# url - The URL to display once logged in. e.g. "/subscribers/"
# integrator_id - The integrator ID. You need to contact Campaign Monitor
# support to get an integrator ID.
# client_id - The Client ID of the client which should be active once
# logged in to the Campaign Monitor account.
#
# Returns An object containing a single field SessionUrl which represents
# the URL to initiate the external Campaign Monitor session.
def external_session_url(email, chrome, url, integrator_id, client_id)
options = { :body => {
:Email => email,
:Chrome => chrome,
:Url => url,
:IntegratorID => integrator_id,
:ClientID => client_id }.to_json }
response = put("/externalsession.json", options)
Hashie::Mash.new(response)
end
def get(*args)
args = add_auth_details_to_options(args)
handle_response CreateSend.get(*args)
end
alias_method :cs_get, :get
def post(*args)
args = add_auth_details_to_options(args)
handle_response CreateSend.post(*args)
end
alias_method :cs_post, :post
def put(*args)
args = add_auth_details_to_options(args)
handle_response CreateSend.put(*args)
end
alias_method :cs_put, :put
def delete(*args)
args = add_auth_details_to_options(args)
handle_response CreateSend.delete(*args)
end
alias_method :cs_delete, :delete
def add_auth_details_to_options(args)
if @auth_details
options = {}
if args.size > 1
options = args[1]
end
if @auth_details.has_key? :access_token
options[:headers] = {
"Authorization" => "Bearer #{@auth_details[:access_token]}" }
elsif @auth_details.has_key? :api_key
if not options.has_key? :basic_auth
options[:basic_auth] = {
:username => @auth_details[:api_key], :password => 'x' }
end
end
args[1] = options
end
args
end
def handle_response(response) # :nodoc:
case response.code
when 400
raise BadRequest.new(Hashie::Mash.new response)
when 401
data = Hashie::Mash.new(response)
case data.Code
when 120
raise InvalidOAuthToken.new data
when 121
raise ExpiredOAuthToken.new data
when 122
raise RevokedOAuthToken.new data
else
raise Unauthorized.new data
end
when 404
raise NotFound.new
when 429
raise TooManyRequests.new
when 400...500
raise ClientError.new
when 500...600
raise ServerError.new
else
response
end
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/segment.rb | lib/createsend/segment.rb | module CreateSend
# Represents a subscriber list segment and associated functionality.
class Segment < CreateSend
attr_reader :segment_id
def initialize(auth, segment_id)
@segment_id = segment_id
super
end
# Creates a new segment.
def self.create(auth, list_id, title, rule_groups)
options = { :body => {
:Title => title,
:RuleGroups => rule_groups }.to_json }
cs = CreateSend.new auth
response = cs.post "/segments/#{list_id}.json", options
response.parsed_response
end
# Updates this segment.
def update(title, rule_groups)
options = { :body => {
:Title => title,
:RuleGroups => rule_groups }.to_json }
cs_put "/segments/#{segment_id}.json", options
end
# Adds a rule to this segment.
def add_rule_group(rule_group)
options = { :body => {
:Rules => rule_group }.to_json }
post "rules", options
end
# Gets the active subscribers in this segment.
def subscribers(date="", page=1, page_size=1000, order_field="email",
order_direction="asc", include_tracking_preference=false)
options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
:orderfield => order_field,
:orderdirection => order_direction,
:includetrackingpreference => include_tracking_preference } }
response = get "active", options
Hashie::Mash.new(response)
end
# Gets the details of this segment
def details
response = cs_get "/segments/#{segment_id}.json", {}
Hashie::Mash.new(response)
end
# Clears all rules of this segment.
def clear_rules
cs_delete "/segments/#{segment_id}/rules.json", {}
end
# Deletes this segment.
def delete
super "/segments/#{segment_id}.json", {}
end
private
def get(action, options = {})
super uri_for(action), options
end
def post(action, options = {})
super uri_for(action), options
end
def uri_for(action)
"/segments/#{segment_id}/#{action}.json"
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/subscriber.rb | lib/createsend/subscriber.rb | module CreateSend
# Represents a subscriber and associated functionality.
class Subscriber < CreateSend
attr_reader :list_id
attr_reader :email_address
def initialize(auth, list_id, email_address)
@list_id = list_id
@email_address = email_address
super
end
# Gets a subscriber by list ID and email address.
def self.get(auth, list_id, email_address, include_tracking_preference=false)
options = { :query => {
:email => email_address,
:includetrackingpreference => include_tracking_preference }
}
cs = CreateSend.new auth
response = cs.get "/subscribers/#{list_id}.json", options
Hashie::Mash.new(response)
end
# Adds a subscriber to a subscriber list.
def self.add(auth, list_id, email_address, name, custom_fields, resubscribe,
consent_to_track, restart_subscription_based_autoresponders=false, mobile_number=nil, consent_to_send_sms=nil)
options = { :body => {
:EmailAddress => email_address,
:Name => name,
:MobileNumber => mobile_number,
:CustomFields => custom_fields,
:Resubscribe => resubscribe,
:RestartSubscriptionBasedAutoresponders =>
restart_subscription_based_autoresponders,
:ConsentToTrack => consent_to_track,
:ConsentToSendSms => consent_to_send_sms }.to_json }
cs = CreateSend.new auth
response = cs.post "/subscribers/#{list_id}.json", options
response.parsed_response
end
# Imports subscribers into a subscriber list.
def self.import(auth, list_id, subscribers, resubscribe,
queue_subscription_based_autoresponders=false,
restart_subscription_based_autoresponders=false)
options = { :body => {
:Subscribers => subscribers,
:Resubscribe => resubscribe,
:QueueSubscriptionBasedAutoresponders =>
queue_subscription_based_autoresponders,
:RestartSubscriptionBasedAutoresponders =>
restart_subscription_based_autoresponders }.to_json }
begin
cs = CreateSend.new auth
response = cs.post(
"/subscribers/#{list_id}/import.json", options)
rescue BadRequest => br
# Subscriber import will throw BadRequest if some subscribers are not
# imported successfully. If this occurs, we want to return the
# ResultData property of the BadRequest exception (which is of the
# same "form" as the response we would receive upon a completely
# successful import).
if br.data.ResultData
return br.data.ResultData
else
raise br # Just raise other Bad Request errors
end
end
Hashie::Mash.new(response)
end
# Updates any aspect of a subscriber, including email address, name, and
# custom field data if supplied.
def update(new_email_address, name, custom_fields, resubscribe,
consent_to_track, restart_subscription_based_autoresponders=false, mobile_number=nil, consent_to_send_sms=nil)
options = {
:query => { :email => @email_address },
:body => {
:EmailAddress => new_email_address,
:Name => name,
:MobileNumber => mobile_number,
:CustomFields => custom_fields,
:Resubscribe => resubscribe,
:RestartSubscriptionBasedAutoresponders =>
restart_subscription_based_autoresponders,
:ConsentToTrack => consent_to_track,
:ConsentToSendSms => consent_to_send_sms }.to_json }
put "/subscribers/#{@list_id}.json", options
# Update @email_address, so this object can continue to be used reliably
@email_address = new_email_address
end
# Unsubscribes this subscriber from the associated list.
def unsubscribe
options = { :body => {
:EmailAddress => @email_address }.to_json }
post "/subscribers/#{@list_id}/unsubscribe.json", options
end
# Gets the historical record of this subscriber's trackable actions.
def history
options = { :query => { :email => @email_address } }
response = cs_get "/subscribers/#{@list_id}/history.json", options
response.map{|item| Hashie::Mash.new(item)}
end
# Moves this subscriber to the Deleted state in the associated list.
def delete
options = { :query => { :email => @email_address } }
super "/subscribers/#{@list_id}.json", options
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/template.rb | lib/createsend/template.rb | module CreateSend
# Represents an email template and associated functionality.
class Template < CreateSend
attr_reader :template_id
def initialize(auth, template_id)
@template_id = template_id
super
end
# Creates a new email template.
def self.create(auth, client_id, name, html_url, zip_url)
options = { :body => {
:Name => name,
:HtmlPageURL => html_url,
:ZipFileURL => zip_url }.to_json }
cs = CreateSend.new auth
response = cs.post "/templates/#{client_id}.json", options
response.parsed_response
end
# Gets the details of this email template.
def details
response = get "/templates/#{template_id}.json", {}
Hashie::Mash.new(response)
end
# Updates this email template.
def update(name, html_url, zip_url)
options = { :body => {
:Name => name,
:HtmlPageURL => html_url,
:ZipFileURL => zip_url }.to_json }
put "/templates/#{template_id}.json", options
end
# Deletes this email template.
def delete
super "/templates/#{template_id}.json", {}
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/list.rb | lib/createsend/list.rb | module CreateSend
# Represents a subscriber list and associated functionality.
class List < CreateSend
attr_reader :list_id
def initialize(auth, list_id)
@list_id = list_id
super
end
# Creates a new list for a client.
# client_id - String representing the ID of the client for whom the list
# will be created
# title - String representing the list title/name
# unsubscribe_page - String representing the url of the unsubscribe
# confirmation page
# confirmed_opt_in - A Boolean representing whether this should be a
# confirmed opt-in (double opt-in) list
# confirmation_success_page - String representing the url of the
# confirmation success page
# unsubscribe_setting - A String which must be either "AllClientLists" or
# "OnlyThisList". See the documentation for details:
# http://www.campaignmonitor.com/api/lists/#creating_a_list
def self.create(auth, client_id, title, unsubscribe_page, confirmed_opt_in,
confirmation_success_page, unsubscribe_setting="AllClientLists")
options = { :body => {
:Title => title,
:UnsubscribePage => unsubscribe_page,
:ConfirmedOptIn => confirmed_opt_in,
:ConfirmationSuccessPage => confirmation_success_page,
:UnsubscribeSetting => unsubscribe_setting }.to_json }
cs = CreateSend.new auth
response = cs.post "/lists/#{client_id}.json", options
response.parsed_response
end
# Deletes this list.
def delete
super "/lists/#{list_id}.json", {}
end
# Creates a new custom field for this list.
# field_name - String representing the name to be given to the field
# data_type - String representing the data type of the field. Valid data
# types are 'Text', 'Number', 'MultiSelectOne', 'MultiSelectMany',
# 'Date', 'Country', and 'USState'.
# options - Array of Strings representing the options for the field if it
# is of type 'MultiSelectOne' or 'MultiSelectMany'.
# visible_in_preference_center - Boolean indicating whether or not the
# field should be visible in the subscriber preference center
def create_custom_field(field_name, data_type, options=[],
visible_in_preference_center=true)
options = { :body => {
:FieldName => field_name,
:DataType => data_type,
:Options => options,
:VisibleInPreferenceCenter => visible_in_preference_center }.to_json }
response = post "customfields", options
response.parsed_response
end
# Updates a custom field belonging to this list.
# custom_field_key - String which represents the key for the custom field
# field_name - String representing the name to be given to the field
# visible_in_preference_center - Boolean indicating whether or not the
# field should be visible in the subscriber preference center
def update_custom_field(custom_field_key, field_name,
visible_in_preference_center)
custom_field_key = CGI.escape(custom_field_key)
options = { :body => {
:FieldName => field_name,
:VisibleInPreferenceCenter => visible_in_preference_center }.to_json }
response = put "customfields/#{custom_field_key}", options
response.parsed_response
end
# Deletes a custom field associated with this list.
def delete_custom_field(custom_field_key)
custom_field_key = CGI.escape(custom_field_key)
cs_delete("/lists/#{list_id}/customfields/#{custom_field_key}.json", {})
end
# Updates the options of a multi-optioned custom field on this list.
def update_custom_field_options(custom_field_key, new_options,
keep_existing_options)
custom_field_key = CGI.escape(custom_field_key)
options = { :body => {
:Options => new_options,
:KeepExistingOptions => keep_existing_options }.to_json }
put "customfields/#{custom_field_key}/options", options
end
# Gets the details of this list.
def details
response = cs_get "/lists/#{list_id}.json"
Hashie::Mash.new(response)
end
# Gets the custom fields for this list.
def custom_fields
response = get "customfields"
response.map{|item| Hashie::Mash.new(item)}
end
# Gets the segments for this list.
def segments
response = get "segments"
response.map{|item| Hashie::Mash.new(item)}
end
# Gets the stats for this list.
def stats
response = get "stats"
Hashie::Mash.new(response)
end
# Gets the active subscribers for this list.
def active(date="", page=1, page_size=1000, order_field="email",
order_direction="asc", include_tracking_preference=false, include_sms_preference:false)
paged_result_by_date("active", date, page, page_size, order_field,
order_direction, include_tracking_preference, include_sms_preference)
end
# Gets the unconfirmed subscribers for this list.
def unconfirmed(date="", page=1, page_size=1000, order_field="email",
order_direction="asc", include_tracking_preference=false, include_sms_preference:false)
paged_result_by_date("unconfirmed", date, page, page_size, order_field,
order_direction, include_tracking_preference, include_sms_preference)
end
# Gets the bounced subscribers for this list.
def bounced(date="", page=1, page_size=1000, order_field="email",
order_direction="asc", include_tracking_preference=false, include_sms_preference:false)
paged_result_by_date("bounced", date, page, page_size, order_field,
order_direction, include_tracking_preference, include_sms_preference)
end
# Gets the unsubscribed subscribers for this list.
def unsubscribed(date="", page=1, page_size=1000, order_field="email",
order_direction="asc", include_tracking_preference=false, include_sms_preference:false)
paged_result_by_date("unsubscribed", date, page, page_size, order_field,
order_direction, include_tracking_preference, include_sms_preference)
end
# Gets the deleted subscribers for this list.
def deleted(date="", page=1, page_size=1000, order_field="email",
order_direction="asc", include_tracking_preference=false, include_sms_preference:false)
paged_result_by_date("deleted", date, page, page_size, order_field,
order_direction, include_tracking_preference, include_sms_preference)
end
# Updates this list.
# title - String representing the list title/name
# unsubscribe_page - String representing the url of the unsubscribe
# confirmation page
# confirmed_opt_in - A Boolean representing whether this should be a
# confirmed opt-in (double opt-in) list
# confirmation_success_page - String representing the url of the
# confirmation success page
# unsubscribe_setting - A String which must be either "AllClientLists" or
# "OnlyThisList". See the documentation for details:
# http://www.campaignmonitor.com/api/lists/#updating_a_list
# add_unsubscribes_to_supp_list - When unsubscribe_setting is
# "AllClientLists", a Boolean which represents whether unsubscribes from
# this list should be added to the suppression list
# scrub_active_with_supp_list - When unsubscribe_setting is
# "AllClientLists", a Boolean which represents whether active sunscribers
# should be scrubbed against the suppression list
def update(title, unsubscribe_page, confirmed_opt_in,
confirmation_success_page, unsubscribe_setting="AllClientLists",
add_unsubscribes_to_supp_list=false, scrub_active_with_supp_list=false)
options = { :body => {
:Title => title,
:UnsubscribePage => unsubscribe_page,
:ConfirmedOptIn => confirmed_opt_in,
:ConfirmationSuccessPage => confirmation_success_page,
:UnsubscribeSetting => unsubscribe_setting,
:AddUnsubscribesToSuppList => add_unsubscribes_to_supp_list,
:ScrubActiveWithSuppList => scrub_active_with_supp_list }.to_json }
cs_put "/lists/#{list_id}.json", options
end
# Gets the webhooks for this list.
def webhooks
response = get "webhooks"
response.map{|item| Hashie::Mash.new(item)}
end
# Creates a new webhook for the specified events (an array of strings).
# Valid events are "Subscribe", "Deactivate", and "Update".
# Valid payload formats are "json", and "xml".
def create_webhook(events, url, payload_format)
options = { :body => {
:Events => events,
:Url => url,
:PayloadFormat => payload_format }.to_json }
response = post "webhooks", options
response.parsed_response
end
# Tests that a post can be made to the endpoint specified for the webhook
# identified by webhook_id.
def test_webhook(webhook_id)
get "webhooks/#{webhook_id}/test"
true # An exception will be raised if any error occurs
end
# Deletes a webhook associated with this list.
def delete_webhook(webhook_id)
cs_delete("/lists/#{list_id}/webhooks/#{webhook_id}.json", {})
end
# Activates a webhook associated with this list.
def activate_webhook(webhook_id)
options = { :body => '' }
put "webhooks/#{webhook_id}/activate", options
end
# De-activates a webhook associated with this list.
def deactivate_webhook(webhook_id)
options = { :body => '' }
put "webhooks/#{webhook_id}/deactivate", options
end
private
def paged_result_by_date(resource, date, page, page_size, order_field,
order_direction, include_tracking_preference, include_sms_preference)
options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
:orderfield => order_field,
:orderdirection => order_direction,
:includetrackingpreference => include_tracking_preference,
:includesmspreference => include_sms_preference} }
response = get resource, options
Hashie::Mash.new(response)
end
def get(action, options = {})
super uri_for(action), options
end
def post(action, options = {})
super uri_for(action), options
end
def put(action, options = {})
super uri_for(action), options
end
def uri_for(action)
"/lists/#{list_id}/#{action}.json"
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/client.rb | lib/createsend/client.rb | module CreateSend
# Represents a client and associated functionality.
class Client < CreateSend
attr_reader :client_id
def initialize(auth, client_id)
@client_id = client_id
super
end
# Creates a client.
def self.create(auth, company, timezone, country)
options = { :body => {
:CompanyName => company,
:TimeZone => timezone,
:Country => country }.to_json }
cs = CreateSend.new auth
cs.post "/clients.json", options
end
# Gets the details of this client.
def details
response = cs_get "/clients/#{client_id}.json", {}
Hashie::Mash.new(response)
end
# Gets the sent campaigns belonging to this client.
def campaigns(page=1, page_size=1000, order_direction="desc",
sent_from_date='', sent_to_date='', tags='')
options = { :query => {
:page => page,
:pagesize => page_size,
:orderdirection => order_direction,
:sentfromdate => sent_from_date,
:senttodate => sent_to_date,
:tags => tags
}}
response = get 'campaigns', options
Hashie::Mash.new(response)
end
# Gets the currently scheduled campaigns belonging to this client.
def scheduled
response = get 'scheduled'
response.map{|item| Hashie::Mash.new(item)}
end
# Gets the draft campaigns belonging to this client.
def drafts
response = get 'drafts'
response.map{|item| Hashie::Mash.new(item)}
end
# Gets all the tags belonging to this client.
def tags
response = get 'tags'
response.map{|item| Hashie::Mash.new(item)}
end
# Gets the subscriber lists belonging to this client.
def lists
response = get 'lists'
response.map{|item| Hashie::Mash.new(item)}
end
# Gets the lists across a client, to which a subscriber with a particular
# email address belongs.
# email_address - A String representing the subcriber's email address
def lists_for_email(email_address)
options = { :query => { :email => email_address } }
response = get 'listsforemail', options
response.map{|item| Hashie::Mash.new(item)}
end
# Gets the segments belonging to this client.
def segments
response = get 'segments'
response.map{|item| Hashie::Mash.new(item)}
end
# Gets the people associated with this client
def people
response = get "people"
response.map{|item| Hashie::Mash.new(item)}
end
def get_primary_contact
response = get "primarycontact"
Hashie::Mash.new(response)
end
def set_primary_contact(email)
options = { :query => { :email => email } }
response = put "primarycontact", options
Hashie::Mash.new(response)
end
# Gets this client's suppression list.
def suppressionlist(page=1, page_size=1000, order_field="email",
order_direction="asc")
options = { :query => {
:page => page,
:pagesize => page_size,
:orderfield => order_field,
:orderdirection => order_direction } }
response = get 'suppressionlist', options
Hashie::Mash.new(response)
end
# Adds email addresses to a client's suppression list
def suppress(emails)
options = { :body => {
:EmailAddresses => emails.kind_of?(String) ?
[ emails ] : emails }.to_json }
post "suppress", options
end
# Unsuppresses an email address by removing it from the the client's
# suppression list
def unsuppress(email)
options = { :query => { :email => email }, :body => '' }
put "unsuppress", options
end
# Gets the templates belonging to this client.
def templates
response = get 'templates'
response.map{|item| Hashie::Mash.new(item)}
end
# Sets the basic details for this client.
def set_basics(company, timezone, country)
options = { :body => {
:CompanyName => company,
:TimeZone => timezone,
:Country => country }.to_json }
put 'setbasics', options
end
# Sets the PAYG billing settings for this client.
def set_payg_billing(currency, can_purchase_credits, client_pays,
markup_percentage, markup_on_delivery=0, markup_per_recipient=0)
options = { :body => {
:Currency => currency,
:CanPurchaseCredits => can_purchase_credits,
:ClientPays => client_pays,
:MarkupPercentage => markup_percentage,
:MarkupOnDelivery => markup_on_delivery,
:MarkupPerRecipient => markup_per_recipient }.to_json }
put 'setpaygbilling', options
end
# Sets the monthly billing settings for this client.
# monthly_scheme must be nil, Basic or Unlimited
def set_monthly_billing(currency, client_pays, markup_percentage,
monthly_scheme = nil)
options = { :body => {
:Currency => currency,
:ClientPays => client_pays,
:MarkupPercentage => markup_percentage,
:MonthlyScheme => monthly_scheme }.to_json }
put 'setmonthlybilling', options
end
# Transfer credits to or from this client.
#
# credits - An Integer representing the number of credits to transfer.
# This value may be either positive if you want to allocate credits from
# your account to the client, or negative if you want to deduct credits
# from the client back into your account.
# can_use_my_credits_when_they_run_out - A Boolean value representing
# which, if set to true, will allow the client to continue sending using
# your credits or payment details once they run out of credits, and if
# set to false, will prevent the client from using your credits to
# continue sending until you allocate more credits to them.
#
# Returns an object of the following form representing the result:
# {
# AccountCredits # Integer representing credits in your account now
# ClientCredits # Integer representing credits in this client's
# account now
# }
def transfer_credits(credits, can_use_my_credits_when_they_run_out)
options = { :body => {
:Credits => credits,
:CanUseMyCreditsWhenTheyRunOut => can_use_my_credits_when_they_run_out
}.to_json }
response = post 'credits', options
Hashie::Mash.new(response)
end
# Deletes this client.
def delete
super "/clients/#{client_id}.json", {}
end
# Gets the journeys belonging to this client.
def journeys
response = get 'journeys'
response.map{|item| Hashie::Mash.new(item)}
end
private
def get(action, options = {})
super uri_for(action), options
end
def post(action, options = {})
super uri_for(action), options
end
def put(action, options = {})
super uri_for(action), options
end
def uri_for(action)
"/clients/#{client_id}/#{action}.json"
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/transactional_smart_email.rb | lib/createsend/transactional_smart_email.rb | module CreateSend
module Transactional
class SmartEmail < CreateSend
attr_reader :smart_email_id
def self.list(auth, options = nil)
cs = CreateSend.new auth
response = cs.get "/transactional/smartemail", :query => options
response.map{|item| Hashie::Mash.new(item)}
end
def initialize(auth, smart_email_id)
@auth = auth
@smart_email_id = smart_email_id
super
end
def details
response = get "/transactional/smartemail/#{@smart_email_id}"
Hashie::Mash.new(response)
end
def send(options)
response = post "/transactional/smartemail/#{@smart_email_id}/send", { :body => options.to_json }
response.map{|item| Hashie::Mash.new(item)}
end
end
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/administrator.rb | lib/createsend/administrator.rb | module CreateSend
# Represents an administrator and associated functionality.
class Administrator < CreateSend
attr_reader :email_address
def initialize(auth, email_address)
@email_address = email_address
super
end
# Gets an administrator by email address.
def self.get(auth, email_address)
options = { :query => { :email => email_address } }
cs = CreateSend.new auth
response = cs.cs_get "/admins.json", options
Hashie::Mash.new(response)
end
# Adds an administrator to the account.
def self.add(auth, email_address, name)
options = { :body => {
:EmailAddress => email_address,
:Name => name
}.to_json }
cs = CreateSend.new auth
response = cs.cs_post "/admins.json", options
Hashie::Mash.new(response)
end
# Updates the administator details.
def update(new_email_address, name)
options = {
:query => { :email => @email_address },
:body => {
:EmailAddress => new_email_address,
:Name => name
}.to_json }
put '/admins.json', options
# Update @email_address, so this object can continue to be used reliably
@email_address = new_email_address
end
# Deletes this administrator from the account.
def delete
options = { :query => { :email => @email_address } }
super '/admins.json', options
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/journey.rb | lib/createsend/journey.rb | module CreateSend
# Represents a journey and provides associated functionality
class Journey < CreateSend
attr_reader :journey_id
def initialize(auth, journey_id)
@journey_id = journey_id
super
end
# Get a full summary of a journey
def summary
response = get "/journeys/#{@journey_id}.json"
Hashie::Mash.new(response)
end
# Gets a list of all recipients of a particular email within a journey
def email_recipients(email_id="", date="", page=1, page_size=1000, order_direction='asc')
paged_result_by_date("recipients", email_id, date, page, page_size, order_direction)
end
# Gets a paged list of subscribers who opened a given journey email
def email_opens(email_id="", date="", page=1, page_size=1000, order_direction='asc')
paged_result_by_date("opens", email_id, date, page, page_size, order_direction)
end
# Gets a paged list of subscribers who clicked a given journey email
def email_clicks(email_id="", date="", page=1, page_size=1000, order_direction='asc')
paged_result_by_date("clicks", email_id, date, page, page_size, order_direction)
end
# Gets a paged result representing all subscribers who unsubscribed from a journey email
def email_unsubscribes(email_id="", date="", page=1, page_size=1000, order_direction='asc')
paged_result_by_date("unsubscribes", email_id, date, page, page_size, order_direction)
end
# Gets a paged result of all bounces for a journey email
def email_bounces(email_id="", date="", page=1, page_size=1000, order_direction='asc')
paged_result_by_date("bounces", email_id, date, page, page_size, order_direction)
end
private
def paged_result_by_date(resource, email_id, date, page, page_size, order_direction)
options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
:orderdirection => order_direction } }
response = get_journey_email_action email_id, resource, options
Hashie::Mash.new(response)
end
def get_journey_email_action(email_id, action, options = {})
get "/journeys/email/#{email_id}/#{action}.json", options
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/person.rb | lib/createsend/person.rb | module CreateSend
# Represents a person and associated functionality.
class Person < CreateSend
attr_reader :client_id
attr_reader :email_address
def initialize(auth, client_id, email_address)
@client_id = client_id
@email_address = email_address
super
end
# Gets a person by client ID and email address.
def self.get(auth, client_id, email_address)
options = { :query => { :email => email_address } }
cs = CreateSend.new auth
response = cs.get "/clients/#{client_id}/people.json", options
Hashie::Mash.new(response)
end
# Adds a person to the client. Password is optional. If ommitted, an
# email invitation will be sent to the person
def self.add(auth, client_id, email_address, name, access_level, password)
options = { :body => {
:EmailAddress => email_address,
:Name => name,
:AccessLevel => access_level,
:Password => password }.to_json }
cs = CreateSend.new auth
response = cs.post "/clients/#{client_id}/people.json", options
Hashie::Mash.new(response)
end
# Updates the person details. password is optional and will only be
# updated if supplied
def update(new_email_address, name, access_level, password)
options = {
:query => { :email => @email_address },
:body => {
:EmailAddress => new_email_address,
:Name => name,
:AccessLevel => access_level,
:Password => password }.to_json }
put uri_for(client_id), options
# Update @email_address, so this object can continue to be used reliably
@email_address = new_email_address
end
# deletes this person from the client
def delete
options = { :query => { :email => @email_address } }
super uri_for(client_id), options
end
def uri_for(client_id)
"/clients/#{client_id}/people.json"
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/transactional_classic_email.rb | lib/createsend/transactional_classic_email.rb | module CreateSend
module Transactional
class ClassicEmail < CreateSend
attr_accessor :options
def initialize(auth, client_id = nil)
@auth = auth
@client_id = client_id
super
end
def send(options)
response = post "/transactional/classicemail/send", { :body => options.to_json , :query => client_id }
response.map{|item| Hashie::Mash.new(item)}
end
def groups
response = get "/transactional/classicemail/groups", :query => client_id
response.map{|item| Hashie::Mash.new(item)}
end
private
def client_id
{:clientID => @client_id} if @client_id
end
end
end
end
| ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
campaignmonitor/createsend-ruby | https://github.com/campaignmonitor/createsend-ruby/blob/a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47/lib/createsend/campaign.rb | lib/createsend/campaign.rb | module CreateSend
# Represents a campaign and provides associated functionality.
class Campaign < CreateSend
attr_reader :campaign_id
def initialize(auth, campaign_id)
@campaign_id = campaign_id
super
end
# Creates a new campaign for a client.
# client_id - String representing the ID of the client for whom the
# campaign will be created.
# subject - String representing the subject of the campaign.
# name - String representing the name of the campaign.
# from_name - String representing the from name for the campaign.
# from_email - String representing the from address for the campaign.
# reply_to - String representing the reply-to address for the campaign.
# html_url - String representing the URL for the campaign HTML content.
# text_url - String representing the URL for the campaign text content.
# Note that text_url is optional and if nil or an empty string, text
# content will be automatically generated from the HTML content.
# list_ids - Array of Strings representing the IDs of the lists to
# which the campaign will be sent.
# segment_ids - Array of Strings representing the IDs of the segments to
# which the campaign will be sent.
def self.create(auth, client_id, subject, name, from_name, from_email,
reply_to, html_url, text_url, list_ids, segment_ids)
options = { :body => {
:Subject => subject,
:Name => name,
:FromName => from_name,
:FromEmail => from_email,
:ReplyTo => reply_to,
:HtmlUrl => html_url,
:TextUrl => text_url,
:ListIDs => list_ids,
:SegmentIDs => segment_ids }.to_json }
cs = CreateSend.new auth
response = cs.post "/campaigns/#{client_id}.json", options
response.parsed_response
end
# Creates a new campaign for a client, from a template.
# client_id - String representing the ID of the client for whom the
# campaign will be created.
# subject - String representing the subject of the campaign.
# name - String representing the name of the campaign.
# from_name - String representing the from name for the campaign.
# from_email - String representing the from address for the campaign.
# reply_to - String representing the reply-to address for the campaign.
# list_ids - Array of Strings representing the IDs of the lists to
# which the campaign will be sent.
# segment_ids - Array of Strings representing the IDs of the segments to
# which the campaign will be sent.
# template_id - String representing the ID of the template on which
# the campaign will be based.
# template_content - Hash representing the content to be used for the
# editable areas of the template. See documentation at
# campaignmonitor.com/api/campaigns/#creating_a_campaign_from_template
# for full details of template content format.
def self.create_from_template(auth, client_id, subject, name, from_name,
from_email, reply_to, list_ids, segment_ids, template_id,
template_content)
options = { :body => {
:Subject => subject,
:Name => name,
:FromName => from_name,
:FromEmail => from_email,
:ReplyTo => reply_to,
:ListIDs => list_ids,
:SegmentIDs => segment_ids,
:TemplateID => template_id,
:TemplateContent => template_content }.to_json }
cs = CreateSend.new auth
response = cs.post(
"/campaigns/#{client_id}/fromtemplate.json", options)
response.parsed_response
end
# Sends a preview of this campaign.
def send_preview(recipients, personalize="fallback")
options = { :body => {
:PreviewRecipients => recipients.kind_of?(String) ?
[ recipients ] : recipients,
:Personalize => personalize }.to_json }
post "sendpreview", options
end
# Sends this campaign.
def send(confirmation_email, send_date="immediately")
options = { :body => {
:ConfirmationEmail => confirmation_email,
:SendDate => send_date }.to_json }
post "send", options
end
# Unschedules this campaign if it is currently scheduled.
def unschedule
options = { :body => "" }
post "unschedule", options
end
# Deletes this campaign.
def delete
super "/campaigns/#{campaign_id}.json", {}
end
# Gets a summary of this campaign
def summary
response = get "summary", {}
Hashie::Mash.new(response)
end
# Gets the email clients that subscribers used to open the campaign
def email_client_usage
response = get "emailclientusage", {}
response.map{|item| Hashie::Mash.new(item)}
end
# Retrieves the lists and segments to which this campaaign will
# be (or was) sent.
def lists_and_segments
response = get "listsandsegments", {}
Hashie::Mash.new(response)
end
# Retrieves the recipients of this campaign.
def recipients(page=1, page_size=1000, order_field="email",
order_direction="asc")
options = { :query => {
:page => page,
:pagesize => page_size,
:orderfield => order_field,
:orderdirection => order_direction } }
response = get 'recipients', options
Hashie::Mash.new(response)
end
# Retrieves the opens for this campaign.
def opens(date="", page=1, page_size=1000, order_field="date",
order_direction="asc")
paged_result_by_date("opens", date, page, page_size, order_field,
order_direction)
end
# Retrieves the subscriber clicks for this campaign.
def clicks(date="", page=1, page_size=1000, order_field="date",
order_direction="asc")
paged_result_by_date("clicks", date, page, page_size, order_field,
order_direction)
end
# Retrieves the unsubscribes for this campaign.
def unsubscribes(date="", page=1, page_size=1000, order_field="date",
order_direction="asc")
paged_result_by_date("unsubscribes", date, page, page_size, order_field,
order_direction)
end
# Retrieves the spam complaints for this campaign.
def spam(date="", page=1, page_size=1000, order_field="date",
order_direction="asc")
paged_result_by_date("spam", date, page, page_size, order_field,
order_direction)
end
# Retrieves the bounces for this campaign.
def bounces(date="", page=1, page_size=1000, order_field="date",
order_direction="asc")
paged_result_by_date("bounces", date, page, page_size, order_field,
order_direction)
end
private
def paged_result_by_date(resource, date, page, page_size, order_field,
order_direction)
options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
:orderfield => order_field,
:orderdirection => order_direction } }
response = get resource, options
Hashie::Mash.new(response)
end
def get(action, options = {})
super uri_for(action), options
end
def post(action, options = {})
super uri_for(action), options
end
def uri_for(action)
"/campaigns/#{campaign_id}/#{action}.json"
end
end
end | ruby | MIT | a2f2ddbbd0845c6cbf1d20443000f0d319e9cc47 | 2026-01-04T17:53:12.263443Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/samples/tail-with-block.rb | samples/tail-with-block.rb | #!/usr/bin/env ruby
#
# Simple 'tail -f' example. This one uses a block instead of a separate handler
# class
# Usage example:
# tail-with-block.rb /var/log/messages
require "rubygems"
require "eventmachine"
require "eventmachine-tail"
def main(args)
if args.length == 0
puts "Usage: #{$0} <path> [path2] [...]"
return 1
end
EventMachine.run do
args.each do |path|
EventMachine::file_tail(path) do |filetail, line|
# filetail is the 'EventMachine::FileTail' instance for this file.
# line is the line read from thefile.
# this block is invoked for every line read.
puts line
end
end
end
end # def main
exit(main(ARGV))
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/samples/globwatch.rb | samples/globwatch.rb | #!/usr/bin/env ruby
require "rubygems"
require "eventmachine"
require "eventmachine-tail"
class Watcher < EventMachine::FileGlobWatch
def initialize(pathglob, interval=5)
super(pathglob, interval)
end
def file_deleted(path)
puts "Removed: #{path}"
end
def file_found(path)
puts "Found: #{path}"
end
def file_modified(path)
puts "Modified: #{path}"
end
end # class Watcher
EM.run do
Watcher.new("/var/log/*")
end
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/samples/glob-tail.rb | samples/glob-tail.rb | #!/usr/bin/env ruby
#
# Sample that uses eventmachine-tail to watch a file or set of files.
# Basically, this example implements 'tail -f' but can accept globs
# that are also watched.
#
# For example, '/var/log/*.log' will be periodically watched for new
# matching files which will additionally be watched.
#
# Usage example:
# glob-tail.rb "/var/log/*.log" "/var/log/httpd/*.log"
#
# (Important to use quotes or otherwise escape the '*' chars, otherwise
# your shell will interpret them)
require "rubygems"
require "eventmachine"
require "eventmachine-tail"
class Reader < EventMachine::FileTail
def initialize(path, startpos=-1)
super(path, startpos)
puts "Tailing #{path}"
@buffer = BufferedTokenizer.new
end
def receive_data(data)
@buffer.extract(data).each do |line|
puts "#{path}: #{line}"
end
end
end
def main(args)
if args.length == 0
puts "Usage: #{$0} <path_or_glob> [path_or_glob2] [...]"
return 1
end
EventMachine.run do
args.each do |path|
EventMachine::FileGlobWatchTail.new(path, Reader)
end
end
end # def main
exit(main(ARGV))
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/samples/tail.rb | samples/tail.rb | #!/usr/bin/env ruby
#
# Simple 'tail -f' example.
# Usage example:
# tail.rb /var/log/messages
require "rubygems"
require "eventmachine"
require "eventmachine-tail"
class Reader < EventMachine::FileTail
def initialize(path, startpos=-1)
super(path, startpos)
puts "Tailing #{path}"
@buffer = BufferedTokenizer.new
end
def receive_data(data)
@buffer.extract(data).each do |line|
puts "#{path}: #{line}"
end
end
end
def main(args)
if args.length == 0
puts "Usage: #{$0} <path> [path2] [...]"
return 1
end
EventMachine.run do
args.each do |path|
EventMachine::file_tail(path, Reader)
end
end
end # def main
exit(main(ARGV))
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/test/alltests.rb | test/alltests.rb | $: << File.expand_path('..', __FILE__)
require 'test_filetail'
require 'test_glob'
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/test/test_glob.rb | test/test_glob.rb | #!/usr/bin/env ruby
require 'rubygems'
$:.unshift "#{File.dirname(__FILE__)}/../lib"
require 'eventmachine-tail'
require 'tempfile'
require 'test/unit'
require 'timeout'
require 'tmpdir'
require 'testcase_helpers'
class Watcher < EventMachine::FileGlobWatch
def initialize(path, interval, data, testobj)
super(path, interval)
@data = data
@testobj = testobj
end # def initialize
def file_found(path)
# Use .include? here because files aren't going to be found in any
# particular order.
@testobj.assert(@data.include?(path), "Expected #{path} in \n#{@data.join("\n")}")
@data.delete(path)
@testobj.finish if @data.length == 0
end
def file_deleted(path)
@testobj.assert(@data.include?(path), "Expected #{path} in \n#{@data.join("\n")}")
@data.delete(path)
@testobj.finish if @data.length == 0
end
end # class Reader
class ModificationWatcher < EventMachine::FileGlobWatch
def initialize(path, interval, data, testobj)
super(path, interval)
@data = data
@testobj = testobj
end # def initialize
def file_found(path)
end
def file_deleted(patH)
end
def file_modified(path)
@testobj.assert(@data.include?(path), "Expected #{path} in \n#{@data.join("\n")}")
@data.delete(path)
@testobj.finish if @data.length == 0
end
end # class ModificationWatcher
class TestGlobWatcher < Test::Unit::TestCase
include EventMachineTailTestHelpers
SLEEPMAX = 1
def setup
@watchinterval = 0.2
@dir = Dir.mktmpdir
@data = []
@data << "#{@dir}/#{rand}"
@data << "#{@dir}/#{rand}"
@data << "#{@dir}/#{rand}"
@data << "#{@dir}/#{rand}"
@data << "#{@dir}/#{rand}"
@data << "#{@dir}/#{rand}"
@data << "#{@dir}/#{rand}"
@data << "#{@dir}/#{rand}.gz"
@data << "#{@dir}/#{rand}.gz"
@data << "#{@dir}/#{rand}.tar.gz"
end # def setup
def teardown
@data.each do |file|
#puts "Deleting #{file}"
File.delete(file) rescue nil
end
Dir.delete(@dir)
end # def teardown
def finish
EM.stop_event_loop
end
def test_glob_finds_existing_files
EM.run do
abort_after_timeout(SLEEPMAX * @data.length + 10)
@data.each do |path|
File.new(path, "w").close
end
EM::watch_glob("#{@dir}/*", Watcher, @watchinterval, @data.clone, self)
end # EM.run
end # def test_glob_finds_existing_files
# This test should run slow. We are trying to ensure that
# our file_tail correctly reads data slowly fed into the file
# as 'tail -f' would.
def test_glob_finds_newly_created_files_at_runtime
EM.run do
abort_after_timeout(SLEEPMAX * @data.length + 10)
EM::watch_glob("#{@dir}/*", Watcher, @watchinterval, @data.clone, self)
datacopy = @data.clone
timer = EM::PeriodicTimer.new(0.2) do
#puts "Creating: #{datacopy.first}"
File.new(datacopy.shift, "w").close
sleep(rand * SLEEPMAX)
timer.cancel if datacopy.length == 0
end
end # EM.run
end # def test_glob_finds_newly_created_files_at_runtime
def test_glob_ignores_file_renames
EM.run do
abort_after_timeout(SLEEPMAX * @data.length + 10)
EM::watch_glob("#{@dir}/*", Watcher, @watchinterval, @data.clone, self)
datacopy = @data.clone
timer = EM::PeriodicTimer.new(0.2) do
filename = datacopy.shift
File.new(filename, "w").close
sleep(rand * SLEEPMAX)
# This file rename should be ignored.
EM::Timer.new(2) do
newname = "#{filename}.renamed"
File.rename(filename, newname)
# Track the new filename so teardown removes it.
@data << newname
end
timer.cancel if datacopy.length == 0
end
end
end # def test_glob_ignores_file_renames
def test_glob_ignores_duplicate_hardlinks
EM.run do
abort_after_timeout(SLEEPMAX * @data.length + 10)
EM::watch_glob("#{@dir}/*", Watcher, @watchinterval, @data.clone, self)
datacopy = @data.clone
timer = EM::PeriodicTimer.new(0.2) do
filename = datacopy.shift
File.new(filename, "w").close
sleep(rand * SLEEPMAX)
# This file rename should be ignored.
EM::Timer.new(2) do
newname = "#{filename}.renamed"
File.link(filename, newname)
# Track the new filename so teardown removes it.
@data << newname
end
timer.cancel if datacopy.length == 0
end
end
end # def test_glob_ignores_file_renames
def test_glob_finds_modified_files_at_runtime
EM.run do
abort_after_timeout(SLEEPMAX * @data.length + 10)
datacopy = @data.clone
# To test if file edit is detected, file must exist first
datacopy.each do |filename|
File.new(filename, "w").close
end
EM::watch_glob("#{@dir}/*", ModificationWatcher, @watchinterval, @data.clone, self)
sleep(2) # Modification time resolution is 1 second, so we need to allow mtimes to change
timer = EM::PeriodicTimer.new(0.2) do
File.open(datacopy.shift, "w") do |f|
f.puts("LOLCAT!")
end
sleep(rand * SLEEPMAX)
timer.cancel if datacopy.length == 0
end
end # EM.run
end # def test_glob_finds_modified_files_at_runtime
end # class TestGlobWatcher
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/test/test_filetail.rb | test/test_filetail.rb | #!/usr/bin/env ruby
require 'rubygems'
$:.unshift "#{File.dirname(__FILE__)}/../lib"
require 'eventmachine-tail'
require 'tempfile'
require 'test/unit'
require 'timeout'
require 'testcase_helpers.rb'
# Generate some data
DATA = (1..10).collect { |i| rand.to_s }
SLEEPMAX = 1
class Reader < EventMachine::FileTail
def initialize(path, startpos=-1, testobj=nil)
super(path, startpos)
@data = DATA.clone
@buffer = BufferedTokenizer.new
@testobj = testobj
@lineno = 0
end # def initialize
def receive_data(data)
@buffer.extract(data).each do |line|
@lineno += 1
expected = @data.shift
@testobj.assert_equal(expected, line,
"Expected '#{expected}' on line #{@lineno}, but got '#{line}'")
end # @buffer.extract
end # def receive_data
# This effectively tests EOF handling by requiring it to work in order
# for the tests to pass.
def eof
if @data.length == 0
close
@testobj.finish
end
end # def eof
end # class Reader
class TestFileTail < Test::Unit::TestCase
include EventMachineTailTestHelpers
# This test should run slow. We are trying to ensure that
# our file_tail correctly reads data slowly fed into the file
# as 'tail -f' would.
def test_filetail
tmp = Tempfile.new("testfiletail")
data = DATA.clone
EM.run do
abort_after_timeout(DATA.length * SLEEPMAX + 10)
EM::file_tail(tmp.path, Reader, -1, self)
timer = EM::PeriodicTimer.new(0.2) do
tmp.puts data.shift
tmp.flush
sleep(rand * SLEEPMAX)
timer.cancel if data.length == 0
end
end # EM.run
end # def test_filetail
def test_filetail_close
tmp = Tempfile.new("testfiletail")
data = DATA.clone
data.each { |i| tmp.puts i }
tmp.flush
EM.run do
abort_after_timeout(2)
ft = EM::file_tail(tmp.path, Reader, -1, self)
ft.close
timer = EM::PeriodicTimer.new(0.2) do
timer.cancel and finish if ft.closed?
end
end # EM.run
end # def test_filetail_close
def test_filetail_with_seek
tmp = Tempfile.new("testfiletail")
data = DATA.clone
data.each { |i| tmp.puts i }
tmp.flush
EM.run do
abort_after_timeout(2)
# Set startpos of 0 (beginning of file)
EM::file_tail(tmp.path, Reader, 0, self)
end # EM.run
end # def test_filetail
def test_filetail_with_block
tmp = Tempfile.new("testfiletail")
data = DATA.clone
EM.run do
abort_after_timeout(DATA.length * SLEEPMAX + 10)
lineno = 0
EM::file_tail(tmp.path) do |filetail, line|
lineno += 1
expected = data.shift
assert_equal(expected, line,
"Expected '#{expected}' on line #{@lineno}, but got '#{line}'")
finish if data.length == 0
end
data_copy = data.clone
timer = EM::PeriodicTimer.new(0.2) do
tmp.puts data_copy.shift
tmp.flush
sleep(rand * SLEEPMAX)
timer.cancel if data_copy.length == 0
end
end # EM.run
end # def test_filetail_with_block
def test_filetail_tracks_renames
tmp = Tempfile.new("testfiletail")
data = DATA.clone
filename = tmp.path
data_copy = data.clone
# Write first so the first read happens immediately
tmp.puts data_copy.shift
tmp.flush
EM.run do
abort_after_timeout(DATA.length * SLEEPMAX + 10)
lineno = 0
# Start at file position 0.
EM::file_tail(tmp.path, nil, 0) do |filetail, line|
lineno += 1
expected = data.shift
#puts "Got #{lineno}: #{line}"
assert_equal(expected, line,
"Expected '#{expected}' on line #{lineno}, but got '#{line}'")
finish if data.length == 0
# Start a timer on the first read.
# This is to ensure we have the file tailing before
# we try to rename.
if lineno == 1
timer = EM::PeriodicTimer.new(0.2) do
value = data_copy.shift
tmp.puts value
tmp.flush
sleep(rand * SLEEPMAX)
# Rename the file, create a new one in it's place.
# This is to simulate log rotation, etc.
path_newname = "#{filename}_#{value}"
File.rename(filename, path_newname)
File.delete(path_newname)
tmp = File.open(filename, "w")
timer.cancel if data_copy.length == 0
end # timer
end # if lineno == 1
end # EM::filetail(...)
end # EM.run
File.delete(filename)
end # def test_filetail_tracks_renames
def test_filetail_tracks_symlink_changes
to_delete = []
link = Tempfile.new("testlink")
File.delete(link.path)
to_delete << link
tmp = Tempfile.new("testfiletail")
to_delete << tmp
data = DATA.clone
File.symlink(tmp.path, link.path)
data_copy = data.clone
# Write first so the first read happens immediately
tmp.puts data_copy.shift
tmp.flush
EM.run do
abort_after_timeout(DATA.length * SLEEPMAX + 10)
lineno = 0
# Start at file position 0.
EM::file_tail(link.path, nil, 0) do |filetail, line|
# This needs to be less than the interval at which we are changing symlinks.
filetail.symlink_check_interval = 0.1
lineno += 1
expected = data.shift
puts "Got #{lineno}: #{line}" if $debug
assert_equal(expected, line,
"Expected '#{expected}' on line #{lineno}, but got '#{line}'")
finish if data.length == 0
# Start a timer on the first read.
# This is to ensure we have the file tailing before
# we try to rename.
if lineno == 1
timer = EM::PeriodicTimer.new(0.2) do
value = data_copy.shift
tmp.puts value
tmp.flush
sleep(rand * SLEEPMAX)
# Make a new file and update the symlink to point to it.
# This is to simulate log rotation, etc.
tmp.close
tmp = Tempfile.new("testfiletail")
to_delete << tmp
File.delete(link.path)
File.symlink(tmp.path, link.path)
puts "#{tmp.path} => #{link.path}" if $debug
timer.cancel if data_copy.length == 0
end # timer
end # if lineno == 1
end # EM::filetail(...)
end # EM.run
to_delete.each do |f|
File.delete(f.path)
end
end # def test_filetail_tracks_renames
def test_encoding
return if RUBY_VERSION < '1.9.0'
tmp = Tempfile.new("testfiletail")
data = DATA.clone
EM.run do
abort_after_timeout(1)
EM::file_tail(tmp.path) do |filetail, line|
assert_equal(Encoding.default_external, line.encoding,
"Expected the read data to have the encoding specified in Encoding.default_external (#{Encoding.default_external}, but was #{line.encoding})")
finish
end
EM.next_tick do
tmp.puts(data.shift)
tmp.flush
end
end # EM.run
end # def test_encoding
end # class TestFileTail
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/test/testcase_helpers.rb | test/testcase_helpers.rb |
module EventMachineTailTestHelpers
def abort_after_timeout(seconds)
EM::Timer.new(seconds) do
EM.stop_event_loop
flunk("Timeout (#{seconds} seconds) while running tests. Failing.")
end
end
def finish
EventMachine.stop_event_loop
end
end # module EventMachineTailTestHelpers
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/lib/eventmachine-tail.rb | lib/eventmachine-tail.rb | require 'em/filetail'
require 'em/globwatcher'
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/lib/em/filetail.rb | lib/em/filetail.rb | #!/usr/bin/env ruby
require "eventmachine"
require "logger"
EventMachine.epoll if EventMachine.epoll?
EventMachine.kqueue = true if EventMachine.kqueue?
# Tail a file.
#
# Example
# class Tailer < EventMachine::FileTail
# def receive_data(data)
# puts "Got #{data.length} bytes"
# end
#
# # Optional
# def eof
# puts "Got EOF!"
# # If you want to stop
# stop
# end
# end
#
# # Now add it to EM
# EM.run do
# EM.file_tail("/var/log/messages", Tailer)
# end
#
# # Or this way:
# EM.run do
# Tailer.new("/var/log/messages")
# end
#
# See also: EventMachine::FileTail#receive_data
class EventMachine::FileTail
# Maximum size to read at a time from a single file.
CHUNKSIZE = 65536
#MAXSLEEP = 2
FORCE_ENCODING = !! (defined? Encoding)
# The path of the file being tailed
attr_reader :path
# The current file read position
attr_reader :position
# If this tail is closed
attr_reader :closed
# Check interval when checking symlinks for changes. This is only useful
# when you are actually tailing symlinks.
attr_accessor :symlink_check_interval
# Check interval for looking for a file if we are tailing it and it has
# gone missing.
attr_accessor :missing_file_check_interval
# Tail a file
#
# * path is a string file path to tail
# * startpos is an offset to start tailing the file at. If -1, start at end of
# file.
#
# If you want debug messages, run ruby with '-d' or set $DEBUG
#
# See also: EventMachine::file_tail
#
public
def initialize(path, startpos=-1, &block)
@path = path
@logger = Logger.new(STDERR)
@logger.level = ($DEBUG and Logger::DEBUG or Logger::WARN)
@logger.debug("Tailing #{path} starting at position #{startpos}")
@file = nil
@want_eof_handling = false
@want_read = false
@want_reopen = false
@reopen_on_eof = false
@symlink_timer = nil
@missing_file_check_timer = nil
@read_timer = nil
@symlink_target = nil
@symlink_stat = nil
@symlink_check_interval = 1
@missing_file_check_interval = 1
read_file_metadata
if @filestat.directory?
on_exception Errno::EISDIR.new(@path)
end
if block_given?
@handler = block
@buffer = BufferedTokenizer.new
end
EventMachine::next_tick do
open
next unless @file
if (startpos == -1)
@position = @file.sysseek(0, IO::SEEK_END)
# TODO(sissel): if we don't have inotify or kqueue, should we
# schedule a next read, here?
# Is there a race condition between setting the file position and
# watching given the two together are not atomic?
else
@position = @file.sysseek(startpos, IO::SEEK_SET)
schedule_next_read
end
watch
end # EventMachine::next_tick
end # def initialize
# This method is called when a tailed file has data read.
#
# * data - string data read from the file.
#
# If you want to read lines from your file, you should use BufferedTokenizer
# (which comes with EventMachine):
# class Tailer < EventMachine::FileTail
# def initialize(*args)
# super(*args)
# @buffer = BufferedTokenizer.new
# end
#
# def receive_data(data)
# @buffer.extract(data).each do |line|
# # do something with 'line'
# end
# end
public
def receive_data(data)
if @handler # FileTail.new called with a block
@buffer.extract(data).each do |line|
@handler.call(self, line)
end
else
on_exception NotImplementedError.new("#{self.class.name}#receive_data is not "\
"implemented. Did you forget to implement this in your subclass or "\
"module?")
end
end # def receive_data
def on_exception(exception)
@logger.error("Exception raised. Using default handler in #{self.class.name}")
raise exception
end
# This method is called when a tailed file reaches EOF.
#
# If you want to stop reading this file, call close(), otherwise
# this eof is handled as normal tailing does. The default
# EOF handler is to do nothing.
public
def eof
@logger.debug { 'EOF' }
# do nothing, subclassers should implement this.
end # def eof
# notify is invoked by EM::watch_file when the file you are tailing has been
# modified or otherwise needs to be acted on.
private
def notify(status)
@logger.debug { "notify: #{status} on #{path}" }
if status == :modified
schedule_next_read
elsif status == :moved
# read to EOF, then reopen.
schedule_next_read
elsif status == :unbind
# :unbind is called after the :deleted handler
# :deleted happens on FreeBSD's newsyslog instead of :moved
# clean up @watch since its reference is wiped in EM's file_deleted callback
@watch = nil
end
end # def notify
# Open (or reopen, if necessary) our file and schedule a read.
private
def open
return if @closed
@file.close if @file && !@file.closed?
return unless File.exist?(@path)
begin
@logger.debug "Opening file #{@path}"
@file = File.open(@path, "r")
rescue Errno::ENOENT => e
@logger.info("File not found: '#{@path}' (#{e})")
on_exception(e)
end
@naptime = 0
@logger.debug { 'EOF' }
@position = 0
schedule_next_read
end # def open
# Close this filetail
public
def close
@closed = true
@want_read = false
EM.schedule do
@watch.stop_watching if @watch
EventMachine::cancel_timer(@read_timer) if @read_timer
@symlink_timer.cancel if @symlink_timer
@missing_file_check_timer.cancel if @missing_file_check_timer
@file.close if @file
end
end # def close
# More rubyesque way of checking if this tail is closed
public
def closed?
@closed
end
# Watch our file.
private
def watch
@watch.stop_watching if @watch
@symlink_timer.cancel if @symlink_timer
return unless File.exist?(@path)
@logger.debug "Starting watch on #{@path}"
callback = proc { |what| notify(what) }
@watch = EventMachine::watch_file(@path, EventMachine::FileTail::FileWatcher, callback)
watch_symlink if @symlink_target
end # def watch
# Watch a symlink
# EM doesn't currently support watching symlinks alone (inotify follows
# symlinks by default), so let's periodically stat the symlink.
private
def watch_symlink(&block)
@symlink_timer.cancel if @symlink_timer
@logger.debug "Launching timer to check for symlink changes since EM can't right now: #{@path}"
@symlink_timer = EM::PeriodicTimer.new(@symlink_check_interval) do
begin
@logger.debug("Checking #{@path}")
read_file_metadata do |filestat, linkstat, linktarget|
handle_fstat(filestat, linkstat, linktarget)
end
rescue Errno::ENOENT
# The file disappeared. Wait for it to reappear.
# This can happen if it was deleted or moved during log rotation.
@logger.debug "File not found, waiting for it to reappear. (#{@path})"
end # begin/rescue ENOENT
end # EM::PeriodicTimer
end # def watch_symlink
private
def schedule_next_read
if !@want_read
@want_read = true
@read_timer = EventMachine::add_timer(@naptime) do
@want_read = false
read
end
end # if !@want_read
end # def schedule_next_read
# Read CHUNKSIZE from our file and pass it to .receive_data()
private
def read
return if @closed
data = nil
@logger.debug "#{self}: Reading..."
begin
data = @file.sysread(CHUNKSIZE)
rescue EOFError, IOError
schedule_eof
return
end
data.force_encoding(@file.external_encoding) if FORCE_ENCODING
# Won't get here if sysread throws EOF
@position += data.length
@naptime = 0
# Subclasses should implement receive_data
receive_data(data)
schedule_next_read
end # def read
# Do EOF handling on next EM iteration
private
def schedule_eof
if !@want_eof_handling
eof # Call our own eof event
@want_eof_handling = true
EventMachine::next_tick do
handle_eof
end # EventMachine::next_tick
end # if !@want_eof_handling
end # def schedule_eof
private
def schedule_reopen
if !@want_reopen
EventMachine::next_tick do
@want_reopen = false
open
watch
end
end # if !@want_reopen
end # def schedule_reopen
private
def handle_eof
@want_eof_handling = false
if @reopen_on_eof
@reopen_on_eof = false
schedule_reopen
end
# EOF actions:
# - Check if the file inode/device is changed
# - If symlink, check if the symlink has changed
# - Otherwise, do nothing
begin
read_file_metadata do |filestat, linkstat, linktarget|
handle_fstat(filestat, linkstat, linktarget)
end
rescue Errno::ENOENT
# The file disappeared. Wait for it to reappear.
# This can happen if it was deleted or moved during log rotation.
@missing_file_check_timer = EM::PeriodicTimer.new(@missing_file_check_interval) do
begin
read_file_metadata do |filestat, linkstat, linktarget|
handle_fstat(filestat, linkstat, linktarget)
end
@missing_file_check_timer.cancel
rescue Errno::ENOENT
# The file disappeared. Wait for it to reappear.
# This can happen if it was deleted or moved during log rotation.
@logger.debug "File not found, waiting for it to reappear. (#{@path})"
end # begin/rescue ENOENT
end # EM::PeriodicTimer
end # begin/rescue ENOENT
end # def handle_eof
private
def read_file_metadata(&block)
begin
filestat = File.stat(@path)
symlink_stat = nil
symlink_target = nil
if filestat.symlink?
symlink_stat = File.lstat(@path) rescue nil
symlink_target = File.readlink(@path) rescue nil
end
rescue Errno::ENOENT
raise
rescue => e
@logger.debug("File stat on '#{@path}' failed")
on_exception e
end
if block_given?
yield filestat, symlink_stat, symlink_target
end
@filestat = filestat
@symlink_stat = symlink_stat
@symlink_target = symlink_target
end # def read_file_metadata
# Handle fstat changes appropriately.
private
def handle_fstat(filestat, symlinkstat, symlinktarget)
# If the symlink target changes, the filestat.ino is very likely to have
# changed since that is the stat on the resolved file (that the link points
# to). However, we'll check explicitly for the symlink target changing
# for better debuggability.
if symlinktarget
if symlinkstat.ino != @symlink_stat.ino
@logger.debug "Inode or device changed on symlink. Reopening..."
@reopen_on_eof = true
schedule_next_read
elsif symlinktarget != @symlink_target
@logger.debug "Symlink target changed. Reopening..."
@reopen_on_eof = true
schedule_next_read
end
elsif (filestat.ino != @filestat.ino or filestat.rdev != @filestat.rdev)
@logger.debug "Inode or device changed. Reopening..."
@logger.debug filestat
@reopen_on_eof = true
schedule_next_read
elsif (filestat.size < @filestat.size)
# If the file size shrank, assume truncation and seek to the beginning.
@logger.info("File likely truncated... #{path}")
@position = @file.sysseek(0, IO::SEEK_SET)
schedule_next_read
end
end # def handle_fstat
def to_s
return "#{self.class.name}(#{@path}) @ pos:#{@position}"
end # def to_s
end # class EventMachine::FileTail
# Internal usage only. This class is used by EventMachine::FileTail
# to watch files you are tailing.
#
# See also: EventMachine::FileTail#watch
class EventMachine::FileTail::FileWatcher < EventMachine::FileWatch
def initialize(block)
@logger = Logger.new(STDERR)
@logger.level = ($DEBUG and Logger::DEBUG or Logger::WARN)
@callback = block
end # def initialize
def file_modified
@callback.call(:modified)
end # def file_modified
def file_moved
@callback.call(:moved)
end # def file_moved
def file_deleted
@callback.call(:deleted)
end # def file_deleted
def unbind
@callback.call(:unbind)
end # def unbind
end # class EventMachine::FileTail::FileWatch < EventMachine::FileWatch
# Add EventMachine::file_tail
module EventMachine
# Tail a file.
#
# path is the path to the file to tail.
# handler should be a module implementing 'receive_data' or
# must be a subclasses of EventMachine::FileTail
#
# For example:
# EM::file_tail("/var/log/messages", MyHandler)
#
# If a block is given, and the handler is not specified or does
# not implement EventMachine::FileTail#receive_data, then it
# will be called as such:
# EM::file_tail(...) do |filetail, line|
# # filetail is the FileTail instance watching the file
# # line is the line read from the file
# end
def self.file_tail(path, handler=nil, *args, &block)
# This code mostly styled on what EventMachine does in many of it's other
# methods.
args = [path, *args]
klass = klass_from_handler(EventMachine::FileTail, handler, *args);
c = klass.new(*args, &block)
return c
end # def self.file_tail
end # module EventMachine
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jordansissel/eventmachine-tail | https://github.com/jordansissel/eventmachine-tail/blob/aeebe12e641a0384100145558cd6449e9a69d3c0/lib/em/globwatcher.rb | lib/em/globwatcher.rb | #!/usr/bin/env ruby
require "em/filetail"
require "eventmachine"
require "logger"
require "set"
EventMachine.epoll if EventMachine.epoll?
EventMachine.kqueue = true if EventMachine.kqueue?
# A file glob pattern watcher for EventMachine.
#
# If you are unfamiliar with globs, see Wikipedia:
# http://en.wikipedia.org/wiki/Glob_(programming)
#
# Any glob supported by Dir#glob will work with
# this class.
#
# This class will allow you to get notified whenever a file
# is created or deleted that matches your glob.
#
# If you are subclassing, here are the methods you should implement:
# file_found(path)
# file_deleted(path)
#
# See alsoe
# * EventMachine::watch_glob
# * EventMachine::FileGlobWatch#file_found
# * EventMachine::FileGlobWatch#file_deleted
#
class EventMachine::FileGlobWatch
# Watch a glob
#
# * glob - a string path or glob, such as "/var/log/*.log"
# * interval - number of seconds between scanning the glob for changes
def initialize(glob, interval=60)
@glob = glob
@files = Hash.new
@watches = Hash.new
@logger = Logger.new(STDOUT)
@logger.level = ($DEBUG and Logger::DEBUG or Logger::WARN)
@interval = interval
start
end # def initialize
# This method may be called to stop watching
# TODO(sissel): make 'stop' stop all active watches, too?
public
def stop
@find_files_interval.cancel if @find_files_interval
end
# This method may be called to start watching
#
public
def start
# We periodically check here because it is easier than writing our own glob
# parser (so we can smartly watch globs like /foo/*/bar*/*.log)
#
# Reasons to fix this -
# This will likely perform badly on globs that result in a large number of
# files.
EM.next_tick do
find_files
@find_files_interval = EM.add_periodic_timer(@interval) do
find_files
end
end # EM.next_tick
end
# This method is called when a new file is found
#
# * path - the string path of the file found
#
# You must implement this in your subclass or module for it
# to work with EventMachine::watch_glob
public
def file_found(path)
raise NotImplementedError.new("#{self.class.name}#file_found is not "\
"implemented. Did you forget to implement this in your subclass or "\
"module?")
end # def file_found
# This method is called when a file is modified.
#
# * path - The string path of the file modified
#
# You AREN'T required to implement this in your sublcass or module
public
def file_modified(path)
end
# This method is called when a file is deleted.
#
# * path - the string path of the file deleted
#
# You must implement this in your subclass or module for it
# to work with EventMachine::watch_glob
public
def file_deleted(path)
raise NotImplementedError.new("#{self.class.name}#file_deleted is not "\
"implemented. Did you forget to implement this in your subclass or "\
"module?")
end # def file_found
private
def find_files
@logger.info("Searching for files in #{@glob}")
list = Dir.glob(@glob)
known_files = @files.clone
list.each do |path|
fileinfo = FileInfo.new(path) rescue next
# Skip files that have the same inode (renamed or hardlinked)
known_files.delete(fileinfo.stat.ino)
if @files.include?(fileinfo.stat.ino)
next unless modified(fileinfo)
file_modified(path)
end
track(fileinfo)
file_found(path)
end
# Report missing files.
known_files.each do |inode, fileinfo|
remove(fileinfo)
end
end # def find_files
# Remove a file from being watched and notify file_deleted()
private
def remove(fileinfo)
@files.delete(fileinfo.stat.ino)
@watches.delete(fileinfo.path)
file_deleted(fileinfo.path)
end # def remove
# Add a file to watch and notify file_found()
private
def track(fileinfo)
@files[fileinfo.stat.ino] = fileinfo
# If EventMachine::watch_file fails, that's ok, I guess.
# We'll still find the file 'missing' from the next glob attempt.
#begin
# EM currently has a bug that only the first handler for a watch_file
# on each file gets events. This causes globtails to never get data
# since the glob is watching the file already.
# Until we fix that, let's skip file watching here.
#@watches[path] = EventMachine::watch_file(path, FileWatcher, self) do |path|
# remove(path)
#end
#rescue Errno::EACCES => e
#@logger.warn(e)
#end
end # def watch
# Tells if a file has been modified since last time
def modified(fileinfo)
not @files[fileinfo.stat.ino].stat.mtime == fileinfo.stat.mtime
end
private
class FileWatcher < EventMachine::FileWatch
def initialize(globwatch, &block)
@globwatch = globwatch
@block = block
end
def file_moved
stop_watching
block.call path
end
def file_deleted
block.call path
end
end # class EventMachine::FileGlobWatch::FileWatcher < EventMachine::FileWatch
private
class FileInfo
attr_reader :path
attr_reader :stat
def initialize(path)
@path = path
@stat = File.stat(path)
end
end # class FileInfo
end # class EventMachine::FileGlobWatch
# A glob tailer for EventMachine
#
# This class combines features of EventMachine::file_tail and
# EventMachine::watch_glob.
#
# You won't generally subclass this class (See EventMachine::FileGlobWatch)
#
# See also: EventMachine::glob_tail
#
class EventMachine::FileGlobWatchTail < EventMachine::FileGlobWatch
# Initialize a new file glob tail.
#
# * path - glob or file path (string)
# * handler - a module or subclass of EventMachine::FileTail
# See also EventMachine::file_tail
# * interval - how often (seconds) the glob path should be scanned
# * exclude - an array of Regexp (or anything with .match) for
# excluding from things to tail
#
# The remainder of arguments are passed to EventMachine::file_tail as
# EventMachine::file_tail(path_found, handler, *args, &block)
public
def initialize(path, handler=nil, interval=60, exclude=[], *args, &block)
super(path, interval)
@handler = handler
@args = args
@exclude = exclude
if block_given?
@handler = block
end
end # def initialize
public
def file_found(path)
begin
@logger.info "#{self.class}: Trying #{path}"
@exclude.each do |exclude|
@logger.info "#{self.class}: Testing #{exclude} =~ #{path} == #{exclude.match(path) != nil}"
if exclude.match(path) != nil
file_excluded(path)
return
end
end
@logger.info "#{self.class}: Watching #{path}"
if @handler.is_a? Proc
EventMachine::file_tail(path, nil, *@args, &@handler)
else
EventMachine::file_tail(path, @handler, *@args)
end
rescue Errno::EACCES => e
file_error(path, e)
rescue Errno::EISDIR => e
file_error(path, e)
end
end # def file_found
public
def file_excluded(path)
@logger.info "#{self.class}: Skipping path #{path} due to exclude rule"
end # def file_excluded
public
def file_deleted(path)
# Nothing to do
end # def file_deleted
public
def file_error(path, e)
$stderr.puts "#{e.class} while trying to tail #{path}"
# otherwise, drop the error by default
end # def file_error
end # class EventMachine::FileGlobWatchHandler
module EventMachine
# Watch a glob and tail any files found.
#
# * glob - a string path or glob, such as /var/log/*.log
# * handler - a module or subclass of EventMachine::FileGlobWatchTail.
# handler can be omitted if you give a block.
#
# If you give a block and omit the handler parameter, then the behavior
# is that your block is called for every line read from any file the same
# way EventMachine::file_tail does when called with a block.
#
# See EventMachine::FileGlobWatchTail for the callback methods.
# See EventMachine::file_tail for more information about block behavior.
def self.glob_tail(glob, handler=nil, *args, &block)
handler = EventMachine::FileGlobWatchTail if handler == nil
args.unshift(glob)
klass = klass_from_handler(EventMachine::FileGlobWatchTail, handler, *args)
c = klass.new(*args, &block)
return c
end
# Watch a glob for any files.
#
# * glob - a string path or glob, such as "/var/log/*.log"
# * handler - must be a module or a subclass of EventMachine::FileGlobWatch
#
# The remaining (optional) arguments are passed to your handler like this:
# If you call this:
# EventMachine.watch_glob("/var/log/*.log", YourHandler, 1, 2, 3, ...)
# This will be invoked when new matching files are found:
# YourHandler.new(path_found, 1, 2, 3, ...)
# ^ path_found is the new path found by the glob
#
# See EventMachine::FileGlobWatch for the callback methods.
def self.watch_glob(glob, handler=nil, *args)
# This code mostly styled on what EventMachine does in many of it's other
# methods.
args = [glob, *args]
klass = klass_from_handler(EventMachine::FileGlobWatch, handler, *args);
c = klass.new(*args)
yield c if block_given?
return c
end # def EventMachine::watch_glob
end # module EventMachine
| ruby | BSD-3-Clause | aeebe12e641a0384100145558cd6449e9a69d3c0 | 2026-01-04T17:53:34.880532Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/candy_check_spec.rb | spec/candy_check_spec.rb | require "spec_helper"
describe CandyCheck do
subject { CandyCheck }
it "has a version" do
_(subject::VERSION).wont_be_nil
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/spec_helper.rb | spec/spec_helper.rb | require "candy_check"
require "candy_check/cli"
def in_continuous_integration_environment?
ENV["CI"] || ENV["TRAVIS"] || ENV["CONTINUOUS_INTEGRATION"]
end
require "simplecov"
SimpleCov.start do
if in_continuous_integration_environment?
require "simplecov-lcov"
SimpleCov::Formatter::LcovFormatter.config do |c|
c.report_with_single_file = true
c.single_report_path = "coverage/lcov.info"
end
formatter SimpleCov::Formatter::LcovFormatter
end
end
require "minitest/autorun"
require "minitest/around/spec"
require "minitest/focus" unless in_continuous_integration_environment?
require "webmock/minitest"
require "vcr"
require "timecop"
require "pry"
require_relative "support/with_fixtures"
require_relative "support/with_temp_file"
require_relative "support/with_command"
ENV["DEBUG"] && Google::APIClient.logger.level = Logger::DEBUG
module Minitest
module Assertions
# The first parameter must be ```true```, not coercible to true.
def assert_true(obj, msg = nil)
msg = message(msg) { "<true> expected but was #{mu_pp obj}" }
assert obj == true, msg
end
# The first parameter must be ```false```, not just coercible to false.
def assert_false(obj, msg = nil)
msg = message(msg) { "<false> expected but was #{mu_pp obj}" }
assert obj == false, msg
end
end
module Expectations
infect_an_assertion :assert_true, :must_be_true, :unary
infect_an_assertion :assert_false, :must_be_false, :unary
end
end
VCR.configure do |config|
config.cassette_library_dir = "spec/fixtures/vcr_cassettes"
config.hook_into :webmock
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/app_store/verification_spec.rb | spec/app_store/verification_spec.rb | require "spec_helper"
describe CandyCheck::AppStore::Verification do
subject { CandyCheck::AppStore::Verification.new(endpoint, data, secret) }
let(:endpoint) { "https://some.endpoint" }
let(:data) { "some_data" }
let(:secret) { "some_secret" }
it "returns a verification failure for status != 0" do
with_mocked_response("status" => 21_000) do |client, recorded|
result = subject.call!
_(client.receipt_data).must_equal data
_(client.secret).must_equal secret
_(recorded.first).must_equal [endpoint]
_(result).must_be_instance_of CandyCheck::AppStore::VerificationFailure
_(result.code).must_equal 21_000
end
end
it "returns a verification failure when receipt is missing" do
with_mocked_response({}) do |client, recorded|
result = subject.call!
_(client.receipt_data).must_equal data
_(client.secret).must_equal secret
_(recorded.first).must_equal [endpoint]
_(result).must_be_instance_of CandyCheck::AppStore::VerificationFailure
_(result.code).must_equal(-1)
end
end
it "returns a receipt when status is 0 and receipt exists" do
response = { "status" => 0, "receipt" => { "item_id" => "some_id" } }
with_mocked_response(response) do
result = subject.call!
_(result).must_be_instance_of CandyCheck::AppStore::Receipt
_(result.item_id).must_equal("some_id")
end
end
private
let(:dummy_client_class) do
Struct.new(:response) do
attr_reader :receipt_data, :secret
def verify(receipt_data, secret)
@receipt_data = receipt_data
@secret = secret
response
end
end
end
def with_mocked_response(response)
recorded = []
dummy = dummy_client_class.new(response)
stub = proc do |*args|
recorded << args
dummy
end
CandyCheck::AppStore::Client.stub :new, stub do
yield dummy, recorded
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/app_store/client_spec.rb | spec/app_store/client_spec.rb | require "spec_helper"
describe CandyCheck::AppStore::Client do
let(:endpoint_url) { "https://some.endpoint.com/verify" }
let(:receipt_data) do
"some_very_long_receipt_information_which_is_normaly_base64_encoded"
end
let(:password) do
"some_secret_password"
end
let(:response) do
'{
"receipt": {
"item_id": "521129812"
},
"status": 0
}'
end
let(:expected) do
{
"status" => 0,
"receipt" => {
"item_id" => "521129812",
},
}
end
subject { CandyCheck::AppStore::Client.new(endpoint_url) }
describe "valid response" do
it "sends JSON and parses the JSON response without a secret" do
stub_endpoint
.with(
body: {
"receipt-data" => receipt_data,
},
)
.to_return(
body: response,
)
result = subject.verify(receipt_data)
_(result).must_equal expected
end
it "sends JSON and parses the JSON response with a secret" do
stub_endpoint
.with(
body: {
"receipt-data" => receipt_data,
"password" => password,
},
)
.to_return(
body: response,
)
result = subject.verify(receipt_data, password)
_(result).must_equal expected
end
end
private
def stub_endpoint
stub_request(:post, endpoint_url)
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/app_store/receipt_spec.rb | spec/app_store/receipt_spec.rb | require "spec_helper"
describe CandyCheck::AppStore::Receipt do
subject { CandyCheck::AppStore::Receipt.new(attributes) }
let(:attributes) do
{
"original_purchase_date_pst" => "2015-01-08 03:40:46" \
" America/Los_Angeles",
"purchase_date_ms" => "1420803646868",
"unique_identifier" => "some_uniq_identifier_from_apple" \
"_for_this",
"original_transaction_id" => "some_original_transaction_id",
"bvrs" => "2.0",
"transaction_id" => "some_transaction_id",
"quantity" => "1",
"unique_vendor_identifier" => "00000000-1111-2222-3333-" \
"444444444444",
"item_id" => "some_item_id",
"product_id" => "some_product",
"purchase_date" => "2015-01-09 11:40:46 Etc/GMT",
"original_purchase_date" => "2015-01-08 11:40:46 Etc/GMT",
"purchase_date_pst" => "2015-01-09 03:40:46" \
" America/Los_Angeles",
"bid" => "some.test.app",
"original_purchase_date_ms" => "1420717246868",
"expires_date" => "2016-06-09 13:59:40 Etc/GMT",
"is_trial_period" => "false",
}
end
describe "valid transaction" do
it "is valid" do
_(subject.valid?).must_be_true
end
it "returns the item's id" do
_(subject.item_id).must_equal "some_item_id"
end
it "returns the item's product_id" do
_(subject.product_id).must_equal "some_product"
end
it "returns the quantity" do
_(subject.quantity).must_equal 1
end
it "returns the app version" do
_(subject.app_version).must_equal "2.0"
end
it "returns the bundle identifier" do
_(subject.bundle_identifier).must_equal "some.test.app"
end
it "returns the purchase date" do
expected = DateTime.new(2015, 1, 9, 11, 40, 46)
_(subject.purchase_date).must_equal expected
end
it "returns the original purchase date" do
expected = DateTime.new(2015, 1, 8, 11, 40, 46)
_(subject.original_purchase_date).must_equal expected
end
it "returns the transaction id" do
_(subject.transaction_id).must_equal "some_transaction_id"
end
it "returns the original transaction id" do
_(subject.original_transaction_id).must_equal "some_original_transaction_id"
end
it "return nil for cancellation date" do
_(subject.cancellation_date).must_be_nil
end
it "returns raw attributes" do
_(subject.attributes).must_be_same_as attributes
end
it "returns the subscription expiration date" do
expected = DateTime.new(2016, 6, 9, 13, 59, 40)
_(subject.expires_date).must_equal expected
end
it "returns the trial status" do
_(subject.is_trial_period).must_be_false
end
end
describe "valid transaction" do
before do
attributes["cancellation_date"] = "2015-01-12 11:40:46 Etc/GMT"
end
it "isn't valid" do
_(subject.valid?).must_be_false
end
it "return nil for cancellation date" do
expected = DateTime.new(2015, 1, 12, 11, 40, 46)
_(subject.cancellation_date).must_equal expected
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/app_store/subscription_verification_spec.rb | spec/app_store/subscription_verification_spec.rb | require "spec_helper"
describe CandyCheck::AppStore::SubscriptionVerification do
subject do
CandyCheck::AppStore::SubscriptionVerification.new(endpoint, data, secret)
end
let(:endpoint) { "https://some.endpoint" }
let(:data) { "some_data" }
let(:secret) { "some_secret" }
it "returns a verification failure for status != 0" do
with_mocked_response("status" => 21_000) do |client, recorded|
result = subject.call!
_(client.receipt_data).must_equal data
_(client.secret).must_equal secret
_(recorded.first).must_equal [endpoint]
_(result).must_be_instance_of CandyCheck::AppStore::VerificationFailure
_(result.code).must_equal 21_000
end
end
it "returns a verification failure when receipt is missing" do
with_mocked_response({}) do |client, recorded|
result = subject.call!
_(client.receipt_data).must_equal data
_(client.secret).must_equal secret
_(recorded.first).must_equal [endpoint]
_(result).must_be_instance_of CandyCheck::AppStore::VerificationFailure
_(result.code).must_equal(-1)
end
end
it "returns a collection of receipt when status is 0 and receipts exists" do
response = {
"status" => 0,
"latest_receipt_info" => [
{ "item_id" => "some_id", "purchase_date" => "2016-04-15 12:52:40 Etc/GMT" },
{ "item_id" => "some_other_id", "purchase_date" => "2016-04-15 12:52:40 Etc/GMT" },
],
}
with_mocked_response(response) do
result = subject.call!
_(result).must_be_instance_of CandyCheck::AppStore::ReceiptCollection
_(result.receipts).must_be_instance_of Array
_(result.receipts.size).must_equal(2)
last = result.receipts.last
_(last).must_be_instance_of CandyCheck::AppStore::Receipt
_(last.item_id).must_equal("some_other_id")
end
end
describe "filtered product_ids" do
subject do
CandyCheck::AppStore::SubscriptionVerification.new(
endpoint,
data,
secret,
product_ids,
)
end
let(:product_ids) { ["product_1"] }
it "returns only filtered reciepts when specifc product_ids are reqested" do
response = {
"status" => 0,
"latest_receipt_info" => [
{ "item_id" => "some_id", "product_id" => "product_1", "purchase_date" => "2016-04-15 12:52:40 Etc/GMT" },
{ "item_id" => "some_other_id", "product_id" => "product_1",
"purchase_date" => "2016-04-15 12:52:40 Etc/GMT" },
{ "item_id" => "some_id", "product_id" => "product_2", "purchase_date" => "2016-04-15 12:52:40 Etc/GMT" },
],
}
with_mocked_response(response) do
result = subject.call!
_(result).must_be_instance_of CandyCheck::AppStore::ReceiptCollection
_(result.receipts).must_be_instance_of Array
_(result.receipts.size).must_equal(2)
last = result.receipts.last
_(last).must_be_instance_of CandyCheck::AppStore::Receipt
_(last.item_id).must_equal("some_other_id")
end
end
end
private
let(:dummy_client_class) do
Struct.new(:response) do
attr_reader :receipt_data, :secret
def verify(receipt_data, secret)
@receipt_data = receipt_data
@secret = secret
response
end
end
end
def with_mocked_response(response)
recorded = []
dummy = dummy_client_class.new(response)
stub = proc do |*args|
recorded << args
dummy
end
CandyCheck::AppStore::Client.stub :new, stub do
yield dummy, recorded
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/app_store/verifcation_failure_spec.rb | spec/app_store/verifcation_failure_spec.rb | require "spec_helper"
describe CandyCheck::AppStore::VerificationFailure do
subject { CandyCheck::AppStore::VerificationFailure }
let(:known) do
[21_000, 21_002, 21_003, 21_004, 21_005, 21_006, 21_007, 21_008]
end
it "fetched an failure with message for every known code" do
known.each do |code|
got = subject.fetch(code)
_(got.code).must_equal code
_(got.message).wont_equal "Unknown error"
end
end
it "fetched an failure for unknown codes" do
got = subject.fetch(1234)
_(got.code).must_equal 1234
_(got.message).must_equal "Unknown error"
end
it "fetched an failure for nil code" do
got = subject.fetch(nil)
_(got.code).must_equal(-1)
_(got.message).must_equal "Unknown error"
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/app_store/config_spec.rb | spec/app_store/config_spec.rb | require "spec_helper"
describe CandyCheck::AppStore::Config do
subject { CandyCheck::AppStore::Config.new(attributes) }
describe "valid" do
let(:attributes) do
{
environment: :sandbox,
}
end
it "returns environment" do
_(subject.environment).must_equal :sandbox
end
it "checks for production?" do
_(subject.production?).must_be_false
other = CandyCheck::AppStore::Config.new(
environment: :production,
)
_(other.production?).must_be_true
end
end
describe "invalid" do
let(:attributes) do
{}
end
it "needs an environment" do
_(proc { subject }).must_raise ArgumentError
end
it "needs an included environment" do
attributes[:environment] = :invalid
_(proc { subject }).must_raise ArgumentError
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/app_store/verifier_spec.rb | spec/app_store/verifier_spec.rb | require "spec_helper"
describe CandyCheck::AppStore::Verifier do
subject { CandyCheck::AppStore::Verifier.new(config) }
let(:config) do
CandyCheck::AppStore::Config.new(environment: environment)
end
let(:environment) { :production }
let(:data) { "some_data" }
let(:secret) { "some_secret" }
let(:receipt) { CandyCheck::AppStore::Receipt.new({}) }
let(:receipt_collection) { CandyCheck::AppStore::ReceiptCollection.new({}) }
let(:production_endpoint) do
"https://buy.itunes.apple.com/verifyReceipt"
end
let(:sandbox_endpoint) do
"https://sandbox.itunes.apple.com/verifyReceipt"
end
it "holds the config" do
_(subject.config).must_be_same_as config
end
describe "sandbox" do
let(:environment) { :sandbox }
it "uses sandbox endpoint without retry on success" do
with_mocked_verifier(receipt) do
_(subject.verify(data, secret)).must_be_same_as receipt
assert_recorded([sandbox_endpoint, data, secret])
end
end
it "only uses sandbox endpoint for normal failures" do
failure = get_failure(21_000)
with_mocked_verifier(failure) do
_(subject.verify(data, secret)).must_be_same_as failure
assert_recorded([sandbox_endpoint, data, secret])
end
end
it "retries production endpoint for redirect error" do
failure = get_failure(21_008)
with_mocked_verifier(failure, receipt) do
_(subject.verify(data, secret)).must_be_same_as receipt
assert_recorded(
[sandbox_endpoint, data, secret],
[production_endpoint, data, secret],
)
end
end
end
describe "production" do
let(:environment) { :production }
it "uses production endpoint without retry on success" do
with_mocked_verifier(receipt) do
_(subject.verify(data, secret)).must_be_same_as receipt
assert_recorded([production_endpoint, data, secret])
end
end
it "only uses production endpoint for normal failures" do
failure = get_failure(21_000)
with_mocked_verifier(failure) do
_(subject.verify(data, secret)).must_be_same_as failure
assert_recorded([production_endpoint, data, secret])
end
end
it "retries production endpoint for redirect error" do
failure = get_failure(21_007)
with_mocked_verifier(failure, receipt) do
_(subject.verify(data, secret)).must_be_same_as receipt
assert_recorded(
[production_endpoint, data, secret],
[sandbox_endpoint, data, secret],
)
end
end
end
describe "subscription" do
let(:environment) { :production }
it "uses production endpoint without retry on success" do
with_mocked_verifier(receipt_collection) do
_(subject.verify_subscription(
data, secret
)).must_be_same_as receipt_collection
assert_recorded([production_endpoint, data, secret, nil])
end
end
it "only uses production endpoint for normal failures" do
failure = get_failure(21_000)
with_mocked_verifier(failure) do
_(subject.verify_subscription(data, secret)).must_be_same_as failure
assert_recorded([production_endpoint, data, secret, nil])
end
end
it "retries production endpoint for redirect error" do
failure = get_failure(21_007)
with_mocked_verifier(failure, receipt) do
_(subject.verify_subscription(data, secret)).must_be_same_as receipt
assert_recorded(
[production_endpoint, data, secret, nil],
[sandbox_endpoint, data, secret, nil],
)
end
end
it "passed the product_ids" do
product_ids = ["product_1"]
with_mocked_verifier(receipt_collection) do
_(subject.verify_subscription(
data, secret, product_ids
)).must_be_same_as receipt_collection
assert_recorded([production_endpoint, data, secret, product_ids])
end
end
end
private
let(:dummy_verification_class) do
Struct.new(:endpoint, :data, :secret, :product_ids) do
attr_accessor :results
def call!
results.shift
end
end
end
def with_mocked_verifier(*results, &block)
@recorded ||= []
stub = proc do |*args|
@recorded << args
dummy_verification_class.new(*args).tap { |v| v.results = results }
end
CandyCheck::AppStore::Verification.stub :new, stub, &block
end
def assert_recorded(*calls)
_(@recorded).must_equal calls
end
def get_failure(code)
CandyCheck::AppStore::VerificationFailure.fetch(code)
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/app_store/receipt_collection_spec.rb | spec/app_store/receipt_collection_spec.rb | require "spec_helper"
describe CandyCheck::AppStore::ReceiptCollection do
subject { CandyCheck::AppStore::ReceiptCollection.new(attributes) }
describe "overdue subscription" do
let(:attributes) do
[{
"expires_date" => "2014-04-15 12:52:40 Etc/GMT",
"expires_date_pst" => "2014-04-15 05:52:40 America/Los_Angeles",
"purchase_date" => "2014-04-14 12:52:40 Etc/GMT",
"is_trial_period" => "false",
}, {
"expires_date" => "2015-04-15 12:52:40 Etc/GMT",
"expires_date_pst" => "2015-04-15 05:52:40 America/Los_Angeles",
"purchase_date" => "2015-04-14 12:52:40 Etc/GMT",
"is_trial_period" => "false",
}]
end
it "is expired" do
_(subject.expired?).must_be_true
end
it "is not a trial" do
_(subject.trial?).must_be_false
end
it "has positive overdue days" do
overdue = subject.overdue_days
_(overdue).must_be_instance_of Integer
assert overdue > 0
end
it "has a last expires date" do
expected = DateTime.new(2015, 4, 15, 12, 52, 40)
_(subject.expires_at).must_equal expected
end
it "is expired? at same pointin time" do
Timecop.freeze(Time.utc(2015, 4, 15, 12, 52, 40)) do
_(subject.expired?).must_be_true
end
end
end
describe "unordered receipts" do
let(:attributes) do
[{
"expires_date" => "2015-04-15 12:52:40 Etc/GMT",
"expires_date_pst" => "2015-04-15 05:52:40 America/Los_Angeles",
"purchase_date" => "2015-04-14 12:52:40 Etc/GMT",
"is_trial_period" => "false",
}, {
"expires_date" => "2014-04-15 12:52:40 Etc/GMT",
"expires_date_pst" => "2014-04-15 05:52:40 America/Los_Angeles",
"purchase_date" => "2014-04-14 12:52:40 Etc/GMT",
"is_trial_period" => "false",
}]
end
it "the expires date is the latest one in time" do
expected = DateTime.new(2015, 4, 15, 12, 52, 40)
_(subject.expires_at).must_equal expected
end
end
describe "unexpired trial subscription" do
two_days_from_now = DateTime.now + 2
let(:attributes) do
[{
"expires_date" => "2016-04-15 12:52:40 Etc/GMT",
"purchase_date" => "2016-04-15 12:52:40 Etc/GMT",
"is_trial_period" => "true",
}, {
"expires_date" =>
two_days_from_now.strftime("%Y-%m-%d %H:%M:%S Etc/GMT"),
"purchase_date" => "2016-04-15 12:52:40 Etc/GMT",
"is_trial_period" => "true",
}]
end
it "has not expired" do
_(subject.expired?).must_be_false
end
it "it is a trial" do
_(subject.trial?).must_be_true
end
it "expires in two days" do
_(subject.overdue_days).must_equal(-2)
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/support/with_fixtures.rb | spec/support/with_fixtures.rb | module WithFixtures
def fixture_path(*args)
File.join(File.expand_path('../../fixtures', __FILE__), *args)
end
def fixture_content(*args)
File.read(fixture_path(*args))
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/support/with_temp_file.rb | spec/support/with_temp_file.rb | require 'tempfile'
module WithTempFile
def self.included(target)
target.instance_eval do
def self.with_temp_file(name)
random_name = "#{name}-#{rand(100_000..200_000)}"
full_path = File.join(Dir.tmpdir, random_name)
define_method "#{name}_path" do
full_path
end
define_method "unlink_#{name}" do
return unless File.exist?(full_path)
File.unlink(full_path)
end
after do
send("unlink_#{name}")
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/support/with_command.rb | spec/support/with_command.rb | module WithCommand
def out
@out ||= OutRecorder.new
end
def run_command!
CandyCheck::CLI::Out.stub :new, out do
subject.run(*arguments)
end
end
def arguments
[]
end
class OutRecorder
def lines
@lines ||= []
end
def print(text = '')
lines << text
end
def pretty(object)
lines << object
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/acknowledger_spec.rb | spec/play_store/acknowledger_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::Acknowledger do
let(:json_key_file) { File.expand_path("../fixtures/play_store/random_dummy_key.json", __dir__) }
subject { CandyCheck::PlayStore::Acknowledger.new(authorization: authorization) }
let(:package_name) { "fake_package_name" }
let(:product_id) { "fake_product_id" }
let(:token) { "fake_token" }
let(:authorization) { CandyCheck::PlayStore.authorization(json_key_file) }
describe "#acknowledge_product_purchase" do
it "when acknowledgement succeeds" do
VCR.use_cassette("play_store/product_acknowledgements/acknowledged") do
result = subject.acknowledge_product_purchase(package_name: package_name, product_id: product_id, token: token)
_(result).must_be_instance_of CandyCheck::PlayStore::ProductAcknowledgements::Response
_(result.acknowledged?).must_be_true
_(result.error).must_be_nil
end
end
it "when already acknowledged" do
# rubocop:disable Layout/LineLength
error_body = "{\n \"error\": {\n \"code\": 400,\n \"message\": \"The purchase is not in a valid state to perform the desired operation.\",\n \"errors\": [\n {\n \"message\": \"The purchase is not in a valid state to perform the desired operation.\",\n \"domain\": \"androidpublisher\",\n \"reason\": \"invalidPurchaseState\",\n \"location\": \"token\",\n \"locationType\": \"parameter\"\n }\n ]\n }\n}\n"
# rubocop:enable Layout/LineLength
VCR.use_cassette("play_store/product_acknowledgements/already_acknowledged") do
result = subject.acknowledge_product_purchase(package_name: package_name, product_id: product_id, token: token)
_(result).must_be_instance_of CandyCheck::PlayStore::ProductAcknowledgements::Response
_(result.acknowledged?).must_be_false
_(result.error[:body]).must_equal(error_body)
_(result.error[:status_code]).must_equal(400)
end
end
it "when it has been refunded" do
# rubocop:disable Layout/LineLength
error_body = "{\n \"error\": {\n \"code\": 400,\n \"message\": \"The product purchase is not owned by the user.\",\n \"errors\": [\n {\n \"message\": \"The product purchase is not owned by the user.\",\n \"domain\": \"androidpublisher\",\n \"reason\": \"productNotOwnedByUser\"\n }\n ]\n }\n}\n"
# rubocop:enable Layout/LineLength
VCR.use_cassette("play_store/product_acknowledgements/refunded") do
result = subject.acknowledge_product_purchase(package_name: package_name, product_id: product_id, token: token)
_(result).must_be_instance_of CandyCheck::PlayStore::ProductAcknowledgements::Response
_(result.acknowledged?).must_be_false
_(result.error[:body]).must_equal(error_body)
_(result.error[:status_code]).must_equal(400)
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/verification_failure_spec.rb | spec/play_store/verification_failure_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::VerificationFailure do
subject { CandyCheck::PlayStore::VerificationFailure.new(fake_error) }
let(:fake_error_class) do
Struct.new(:status_code, :message)
end
describe "denied" do
let(:fake_error) do
fake_error_class.new("401", "The current user has insufficient permissions")
end
it "returns the code" do
_(subject.code).must_equal 401
end
it "returns the message" do
_(subject.message).must_equal "The current user has insufficient permissions"
end
end
describe "empty" do
let(:fake_error) do
fake_error_class.new(nil, nil)
end
it "returns an unknown code" do
_(subject.code).must_equal(-1)
end
it "returns an unknown message" do
_(subject.message).must_equal "Unknown error"
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/verifier_spec.rb | spec/play_store/verifier_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::Verifier do
subject { CandyCheck::PlayStore::Verifier.new(authorization: authorization) }
let(:package_name) { "my_package_name" }
let(:product_id) { "my_product_id" }
let(:subscription_id) { "my_subscription_id" }
let(:token) { "my_token" }
let(:json_key_file) { File.expand_path("../fixtures/play_store/random_dummy_key.json", __dir__) }
let(:authorization) { CandyCheck::PlayStore.authorization(json_key_file) }
describe "product purchases" do
it "verifies a product purchase" do
VCR.use_cassette("play_store/product_purchases/valid_but_not_consumed") do
result = subject.verify_product_purchase(package_name: package_name, product_id: product_id, token: token)
_(result).must_be_instance_of CandyCheck::PlayStore::ProductPurchases::ProductPurchase
_(result.valid?).must_be_true
_(result.consumed?).must_be_false
end
end
it "can return a product purchase verification failure" do
VCR.use_cassette("play_store/product_purchases/permission_denied") do
result = subject.verify_product_purchase(package_name: package_name, product_id: product_id, token: token)
_(result).must_be_instance_of CandyCheck::PlayStore::VerificationFailure
end
end
end
describe "subscription purchases" do
it "verifies a subscription purchase" do
VCR.use_cassette("play_store/subscription_purchases/valid_but_expired") do
result = subject.verify_subscription_purchase(package_name: package_name, subscription_id: subscription_id,
token: token)
_(result).must_be_instance_of CandyCheck::PlayStore::SubscriptionPurchases::SubscriptionPurchase
end
end
it "can return a subscription purchase verification failure" do
VCR.use_cassette("play_store/subscription_purchases/permission_denied") do
result = subject.verify_subscription_purchase(package_name: package_name, subscription_id: subscription_id,
token: token)
_(result).must_be_instance_of CandyCheck::PlayStore::VerificationFailure
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/subscription_purchases/subscription_purchase_spec.rb | spec/play_store/subscription_purchases/subscription_purchase_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::SubscriptionPurchases::SubscriptionPurchase do
subject { CandyCheck::PlayStore::SubscriptionPurchases::SubscriptionPurchase.new(fake_subscription_purchase) }
describe "expired and canceled subscription" do
let(:fake_subscription_purchase) do
OpenStruct.new(
kind: "androidpublisher#subscriptionPurchase",
start_time_millis: 1_459_540_113_244,
expiry_time_millis: 1_462_132_088_610,
auto_renewing: false,
developer_payload: "payload that gets stored and returned",
cancel_reason: 0,
payment_state: 1,
)
end
it "is expired?" do
_(subject.expired?).must_be_true
end
it "is canceled by user" do
_(subject.canceled_by_user?).must_be_true
end
it "returns the payment_state" do
_(subject.payment_state).must_equal 1
end
it "considers a payment as valid" do
_(subject.payment_received?).must_be_true
end
it "checks that auto renewal status is false" do
_(subject.auto_renewing?).must_be_false
end
it "returns the developer_payload" do
_(subject.developer_payload).must_equal \
"payload that gets stored and returned"
end
it "returns the kind" do
_(subject.kind).must_equal "androidpublisher#subscriptionPurchase"
end
it "returns the start_time_millis" do
_(subject.start_time_millis).must_equal 145_954_011_324_4
end
it "returns the expiry_time_millis" do
_(subject.expiry_time_millis).must_equal 146_213_208_861_0
end
it "returns the starts_at" do
expected = DateTime.new(2016, 4, 1, 19, 48, 33)
_(subject.starts_at).must_equal expected
end
it "returns the expires_at" do
expected = DateTime.new(2016, 5, 1, 19, 48, 8)
_(subject.expires_at).must_equal expected
end
end
describe "unexpired and renewing subscription" do
two_days_from_now = DateTime.now + 2
let(:fake_subscription_purchase) do
OpenStruct.new(
kind: "androidpublisher#subscriptionPurchase",
start_time_millis: 1_459_540_113_244,
expiry_time_millis: (two_days_from_now.to_time.to_i * 1000),
auto_renewing: true,
developer_payload: "payload that gets stored and returned",
cancel_reason: 0,
payment_state: 1,
)
end
it "is expired?" do
_(subject.expired?).must_be_false
end
it "is two days left until it is overdue" do
_(subject.overdue_days).must_equal(-2)
end
end
describe "expired due to payment failure" do
let(:fake_subscription_purchase) do
OpenStruct.new(
kind: "androidpublisher#subscriptionPurchase",
start_time_millis: 1_459_540_113_244,
expiry_time_millis: 1_462_132_088_610,
auto_renewing: true,
developer_payload: "payload that gets stored and returned",
cancel_reason: 1,
payment_state: 1,
)
end
it "is expired?" do
_(subject.expired?).must_be_true
end
it "is payment_failed?" do
_(subject.payment_failed?).must_be_true
end
end
describe "subscription cancelation by user" do
describe "when subscription is not canceled" do
let(:fake_subscription_purchase) do
OpenStruct.new(
kind: "androidpublisher#subscriptionPurchase",
start_time_millis: 1_459_540_113_244,
expiry_time_millis: 1_462_132_088_610,
auto_renewing: true,
developer_payload: "payload that gets stored and returned",
payment_state: 1,
)
end
it "is not canceled?" do
_(subject.canceled_by_user?).must_be_false
end
it "returns nil user_cancellation_time_millis" do
_(subject.user_cancellation_time_millis).must_be_nil
end
it "returns nil canceled_at" do
_(subject.canceled_at).must_be_nil
end
end
describe "when subscription is canceled" do
let(:fake_subscription_purchase) do
OpenStruct.new(
kind: "androidpublisher#subscriptionPurchase",
start_time_millis: 1_459_540_113_244,
expiry_time_millis: 1_462_132_088_610,
user_cancellation_time_millis: 1_461_872_888_000,
auto_renewing: true,
developer_payload: "payload that gets stored and returned",
cancel_reason: 0,
payment_state: 1,
)
end
it "is canceled?" do
_(subject.canceled_by_user?).must_be_true
end
it "returns the user_cancellation_time_millis" do
_(subject.user_cancellation_time_millis).must_equal 1_461_872_888_000
end
it "returns the starts_at" do
expected = DateTime.new(2016, 4, 28, 19, 48, 8)
_(subject.canceled_at).must_equal expected
end
end
end
describe "expired with pending payment" do
let(:fake_subscription_purchase) do
OpenStruct.new(
kind: "androidpublisher#subscriptionPurchase",
start_time_millis: 1_459_540_113_244,
expiry_time_millis: 1_462_132_088_610,
auto_renewing: true,
developer_payload: "payload that gets stored and returned",
cancel_reason: 0,
payment_state: 0,
)
end
it "is expired?" do
_(subject.expired?).must_be_true
end
it "is payment_pending?" do
_(subject.payment_pending?).must_be_true
end
end
describe "trial" do
let(:fake_subscription_purchase) do
OpenStruct.new(
kind: "androidpublisher#subscriptionPurchase",
start_time_millis: 1_459_540_113_244,
expiry_time_millis: 1_462_132_088_610,
auto_renewing: false,
developer_payload: "payload that gets stored and returned",
cancel_reason: 0,
payment_state: 1,
price_currency_code: "SOMECODE",
price_amount_micros: 0,
)
end
it "is trial?" do
_(subject.trial?).must_be_true
end
it "returns the price_currency_code" do
_(subject.price_currency_code).must_equal "SOMECODE"
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/subscription_purchases/subscription_verification_spec.rb | spec/play_store/subscription_purchases/subscription_verification_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::SubscriptionPurchases::SubscriptionVerification do
subject do
CandyCheck::PlayStore::SubscriptionPurchases::SubscriptionVerification.new(
package_name: package_name,
subscription_id: subscription_id,
token: token,
authorization: authorization,
)
end
let(:json_key_file) { File.expand_path("../../fixtures/play_store/random_dummy_key.json", __dir__) }
let(:authorization) { CandyCheck::PlayStore.authorization(json_key_file) }
let(:package_name) { "my_package_name" }
let(:subscription_id) { "my_subscription_id" }
let(:token) { "my_token" }
describe "valid" do
it "returns a subscription" do
VCR.use_cassette("play_store/subscription_purchases/valid_but_expired") do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::SubscriptionPurchases::SubscriptionPurchase
_(result.expired?).must_be_true
end
end
end
describe "failure" do
it "returns a verification failure" do
VCR.use_cassette("play_store/subscription_purchases/permission_denied") do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::VerificationFailure
_(result.code).must_equal 401
end
end
end
describe "empty" do
let(:response) do
{}
end
it "returns a verification failure" do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::VerificationFailure
_(result.code).must_equal(-1)
end
end
describe "invalid response kind" do
let(:response) do
{
"kind" => "something weird",
}
end
it "returns a verification failure" do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::VerificationFailure
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/product_purchases/product_purchase_spec.rb | spec/play_store/product_purchases/product_purchase_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::ProductPurchases::ProductPurchase do
subject { CandyCheck::PlayStore::ProductPurchases::ProductPurchase.new(fake_product_purchase) }
describe "valid and non-consumed product" do
let(:fake_product_purchase) do
OpenStruct.new(
consumption_state: 0,
developer_payload: "payload that gets stored and returned",
kind: "androidpublisher#productPurchase",
order_id: "ABC123",
purchase_state: 0,
purchase_time_millis: 1_421_676_237_413,
)
end
it "is valid?" do
_(subject.valid?).must_be_true
end
it "is not consumed" do
_(subject.consumed?).must_be_false
end
it "returns the purchase_state" do
_(subject.purchase_state).must_equal 0
end
it "returns the consumption_state" do
_(subject.consumption_state).must_equal 0
end
it "returns the developer_payload" do
_(subject.developer_payload).must_equal "payload that gets stored and returned"
end
it "returns the kind" do
_(subject.kind).must_equal "androidpublisher#productPurchase"
end
it "returns the purchase_time_millis" do
_(subject.purchase_time_millis).must_equal 1_421_676_237_413
end
it "returns the purchased_at" do
expected = DateTime.new(2015, 1, 19, 14, 3, 57)
_(subject.purchased_at).must_equal expected
end
end
describe "valid and consumed product" do
let(:fake_product_purchase) do
OpenStruct.new(
consumption_state: 1,
developer_payload: "payload that gets stored and returned",
kind: "androidpublisher#productPurchase",
order_id: "ABC123",
purchase_state: 0,
purchase_time_millis: 1_421_676_237_413,
)
end
it "is valid?" do
_(subject.valid?).must_be_true
end
it "is consumed?" do
_(subject.consumed?).must_be_true
end
end
describe "non-valid product" do
let(:fake_product_purchase) do
OpenStruct.new(
consumption_state: 0,
developer_payload: "payload that gets stored and returned",
kind: "androidpublisher#productPurchase",
order_id: "ABC123",
purchase_state: 1,
purchase_time_millis: 1_421_676_237_413,
)
end
it "is valid?" do
_(subject.valid?).must_be_false
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/product_purchases/product_verification_spec.rb | spec/play_store/product_purchases/product_verification_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::ProductPurchases::ProductVerification do
subject do
CandyCheck::PlayStore::ProductPurchases::ProductVerification.new(
package_name: package_name,
product_id: product_id,
token: token,
authorization: authorization,
)
end
let(:package_name) { "my_package_name" }
let(:product_id) { "my_product_id" }
let(:token) { "my_token" }
let(:json_key_file) { File.expand_path("../../fixtures/play_store/random_dummy_key.json", __dir__) }
let(:authorization) { CandyCheck::PlayStore.authorization(json_key_file) }
describe "valid" do
it "returns a product purchase" do
VCR.use_cassette("play_store/product_purchases/valid_but_not_consumed") do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::ProductPurchases::ProductPurchase
_(result.valid?).must_be_true
_(result.consumed?).must_be_false
end
end
end
describe "failure" do
it "returns a verification failure" do
VCR.use_cassette("play_store/product_purchases/permission_denied") do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::VerificationFailure
_(result.code).must_equal 401
end
end
end
describe "empty" do
it "returns a verification failure" do
VCR.use_cassette("play_store/product_purchases/response_with_empty_body") do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::VerificationFailure
_(result.code).must_equal(-1)
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/product_acknowledgements/response_spec.rb | spec/play_store/product_acknowledgements/response_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::ProductAcknowledgements::Response do
subject do
CandyCheck::PlayStore::ProductAcknowledgements::Response.new(result: result, error_data: error_data)
end
describe "#acknowledged?" do
describe "when result present" do
let(:result) { "" }
let(:error_data) { nil }
it "returns true" do
result = subject.acknowledged?
_(result).must_be_true
end
end
describe "when result is not present" do
let(:result) { nil }
let(:error_data) { nil }
it "returns false" do
result = subject.acknowledged?
_(result).must_be_false
end
end
end
describe "#error" do
describe "when error present" do
let(:result) { nil }
let(:error_data) do
Module.new do
def status_code
400
end
def body
"A String describing the issue"
end
module_function :status_code, :body
end
end
it "returns the expected data" do
result = subject.error
_(result[:status_code]).must_equal(400)
_(result[:body]).must_equal("A String describing the issue")
end
end
describe "when error is not present" do
let(:result) { "" }
let(:error_data) { nil }
it "returns false" do
result = subject.error
_(result).must_be_nil
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/play_store/product_acknowledgements/acknowledgement_spec.rb | spec/play_store/product_acknowledgements/acknowledgement_spec.rb | require "spec_helper"
describe CandyCheck::PlayStore::ProductAcknowledgements::Acknowledgement do
subject do
CandyCheck::PlayStore::ProductAcknowledgements::Acknowledgement.new(
package_name: package_name,
product_id: product_id,
token: token,
authorization: authorization,
)
end
let(:package_name) { "fake_package_name" }
let(:product_id) { "fake_product_id" }
let(:token) { "fake_token" }
let(:json_key_file) { File.expand_path("../../fixtures/play_store/random_dummy_key.json", __dir__) }
let(:authorization) { CandyCheck::PlayStore.authorization(json_key_file) }
describe "#call!" do
it "when acknowledgement succeeds" do
VCR.use_cassette("play_store/product_acknowledgements/acknowledged") do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::ProductAcknowledgements::Response
_(result.acknowledged?).must_be_true
_(result.error).must_be_nil
end
end
it "when already acknowledged" do
# rubocop:disable Layout/LineLength
error_body = "{\n \"error\": {\n \"code\": 400,\n \"message\": \"The purchase is not in a valid state to perform the desired operation.\",\n \"errors\": [\n {\n \"message\": \"The purchase is not in a valid state to perform the desired operation.\",\n \"domain\": \"androidpublisher\",\n \"reason\": \"invalidPurchaseState\",\n \"location\": \"token\",\n \"locationType\": \"parameter\"\n }\n ]\n }\n}\n"
# rubocop:enable Layout/LineLength
VCR.use_cassette("play_store/product_acknowledgements/already_acknowledged") do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::ProductAcknowledgements::Response
_(result.acknowledged?).must_be_false
_(result.error[:body]).must_equal(error_body)
_(result.error[:status_code]).must_equal(400)
end
end
it "when it has been refunded" do
# rubocop:disable Layout/LineLength
error_body = "{\n \"error\": {\n \"code\": 400,\n \"message\": \"The product purchase is not owned by the user.\",\n \"errors\": [\n {\n \"message\": \"The product purchase is not owned by the user.\",\n \"domain\": \"androidpublisher\",\n \"reason\": \"productNotOwnedByUser\"\n }\n ]\n }\n}\n"
# rubocop:enable Layout/LineLength
VCR.use_cassette("play_store/product_acknowledgements/refunded") do
result = subject.call!
_(result).must_be_instance_of CandyCheck::PlayStore::ProductAcknowledgements::Response
_(result.acknowledged?).must_be_false
_(result.error[:body]).must_equal(error_body)
_(result.error[:status_code]).must_equal(400)
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/cli/app_spec.rb | spec/cli/app_spec.rb | require "spec_helper"
describe CandyCheck::CLI::App do
subject { CandyCheck::CLI::App.new }
it "supports the version command" do
stub_command(CandyCheck::CLI::Commands::Version) do
_(subject.version).must_equal :stubbed
_(@arguments).must_be_empty
end
end
it "supports the app_store command" do
stub_command(CandyCheck::CLI::Commands::AppStore) do
_(subject.app_store("receipt")).must_equal :stubbed
_(@arguments).must_equal ["receipt"]
end
end
it "supports the play_store command" do
stub_command(CandyCheck::CLI::Commands::PlayStore) do
_(subject.play_store("package", "id", "token")).must_equal :stubbed
_(@arguments).must_equal %w(package id token)
end
end
it "returns true when call .exit_on_failure?" do
_(CandyCheck::CLI::App.exit_on_failure?).must_equal true
end
private
def stub_command(target, &block)
stub = proc do |*args|
@arguments = args
:stubbed
end
target.stub :run, stub, &block
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/cli/out_spec.rb | spec/cli/out_spec.rb | require "spec_helper"
describe CandyCheck::CLI::Out do
subject { CandyCheck::CLI::Out.new(out) }
let(:out) { StringIO.new }
it "defaults to use STDOUT" do
_(CandyCheck::CLI::Out.new.out).must_be_same_as $stdout
end
it "holds the outlet" do
_(subject.out).must_be_same_as out
end
it "prints to outlet" do
subject.print "some text"
subject.print "another line"
close
_(out.readlines).must_equal [
"some text\n",
"another line\n",
]
end
it "pretty prints to outlet" do
subject.pretty dummy: 1
subject.pretty [1, 2, 3]
close
_(out.readlines).must_equal [
"{:dummy=>1}\n",
"[1, 2, 3]\n",
]
end
private
def close
out.flush
out.rewind
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/cli/commands/version_spec.rb | spec/cli/commands/version_spec.rb | require "spec_helper"
describe CandyCheck::CLI::Commands::Version do
include WithCommand
subject { CandyCheck::CLI::Commands::Version }
it "prints the gem's version" do
run_command!
_(out.lines).must_equal [CandyCheck::VERSION]
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/cli/commands/app_store_spec.rb | spec/cli/commands/app_store_spec.rb | require "spec_helper"
describe CandyCheck::CLI::Commands::AppStore do
include WithCommand
subject { CandyCheck::CLI::Commands::AppStore }
let(:arguments) { [receipt, options] }
let(:receipt) { "data" }
let(:options) do
{
environment: :sandbox,
}
end
let(:dummy_verifier_class) do
Struct.new(:config) do
attr_reader :arguments
def verify(*arguments)
@arguments = arguments
{ result: :stubbed }
end
end
end
before do
stub = proc do |*args|
@verifier = dummy_verifier_class.new(*args)
end
CandyCheck::AppStore::Verifier.stub :new, stub do
run_command!
end
end
describe "default" do
it "uses the receipt and the options" do
_(@verifier.config.environment).must_equal :sandbox
_(@verifier.arguments).must_equal [receipt, nil]
_(out.lines).must_equal ["Hash:", { result: :stubbed }]
end
end
describe "with secret" do
let(:options) do
{
environment: :production,
secret: "notasecret",
}
end
it "uses the secret for verification" do
_(@verifier.config.environment).must_equal :production
_(@verifier.arguments).must_equal [receipt, "notasecret"]
_(out.lines).must_equal ["Hash:", { result: :stubbed }]
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/spec/cli/commands/play_store_spec.rb | spec/cli/commands/play_store_spec.rb | require "spec_helper"
describe CandyCheck::CLI::Commands::PlayStore do
include WithCommand
subject do
CandyCheck::CLI::Commands::PlayStore.new(package_name, product_id, token, "json_key_file" => json_key_file)
end
let(:package_name) { "my_package_name" }
let(:product_id) { "my_product_id" }
let(:token) { "my_token" }
let(:json_key_file) { File.expand_path("../../fixtures/play_store/random_dummy_key.json", __dir__) }
it "calls and outputs the verifier" do
VCR.use_cassette("play_store/product_purchases/valid_but_not_consumed") do
run_command!
assert_equal "CandyCheck::PlayStore::ProductPurchases::ProductPurchase:", out.lines.first
assert_equal CandyCheck::PlayStore::ProductPurchases::ProductPurchase, out.lines[1].class
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check.rb | lib/candy_check.rb | require "candy_check/version"
require "candy_check/utils"
require "candy_check/app_store"
require "candy_check/play_store"
# Module to check and verify in-app receipts
module CandyCheck
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/version.rb | lib/candy_check/version.rb | module CandyCheck
# The current gem's version
VERSION = "0.6.0".freeze
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/utils.rb | lib/candy_check/utils.rb | require "candy_check/utils/attribute_reader"
require "candy_check/utils/config"
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store.rb | lib/candy_check/play_store.rb | require "google-apis-androidpublisher_v3"
require "googleauth"
require "candy_check/play_store/android_publisher_service"
require "candy_check/play_store/product_purchases/product_purchase"
require "candy_check/play_store/subscription_purchases/subscription_purchase"
require "candy_check/play_store/product_purchases/product_verification"
require "candy_check/play_store/product_acknowledgements/acknowledgement"
require "candy_check/play_store/product_acknowledgements/response"
require "candy_check/play_store/subscription_purchases/subscription_verification"
require "candy_check/play_store/verification_failure"
require "candy_check/play_store/verifier"
require "candy_check/play_store/acknowledger"
module CandyCheck
# Module to request and verify a AppStore receipt
module PlayStore
# Build an authorization object
# @param json_key_file [String]
# @return [Google::Auth::ServiceAccountCredentials]
def self.authorization(json_key_file)
Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open(json_key_file),
scope: "https://www.googleapis.com/auth/androidpublisher",
)
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/cli.rb | lib/candy_check/cli.rb | require "candy_check/cli/app"
require "candy_check/cli/commands"
require "candy_check/cli/out"
module CandyCheck
# Namespace holding the implementation of the CLI to
# verify in-app purchases
module CLI
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store.rb | lib/candy_check/app_store.rb | require "candy_check/app_store/client"
require "candy_check/app_store/config"
require "candy_check/app_store/receipt"
require "candy_check/app_store/receipt_collection"
require "candy_check/app_store/verification"
require "candy_check/app_store/subscription_verification"
require "candy_check/app_store/verification_failure"
require "candy_check/app_store/verifier"
module CandyCheck
# Module to request and verify a AppStore receipt
module AppStore
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store/subscription_verification.rb | lib/candy_check/app_store/subscription_verification.rb | module CandyCheck
module AppStore
# Verifies a latest_receipt_info block against a verification server.
# The call return either an {ReceiptCollection} or a {VerificationFailure}
class SubscriptionVerification < CandyCheck::AppStore::Verification
# Builds a fresh verification run
# @param endpoint_url [String] the verification URL to use
# @param receipt_data [String] the raw data to be verified
# @param secret [String] optional: shared secret
# @param product_ids [Array<String>] optional: select specific products
def initialize(
endpoint_url,
receipt_data,
secret = nil,
product_ids = nil
)
super(endpoint_url, receipt_data, secret)
@product_ids = product_ids
end
# Performs the verification against the remote server
# @return [ReceiptCollection] if successful
# @return [VerificationFailure] otherwise
def call!
verify!
if valid?
build_collection(@response["latest_receipt_info"])
else
VerificationFailure.fetch(@response["status"])
end
end
private
def build_collection(latest_receipt_info)
unless @product_ids.nil?
latest_receipt_info = latest_receipt_info.select do |info|
@product_ids.include?(info["product_id"])
end
end
ReceiptCollection.new(latest_receipt_info)
end
def valid?
status_is_ok = @response["status"] == STATUS_OK
@response && status_is_ok && @response["latest_receipt_info"]
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store/verification_failure.rb | lib/candy_check/app_store/verification_failure.rb | module CandyCheck
module AppStore
# Represents a failing call against the verification server
class VerificationFailure
# @return [Integer] the code of the failure
attr_reader :code
# @return [String] the message of the failure
attr_reader :message
# Initializes a new instance which bases on a JSON result
# from Apple servers
# @param code [Integer]
# @param message [String]
def initialize(code, message)
@code = code
@message = message
end
class << self
# Gets a known failure or build an unknown failure
# without description
# @param code [Integer]
# @return [VerificationFailure]
def fetch(code)
known.fetch(code) do
fallback(code)
end
end
private
def fallback(code)
new(code || -1, "Unknown error")
end
def known
@known ||= {}
end
def add(code, name)
known[code] = new(code, name)
end
def freeze!
known.freeze
end
end
add 21_000, "The request to the App Store was not made using" \
" the HTTP POST request method."
add 21_001, "This status code is no longer sent by the App Store."
add 21_002, "The data in the receipt-data property was malformed" \
" or the service experienced a temporary issue. Try again."
add 21_003, "The receipt could not be authenticated."
add 21_004, "The shared secret you provided does not match the shared" \
" secret on file for your account."
add 21_005, "The receipt server was temporarily unable to provide" \
" the receipt. Try again."
add 21_006, "This receipt is valid but the subscription has expired." \
" When this status code is returned to your server, the" \
" receipt data is also decoded and returned as part of" \
" the response. Only returned for iOS 6-style transaction" \
" receipts for auto-renewable subscriptions."
add 21_007, "This receipt is from the test environment, but it was" \
" sent to the production environment for verification."
add 21_008, "This receipt is from the production environment, but it" \
" was sent to the test environment for verification."
add 21_009, "Internal data access error. Try again later."
add 21_010, "The user account cannot be found or has been deleted."
freeze!
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store/verifier.rb | lib/candy_check/app_store/verifier.rb | module CandyCheck
module AppStore
# Verifies receipts against the verification servers.
# The call return either an {Receipt} or a {VerificationFailure}
class Verifier
# HTTPS endpoint for production receipts
PRODUCTION_ENDPOINT = "https://buy.itunes.apple.com/verifyReceipt".freeze
# HTTPS endpoint for sandbox receipts
SANDBOX_ENDPOINT = "https://sandbox.itunes.apple.com/verifyReceipt".freeze
# Status code from production endpoint when receiving a sandbox
# receipt which occurs during the app's review process
REDIRECT_TO_SANDBOX_CODE = 21_007
# Status code from the sandbox endpoint when receiving a production
# receipt
REDIRECT_TO_PRODUCTION_CODE = 21_008
# @return [Config] the current configuration
attr_reader :config
# Initializes a new verifier for the application which is bound
# to a configuration
# @param config [Config]
def initialize(config)
@config = config
end
# Calls a verification for the given input
# @param receipt_data [String] the raw data to be verified
# @param secret [String] the optional shared secret
# @return [Receipt] if successful
# @return [VerificationFailure] otherwise
def verify(receipt_data, secret = nil)
fetch_receipt_information(Verification, [receipt_data, secret])
end
# Calls a subscription verification for the given input
# @param receipt_data [String] the raw data to be verified
# @param secret [String] optional: shared secret
# @param product_ids [Array<String>] optional: products to filter
# @return [ReceiptCollection] if successful
# @return [Verification] otherwise
def verify_subscription(receipt_data, secret = nil, product_ids = nil)
args = [receipt_data, secret, product_ids]
fetch_receipt_information(SubscriptionVerification, args)
end
private
def fetch_receipt_information(verifier_class, args)
default_endpoint, opposite_endpoint = endpoints
result = call_for(verifier_class, args.dup.unshift(default_endpoint))
return call_for(verifier_class, args.dup.unshift(opposite_endpoint)) if should_retry?(result)
result
end
def call_for(verifier_class, args)
verifier_class.new(*args).call!
end
def should_retry?(result)
result.is_a?(VerificationFailure) && redirect?(result)
end
def endpoints
if config.production?
[PRODUCTION_ENDPOINT, SANDBOX_ENDPOINT]
else
[SANDBOX_ENDPOINT, PRODUCTION_ENDPOINT]
end
end
def redirect_code
if config.production?
REDIRECT_TO_SANDBOX_CODE
else
REDIRECT_TO_PRODUCTION_CODE
end
end
def redirect?(failure)
failure.code == redirect_code
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store/verification.rb | lib/candy_check/app_store/verification.rb | module CandyCheck
module AppStore
# Verifies a receipt block against a verification server.
# The call return either an {Receipt} or a {VerificationFailure}
class Verification
# @return [String] the verification URL to use
attr_reader :endpoint_url
# @return [String] the raw data to be verified
attr_reader :receipt_data
# @return [String] the optional shared secret
attr_reader :secret
# Constant for successful responses
STATUS_OK = 0
# Builds a fresh verification run
# @param endpoint_url [String] the verification URL to use
# @param receipt_data [String] the raw data to be verified
# @param secret [String] optional: shared secret
def initialize(endpoint_url, receipt_data, secret = nil)
@endpoint_url = endpoint_url
@receipt_data = receipt_data
@secret = secret
end
# Performs the verification against the remote server
# @return [Receipt] if successful
# @return [VerificationFailure] otherwise
def call!
verify!
if valid?
Receipt.new(@response["receipt"])
else
VerificationFailure.fetch(@response["status"])
end
end
private
def valid?
@response && @response["status"] == STATUS_OK && @response["receipt"]
end
def verify!
client = Client.new(endpoint_url)
@response = client.verify(receipt_data, secret)
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store/receipt.rb | lib/candy_check/app_store/receipt.rb | module CandyCheck
module AppStore
# Describes a successful response from the AppStore verification server
class Receipt
include Utils::AttributeReader
# @return [Hash] the raw attributes returned from the server
attr_reader :attributes
# Initializes a new instance which bases on a JSON result
# from Apple's verification server
# @param attributes [Hash]
def initialize(attributes)
@attributes = attributes
end
# In most cases a receipt is a valid transaction except when the
# transaction was canceled.
# @return [Boolean]
def valid?
!has?("cancellation_date")
end
# The receipt's transaction id
# @return [String]
def transaction_id
read("transaction_id")
end
# The receipt's original transaction id which might differ from
# the transaction id for restored products
# @return [String]
def original_transaction_id
read("original_transaction_id")
end
# The version number for the app
# @return [String]
def app_version
read("bvrs")
end
# The app's bundle identifier
# @return [String]
def bundle_identifier
read("bid")
end
# The app's identifier of the product (SKU)
# @return [String]
def product_id
read("product_id")
end
# The app's item id of the product
# @return [String]
def item_id
read("item_id")
end
# The quantity of the product
# @return [Integer]
def quantity
read_integer("quantity")
end
# The purchase date
# @return [DateTime]
def purchase_date
read_datetime_from_string("purchase_date")
end
# The original purchase date which might differ from the
# actual purchase date for restored products
# @return [DateTime]
def original_purchase_date
read_datetime_from_string("original_purchase_date")
end
# The date of when Apple has canceled this transaction.
# From Apple's documentation: "Treat a canceled receipt
# the same as if no purchase had ever been made."
# @return [DateTime]
def cancellation_date
read_datetime_from_string("cancellation_date")
end
# The date of a subscription's expiration
# @return [DateTime]
def expires_date
read_datetime_from_string("expires_date")
end
# rubocop:disable Naming/PredicateName
def is_trial_period
# rubocop:enable Naming/PredicateName
read_bool("is_trial_period")
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store/client.rb | lib/candy_check/app_store/client.rb | require "multi_json"
require "net/http"
module CandyCheck
module AppStore
# Simple HTTP client to load the receipt's data from Apple's verification
# servers (either sandbox or production).
class Client
# Mimetype for JSON objects
JSON_MIME_TYPE = "application/json".freeze
# Initialize a new client bound to an endpoint
# @param endpoint_url [String]
def initialize(endpoint_url)
@uri = URI(endpoint_url)
end
# Contacts the configured endpoint and requests the receipt's data
# @param receipt_data [String] base64 encoded data string from the app
# @param secret [String] the password for auto-renewable subscriptions
# @return [Hash]
def verify(receipt_data, secret = nil)
request = build_request(build_request_parameters(receipt_data, secret))
response = perform_request(request)
MultiJson.load(response.body)
end
private
def perform_request(request)
build_http_connector.request(request)
end
def build_http_connector
Net::HTTP.new(@uri.host, @uri.port).tap do |net|
net.use_ssl = true
net.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
end
def build_request(parameters)
Net::HTTP::Post.new(@uri.request_uri).tap do |post|
post["Accept"] = JSON_MIME_TYPE
post["Content-Type"] = JSON_MIME_TYPE
post.body = MultiJson.dump(parameters)
end
end
def build_request_parameters(receipt_data, secret)
{
"receipt-data" => receipt_data,
}.tap do |h|
h["password"] = secret if secret
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store/receipt_collection.rb | lib/candy_check/app_store/receipt_collection.rb | module CandyCheck
module AppStore
# Store multiple {Receipt}s in order to perform collective operation on them
class ReceiptCollection
# Multiple receipts as in verfication response
# @return [Array<Receipt>]
attr_reader :receipts
# Initializes a new instance which bases on a JSON result
# from Apple's verification server
# @param attributes [Array<Hash>] raw data from Apple's server
def initialize(attributes)
@receipts = attributes.map { |r| Receipt.new(r) }.sort do |a, b|
a.purchase_date - b.purchase_date
end
end
# Check if the latest expiration date is passed
# @return [bool]
def expired?
expires_at.to_time <= Time.now.utc
end
# Check if in trial
# @return [bool]
def trial?
@receipts.last.is_trial_period
end
# Get latest expiration date
# @return [DateTime]
def expires_at
@receipts.last.expires_date
end
# Get number of overdue days. If this is negative, it is not overdue.
# @return [Integer]
def overdue_days
(Date.today - expires_at.to_date).to_i
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/app_store/config.rb | lib/candy_check/app_store/config.rb | module CandyCheck
module AppStore
# Configure the verifier
class Config < Utils::Config
# @return [Symbol] the used environment
attr_reader :environment
# @!method initialize(attributes)
# Initializes a new configuration from a hash
# @param attributes [Hash]
# @example
# Config.new(
# environment: :production # or :sandbox
# )
# @return [Boolean] if it is production environment
def production?
environment == :production
end
private
def validate!
validates_inclusion(:environment, :production, :sandbox)
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/verification_failure.rb | lib/candy_check/play_store/verification_failure.rb | module CandyCheck
module PlayStore
# Represents a failing call against the Google API server
class VerificationFailure
include Utils::AttributeReader
# @return [Hash] the raw attributes returned from the server
attr_reader :error
# Initializes a new instance which bases on a JSON result
# from Google API servers
# @param error [Hash]
def initialize(error)
@error = error
end
# The code of the failure
# @return [Integer]
def code
Integer(error.status_code)
rescue StandardError
-1
end
# The message of the failure
# @return [String]
def message
error.message || "Unknown error"
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/verifier.rb | lib/candy_check/play_store/verifier.rb | module CandyCheck
module PlayStore
# Verifies purchase tokens against the Google API.
# The call return either a {SubscriptionPurchases::SubscriptionPurchase} or a {VerificationFailure}
class Verifier
# Initializes a new verifier which is bound to an authorization
# @param authorization [Google::Auth::ServiceAccountCredentials] to use against the PlayStore API
def initialize(authorization:)
@authorization = authorization
end
# Contacts the Google API and requests the product state
# @param package_name [String] to query
# @param product_id [String] to query
# @param token [String] to use for authentication
# @return [ProductPurchases::ProductPurchase] if successful
# @return [VerificationFailure] otherwise
def verify_product_purchase(package_name:, product_id:, token:)
verifier = CandyCheck::PlayStore::ProductPurchases::ProductVerification.new(
package_name: package_name,
product_id: product_id,
token: token,
authorization: @authorization,
)
verifier.call!
end
# Contacts the Google API and requests the product state
# @param package_name [String] to query
# @param subscription_id [String] to query
# @param token [String] to use for authentication
# @return [SubscriptionPurchases::SubscriptionPurchase] if successful
# @return [VerificationFailure] otherwise
def verify_subscription_purchase(package_name:, subscription_id:, token:)
verifier = CandyCheck::PlayStore::SubscriptionPurchases::SubscriptionVerification.new(
package_name: package_name,
subscription_id: subscription_id,
token: token,
authorization: @authorization,
)
verifier.call!
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/android_publisher_service.rb | lib/candy_check/play_store/android_publisher_service.rb | module CandyCheck
module PlayStore
class AndroidPublisherService < Google::Apis::AndroidpublisherV3::AndroidPublisherService
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/acknowledger.rb | lib/candy_check/play_store/acknowledger.rb | module CandyCheck
module PlayStore
class Acknowledger
def initialize(authorization:)
@authorization = authorization
end
def acknowledge_product_purchase(package_name:, product_id:, token:)
acknowledger = CandyCheck::PlayStore::ProductAcknowledgements::Acknowledgement.new(
package_name: package_name,
product_id: product_id,
token: token,
authorization: @authorization,
)
acknowledger.call!
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/subscription_purchases/subscription_verification.rb | lib/candy_check/play_store/subscription_purchases/subscription_verification.rb | module CandyCheck
module PlayStore
module SubscriptionPurchases
# Verifies a purchase token against the Google API
# The call return either an {SubscriptionPurchase} or an {VerificationFailure}
class SubscriptionVerification
# @return [String] the package which will be queried
attr_reader :package_name
# @return [String] the item id which will be queried
attr_reader :subscription_id
# @return [String] the token for authentication
attr_reader :token
# Initializes a new call to the API
# @param package_name [String]
# @param subscription_id [String]
# @param token [String]
def initialize(package_name:, subscription_id:, token:, authorization:)
@package_name = package_name
@subscription_id = subscription_id
@token = token
@authorization = authorization
end
# Performs the verification against the remote server
# @return [SubscriptionPurchase] if successful
# @return [VerificationFailure] otherwise
def call!
verify!
if valid?
CandyCheck::PlayStore::SubscriptionPurchases::SubscriptionPurchase.new(@response[:result])
else
CandyCheck::PlayStore::VerificationFailure.new(@response[:error])
end
end
private
def valid?
return false unless @response[:result]
ok_kind = @response[:result].kind == "androidpublisher#subscriptionPurchase"
@response && @response[:result].expiry_time_millis && ok_kind
end
def verify!
service = CandyCheck::PlayStore::AndroidPublisherService.new
service.authorization = @authorization
service.get_purchase_subscription(package_name, subscription_id, token) do |result, error|
@response = { result: result, error: error }
end
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/subscription_purchases/subscription_purchase.rb | lib/candy_check/play_store/subscription_purchases/subscription_purchase.rb | module CandyCheck
module PlayStore
module SubscriptionPurchases
# Describes a successfully validated subscription
class SubscriptionPurchase
include Utils::AttributeReader
# @return [Google::Apis::AndroidpublisherV3::SubscriptionPurchase] the raw subscription purchase
# from google-api-client
attr_reader :subscription_purchase
# The payment of the subscription is pending (paymentState)
PAYMENT_PENDING = 0
# The payment of the subscript is received (paymentState)
PAYMENT_RECEIVED = 1
# The subscription was canceled by the user (cancelReason)
PAYMENT_CANCELED = 0
# The payment failed during processing (cancelReason)
PAYMENT_FAILED = 1
# Initializes a new instance which bases on a JSON result
# from Google's servers
# @param subscription_purchase [Google::Apis::AndroidpublisherV3::SubscriptionPurchase]
def initialize(subscription_purchase)
@subscription_purchase = subscription_purchase
end
# Check if the expiration date is passed
# @return [bool]
def expired?
overdue_days > 0
end
# Check if in trial. This is actually not given by Google, but we assume
# that it is a trial going on if the paid amount is 0 and
# renewal is activated.
# @return [bool]
def trial?
price_is_zero = price_amount_micros == 0
price_is_zero && payment_received?
end
# see if payment is ok
# @return [bool]
def payment_received?
payment_state == PAYMENT_RECEIVED
end
# see if payment is pending
# @return [bool]
def payment_pending?
payment_state == PAYMENT_PENDING
end
# see if payment has failed according to Google
# @return [bool]
def payment_failed?
cancel_reason == PAYMENT_FAILED
end
# see if this the user has canceled its subscription
# @return [bool]
def canceled_by_user?
cancel_reason == PAYMENT_CANCELED
end
# Get number of overdue days. If this is negative, it is not overdue.
# @return [Integer]
def overdue_days
(Time.now.utc.to_date - expires_at.to_date).to_i
end
# Get the auto renewal status as given by Google
# @return [bool] true if renewing automatically, false otherwise
def auto_renewing?
@subscription_purchase.auto_renewing
end
# Get the payment state as given by Google
# @return [Integer]
def payment_state
@subscription_purchase.payment_state
end
# Get the price amount for the subscription in micros in the payed
# currency
# @return [Integer]
def price_amount_micros
@subscription_purchase.price_amount_micros
end
# Get the cancel reason, as given by Google
# @return [Integer]
def cancel_reason
@subscription_purchase.cancel_reason
end
# Get the kind of subscription as stored in the android publisher service
# @return [String]
def kind
@subscription_purchase.kind
end
# Get developer-specified supplemental information about the order
# @return [String]
def developer_payload
@subscription_purchase.developer_payload
end
# Get the currency code in ISO 4217 format, e.g. "GBP" for British pounds
# @return [String]
def price_currency_code
@subscription_purchase.price_currency_code
end
# Get start time for subscription in milliseconds since Epoch
# @return [Integer]
def start_time_millis
@subscription_purchase.start_time_millis
end
# Get expiry time for subscription in milliseconds since Epoch
# @return [Integer]
def expiry_time_millis
@subscription_purchase.expiry_time_millis
end
# Get cancellation time for subscription in milliseconds since Epoch.
# Only present if cancelReason is 0.
# @return [Integer]
def user_cancellation_time_millis
@subscription_purchase.user_cancellation_time_millis if canceled_by_user?
end
# Get start time in UTC
# @return [DateTime]
def starts_at
Time.at(start_time_millis / 1000).utc.to_datetime
end
# Get expiration time in UTC
# @return [DateTime]
def expires_at
Time.at(expiry_time_millis / 1000).utc.to_datetime
end
# Get cancellation time in UTC
# @return [DateTime]
def canceled_at
Time.at(user_cancellation_time_millis / 1000).utc.to_datetime if user_cancellation_time_millis
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/product_purchases/product_purchase.rb | lib/candy_check/play_store/product_purchases/product_purchase.rb | module CandyCheck
module PlayStore
module ProductPurchases
# Describes a successful response from the PlayStore verification server
class ProductPurchase
include Utils::AttributeReader
# Returns the raw ProductPurchase from google-api-client gem
# @return [Google::Apis::AndroidpublisherV3::ProductPurchase]
attr_reader :product_purchase
# Purchased product (0 is purchased, don't ask me why)
# @see https://developers.google.com/android-publisher/api-ref/purchases/products
PURCHASE_STATE_PURCHASED = 0
# A consumed product
CONSUMPTION_STATE_CONSUMED = 1
# Initializes a new instance which bases on a JSON result
# from PlayStore API servers
# @param product_purchase [Google::Apis::AndroidpublisherV3::ProductPurchase]
def initialize(product_purchase)
@product_purchase = product_purchase
end
# The purchase state of the order. Possible values are:
# * 0: Purchased
# * 1: Cancelled
# @return [Integer]
def purchase_state
@product_purchase.purchase_state
end
# The consumption state of the inapp product. Possible values are:
# * 0: Yet to be consumed
# * 1: Consumed
# @return [Integer]
def consumption_state
@product_purchase.consumption_state
end
# The developer payload which was used when buying the product
# @return [String]
def developer_payload
@product_purchase.developer_payload
end
# This kind represents an inappPurchase object in the androidpublisher
# service.
# @return [String]
def kind
@product_purchase.kind
end
# The order id
# @return [String]
def order_id
@product_purchase.order_id
end
# The time the product was purchased, in milliseconds since the
# epoch (Jan 1, 1970)
# @return [Integer]
def purchase_time_millis
@product_purchase.purchase_time_millis
end
# A product may be purchased or canceled. Ensure a receipt
# is valid before granting some candy
# @return [Boolean]
def valid?
purchase_state == PURCHASE_STATE_PURCHASED
end
# A purchased product may already be consumed. In this case you
# should grant candy even if it's valid.
# @return [Boolean]
def consumed?
consumption_state == CONSUMPTION_STATE_CONSUMED
end
# The date and time the product was purchased
# @return [DateTime]
def purchased_at
Time.at(purchase_time_millis / 1000).utc.to_datetime
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/product_purchases/product_verification.rb | lib/candy_check/play_store/product_purchases/product_verification.rb | module CandyCheck
module PlayStore
module ProductPurchases
# Verifies a purchase token against the PlayStore API
# The call return either a {ProductPurchase} or a {VerificationFailure}
class ProductVerification
# @return [String] the package_name which will be queried
attr_reader :package_name
# @return [String] the item id which will be queried
attr_reader :product_id
# @return [String] the token for authentication
attr_reader :token
# Initializes a new call to the API
# @param package_name [String]
# @param product_id [String]
# @param token [String]
def initialize(package_name:, product_id:, token:, authorization:)
@package_name = package_name
@product_id = product_id
@token = token
@authorization = authorization
end
# Performs the verification against the remote server
# @return [ProductPurchase] if successful
# @return [VerificationFailure] otherwise
def call!
verify!
if valid?
CandyCheck::PlayStore::ProductPurchases::ProductPurchase.new(@response[:result])
else
CandyCheck::PlayStore::VerificationFailure.new(@response[:error])
end
end
private
def valid?
@response[:result]&.purchase_state && @response[:result]&.consumption_state
end
def verify!
service = CandyCheck::PlayStore::AndroidPublisherService.new
service.authorization = @authorization
service.get_purchase_product(package_name, product_id, token) do |result, error|
@response = { result: result, error: error }
end
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/product_acknowledgements/response.rb | lib/candy_check/play_store/product_acknowledgements/response.rb | module CandyCheck
module PlayStore
module ProductAcknowledgements
class Response
def initialize(result:, error_data:)
@result = result
@error_data = error_data
end
def acknowledged?
!!result
end
def error
return unless error_data
{ status_code: error_data.status_code, body: error_data.body }
end
attr_reader :result, :error_data
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/play_store/product_acknowledgements/acknowledgement.rb | lib/candy_check/play_store/product_acknowledgements/acknowledgement.rb | module CandyCheck
module PlayStore
module ProductAcknowledgements
# Verifies a purchase token against the PlayStore API
class Acknowledgement
# @return [String] the package_name which will be queried
attr_reader :package_name
# @return [String] the item id which will be queried
attr_reader :product_id
# @return [String] the token for authentication
attr_reader :token
# Initializes a new call to the API
# @param package_name [String]
# @param product_id [String]
# @param token [String]
def initialize(package_name:, product_id:, token:, authorization:)
@package_name = package_name
@product_id = product_id
@token = token
@authorization = authorization
end
def call!
acknowledge!
CandyCheck::PlayStore::ProductAcknowledgements::Response.new(
result: @response[:result], error_data: @response[:error_data],
)
end
private
def acknowledge!
service = CandyCheck::PlayStore::AndroidPublisherService.new
service.authorization = @authorization
service.acknowledge_purchase_product(package_name, product_id, token) do |result, error_data|
@response = { result: result, error_data: error_data }
end
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/utils/attribute_reader.rb | lib/candy_check/utils/attribute_reader.rb | require "date"
module CandyCheck
module Utils
# @private
module AttributeReader
protected
def read(field)
attributes[field]
end
def has?(field)
attributes.key?(field)
end
def read_integer(field)
(val = read(field)) && val.to_i
end
# @return [bool] if value is either 'true' or 'false'
# @return [nil] if value is not 'true'/'false'
def read_bool(field)
val = read(field).to_s
return nil unless %w(false true).include?(val)
val == "true"
end
def read_datetime_from_string(field)
(val = read(field)) && DateTime.parse(val)
end
def read_datetime_from_millis(field)
(val = read_integer(field)) && Time.at(val / 1000).utc.to_datetime
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/utils/config.rb | lib/candy_check/utils/config.rb | module CandyCheck
module Utils
# Very basic base implementation to store and validate a configuration
class Config
# Initializes a new configuration from a hash
# @param attributes [Hash]
def initialize(attributes)
if attributes.is_a?(Hash)
attributes.each do |k, v|
instance_variable_set "@#{k}", v
end
end
validate!
end
protected
# Hook to check for validation error in the sub classes
# should raise an error if not passed
def validate!
# pass
end
# Check for the presence of an attribute
# @param name [String]
# @raise [ArgumentError] if attribute is missing
def validates_presence(name)
return if send(name)
raise ArgumentError, "Configuration field #{name} is missing"
end
# Checks for the inclusion of an attribute
# @param name [String]
# @param values [Array] of possible values
def validates_inclusion(name, *values)
return if values.include?(send(name))
raise ArgumentError, "Configuration field #{name} should be "\
"one of: #{values.join(', ')}"
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/cli/app.rb | lib/candy_check/cli/app.rb | require "thor"
module CandyCheck
module CLI
# Main class for the executable 'candy_check'
# @example
# $> candy_check help
class App < Thor
package_name "CandyCheck"
desc "app_store RECEIPT_DATA", "Verify a base64 encoded AppStore receipt"
method_option :environment,
default: "production",
type: :string,
enum: %w(production sandbox),
aliases: "-e",
desc: "The environment to use for verfication"
method_option :secret,
aliases: "-s",
type: :string,
desc: "The shared secret for auto-renewable subscriptions"
def app_store(receipt)
Commands::AppStore.run(receipt, **options)
end
desc "play_store PACKAGE PRODUCT_ID TOKEN", "Verify PlayStore purchase"
method_option :json_key_file,
required: true,
type: :string,
aliases: "-k",
desc: "The json key file to use for API authentication"
def play_store(package, product_id, token)
Commands::PlayStore.run(package, product_id, token, **options)
end
desc "version", "Print the gem's version"
def version
Commands::Version.run
end
def self.exit_on_failure?
true
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/cli/commands.rb | lib/candy_check/cli/commands.rb | require "candy_check/cli/commands/base"
require "candy_check/cli/commands/app_store"
require "candy_check/cli/commands/play_store"
require "candy_check/cli/commands/version"
module CandyCheck
module CLI
# Module for actual commands which can be invoked from the terminal
module Commands
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/cli/out.rb | lib/candy_check/cli/out.rb | module CandyCheck
module CLI
# A wrapper to output text information to any kind of buffer
# @example
# out = Out.new(std_buffer)
# out.print('something') # => appends 'something' to std_buffer
class Out
# @return [Object] buffer used as default outlet
attr_reader :out
# Bind a new out instance to two buffers
# @param out [Object] STDOUT is default
def initialize(out = $stdout)
@out = out
end
# Prints to +out+
# @param text [String]
def print(text = "")
out.puts text
end
# Pretty print an object to +out+
# @param object [Object]
def pretty(object)
PP.pp(object, out)
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/cli/commands/version.rb | lib/candy_check/cli/commands/version.rb | module CandyCheck
module CLI
module Commands
# Command to show the gem's version
class Version < Base
# Prints the current gem's version to the command line
def run
out.print CandyCheck::VERSION
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/cli/commands/play_store.rb | lib/candy_check/cli/commands/play_store.rb | module CandyCheck
module CLI
module Commands
# Command to verify an PlayStore purchase
class PlayStore < Base
# Prepare a verification run from the terminal
# @param package_name [String]
# @param product_id [String]
# @param token [String]
# @param options [Hash]
# @option options [String] :json_key_file to use for API access
def initialize(package_name, product_id, token, options)
@package = package_name
@product_id = product_id
@token = token
super(options)
end
# Print the result of the verification to the terminal
def run
verifier = CandyCheck::PlayStore::Verifier.new(authorization: authorization)
result = verifier.verify_product_purchase(
package_name: @package,
product_id: @product_id,
token: @token,
)
out.print "#{result.class}:"
out.pretty result
end
private
def authorization
CandyCheck::PlayStore.authorization(options["json_key_file"])
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/cli/commands/base.rb | lib/candy_check/cli/commands/base.rb | module CandyCheck
module CLI
module Commands
# Base for all commands providing simple support for running a single
# command and printing to an {Out} instance
class Base
# Initialize a new command and prepare options for the run
# @param options [Object]
def initialize(options = nil)
@options = options
end
# Run a single instance of a command
# @param args [Array] arguments for the command
# @return [Base] the command after the run
def self.run(*args)
new(*args).tap(&:run)
end
protected
# @return [Object] configuration for the run
attr_reader :options
def out
@out ||= Out.new
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
jnbt/candy_check | https://github.com/jnbt/candy_check/blob/a4f2e80810c62f8e8bff88632a3b866de8eb59d1/lib/candy_check/cli/commands/app_store.rb | lib/candy_check/cli/commands/app_store.rb | module CandyCheck
module CLI
module Commands
# Command to verify an AppStore receipt token
class AppStore < Base
# Prepare a verification run from the terminal
# @param receipt [String]
# @param options [Hash]
# @option options [String] :secret A shared secret to use
# @option options [String] :environment The environment to use
def initialize(receipt, options)
@receipt = receipt
super(options)
end
# Print the result of the verification to the terminal
def run
verifier = CandyCheck::AppStore::Verifier.new(config)
result = verifier.verify(@receipt, options[:secret])
out.print "#{result.class}:"
out.pretty result
end
private
def config
CandyCheck::AppStore::Config.new(
environment: options[:environment].to_sym,
)
end
end
end
end
end
| ruby | MIT | a4f2e80810c62f8e8bff88632a3b866de8eb59d1 | 2026-01-04T17:53:38.935512Z | false |
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/tools.rb | tools.rb |
module DNE
# Tools to support debug and implementation.
# I just want to be able to call `show_image` anywhere in the code and
# be presented with something sensible.
module Tools
def self.show_image img
shape = nil
to_disp = case img
when NArray, NImage
img = img.cast_to NArray # in case it's NImage, need floats for the scaling
shape = [80, 70] # BEWARE of hardcoded values
WB::Tools::Normalization.feature_scaling img, to: [0,1]
else # assume python image
shape = [160, 210] # BEWARE of hardcoded values
NImage[*img.mean(2).ravel.tolist.to_a]
end
WB::Tools::Imaging.display to_disp,
shape: shape, disp_size: [300,300]
end
end
end
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/observation_compressor.rb | observation_compressor.rb | require 'forwardable'
require 'machine_learning_workbench'
module DNE
# Wrap a WB compressor for usage on observations in a UL-ERL + PyCall context
class ObservationCompressor
extend Forwardable
def_delegators :@compr, :ncentrs, :centrs, :ntrains, :ntrains_skip, :encoding, :code_size
attr_reader :downsample, :downsampled_size, :compr, :train_set, :obs_range
def initialize type:, orig_size:, obs_range:, downsample: nil, **compr_args
@obs_range = obs_range
@downsample = downsample
raise ArgumentError, "Only downward scaling" if downsample.any? { |v| v < 1 }
@downsampled_size = orig_size.zip(downsample).map { |s,r| s/r }
centr_size = downsampled_size.reduce(:*)
compr_class = begin
WB::Compressor.const_get(type)
rescue NameError => err
raise ArgumentError, "Unrecognized compressor type `#{type}`"
end
@compr = compr_class.new **compr_args.merge({dims: centr_size})
@train_set = []
end
# Reset the centroids to something else than random noise
# TODO: refactor
def reset_centrs img, proport: nil
img = normalize img if img.kind_of? NImage
compr.init_centrs base: img, proport: proport
end
# Normalize an observation into a form preferable for the WB compressor
# @param observation [NImage] an observation coming from the environment
# through `AtariWrapper` (already resampled and converted to NArray)
# @return [NArray] the normalized observation ready for processing
def normalize observation
WB::Tools::Normalization.feature_scaling observation,
from: obs_range, to: compr.vrange
# from: [observation.class::MIN, observation.class::MAX], to: compr.vrange
end
# Encodes an observation using the underlying compressor
# @param observation [NArray]
# @return [NArray] encoded observation
def encode obs
obs = normalize(obs) if obs.kind_of? NImage
compr.encode obs
end
# Compute the novelty of an observation as aggregated reconstruction error
# @param observation [NArray]
# @param code [Array]
# @return [Float] novelty score
def novelty obs, code
compr.reconstr_error(obs, code: code).abs.mean
end
# Train the compressor on the observations collected so far
def train
# TODO: I can save the most similar centroid and corresponding simil in the
# training set, then the training should be just some sums! Super fast!
# NOTE: if I go back to using centroid training at all...
# NOTE: careful if you're using normalized centroids from here on
compr.train train_set.map &method(:normalize)
@train_set = []
end
# TODO: move most of this to VQ?
# Show a centroid using ImageMagick
def show_centroid idx, disp_size: [300,300]
WB::Tools::Imaging.display centrs[idx, true], shape: downsampled_size.reverse, disp_size: disp_size
end
# Show centroids using ImageMagick
def show_centroids to_disp=ncentrs, disp_size: [300, 300], wait: true
to_disp = to_disp.times unless to_disp.kind_of? Enumerable
to_disp.each &method(:show_centroid)
puts "#{to_disp.size}/#{centrs.shape.first} centroids displayed"
if wait
puts "Hit return to close them"
gets
end
nil
ensure
WB::Tools::Execution.kill_forks
end
# Save centroids to files using ImageMagick
def save_centroids to_save=ncentrs, disp_size: [700, 800]
require 'rmagick'
to_save = to_save.times unless to_save.kind_of? Enumerable
to_save.each do |idx|
img = WB::Tools::Imaging.narr_to_img centrs[idx, true], shape: downsampled_size.reverse
img.resize!(*disp_size, Magick::TriangleFilter,0.51) if disp_size
img.write "centr_#{idx}.pdf"
end
puts "#{to_save.size}/#{centrs.shape.first} centroids saved"
end
# Returns a hash of values to maintain from parallel execution
# See `AtariUlerlExperiment#gen_fit_fn`
def parall_info
{ tset: train_set,
utility: compr.utility,
ncodes: compr.ncodes
}
end
# Loads data from a hash generated by forks using `parall_info`
# See `#parall_info` and `AtariUlerlExperiment#gen_fit_fn`
def add_from_parall_info tset:, utility:, ncodes:
# NOTE: here tset contains `NImage`s, will convert into `NArray`s in `#train`
@train_set += tset # this already works regardless of the size of tset
compr.utility = case compr.encoding_type
when :ensemble, :norm_ensemble, :sparse_coding # cumulative moving average
((compr.ncodes * compr.utility) + (ncodes * utility)) / (compr.ncodes + ncodes)
when :most_similar_ary # counts occurrencies in array
compr.utility + utility
when :most_similar # only counts occurrencies
compr.utility[util] += 1
else raise ArgumentError "how did you even get here?"
end
compr.ncodes += ncodes
end
end
end
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/gym_test.rb | gym_test.rb |
def test_pycall_gym
ENV["PYTHON"] = `which python3`.strip # set python3 path for PyCall
require 'pycall/import' # https://github.com/mrkn/pycall.rb/
include PyCall::Import
pyimport :gym
env = gym.make('CartPole-v1')
nsteps = 100
env.reset
env.render
nsteps.times do |i|
selected_action = env.action_space.sample
env.step(selected_action)
env.render
end
end
puts "Choose your test: [a,b]"
case gets.strip
when 'a'
puts "The test works fine by itself"
test_pycall_gym
puts "and if I later require `numo/narray`, everything is fine"
require 'numo/narray'
puts "I can run the test again with no problem"
test_pycall_gym
when 'b'
puts "Requiring `'numo/narray'` before the first `pyimport :gym` makes PyCall crash"
require 'numo/narray'
test_pycall_gym
else
puts "Please choose between 'a' and 'b' next time."
end
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/atari_ulerl_experiment.rb | atari_ulerl_experiment.rb | require 'forwardable'
require_relative 'gym_experiment'
require_relative 'observation_compressor'
require_relative 'atari_wrapper'
require_relative 'tools'
module DNE
# TODO: why doesn't it work when I use UInt8? We're in [0,255]!
NImage = Xumo::UInt32 # set a single data type for images
# Specialized GymExperiment class for Atari environments and UL-ERL.
class AtariUlerlExperiment < GymExperiment
attr_reader :compr, :resize, :preproc, :nobs_per_ind, :ntrials_per_ind
def initialize config
## Why would I wish:
# compr before super (current choice)
# - net.struct => compr.code_size
# super before compr
# - config[:run][:debug] # can live without
# - compr.dims => AtariWrapper.downsample # gonna duplicate the process, beware
# - obs size => AtariWrapper orig_size
puts "Initializing compressor" # if debug
compr_opts = config.delete :compr # otherwise unavailable for debug
seed_proport = compr_opts.delete :seed_proport
@nobs_per_ind = compr_opts.delete :nobs_per_ind
@preproc = compr_opts.delete :preproc
@ntrials_per_ind = config[:run].delete :ntrials_per_ind
@compr = ObservationCompressor.new **compr_opts
# default ninputs for network
config[:net][:ninputs] ||= compr.code_size
puts "Loading Atari OpenAI Gym environment" # if debug
super config
# initialize the centroids based on the env's reset obs
compr.reset_centrs single_env.reset_obs, proport: seed_proport if seed_proport
end
# Initializes the Atari environment
# @note python environments interfaced through pycall
# @param type [String] the type of environment as understood by OpenAI Gym
# @param [Array<Integer,Integer>] optional downsampling for rows and columns
# @return an initialized environment
# NEW ENVS CURRENTLY SPAWNED IN PARALL CHILD
# means that they'll get respawned every time
# should instead update @parall_env in parent after every pop
# for now keep like this, spawning is fast and gets deleted with child process
# we are ensuring there's one per ind and that's what matters
# note the same env is used for multiple evals on each ind
def init_env type:
# puts " initializing env" if debug
# print "(newenv) " #if debug
AtariWrapper.new gym.make(type), downsample: compr.downsample,
skip_type: skip_type, preproc: preproc
end
# How to aggregate observations coming from a sequence of noops
OBS_AGGR = {
avg: -> (obs_lst) { obs_lst.reduce(:+) / obs_lst.size},
new: -> (obs_lst) { obs_lst.first - env.reset_obs},
first: -> (obs_lst) { obs_lst.first },
last: -> (obs_lst) { obs_lst.last }
}
# Return the fitness of a single genotype
# @param genotype the individual to be evaluated
# @param env the environment to use for the evaluation
# @param render [bool] whether to render the evaluation on screen
# @param nsteps [Integer] how many interactions to run with the game. One interaction is one action choosing + enacting followed by `skip_frames` frame skips
def fitness_one genotype, env: single_env, render: false, nsteps: max_nsteps, aggr_type: :last
puts "Evaluating one individual" if debug
puts " Loading weights in network" if debug
net.deep_reset
net.load_weights genotype
observation = env.reset
# require 'pry'; binding.pry unless observation == env.reset_obs # => check passed, add to tests
env.render if render
tot_reward = 0
# # set of observations with highest novelty, representative of the ability of the individual
# # to obtain novel observations from the environment => hence reaching novel env states
# represent_obs = []
puts "IGNORING `nobs_per_ind=#{nobs_per_ind}` (random sampling obs)" if nobs_per_ind
represent_obs = observation
nobs = 1
puts " Running (max_nsteps: #{max_nsteps})" if debug
runtime = nsteps.times do |i|
code = compr.encode observation
# print code.to_a
selected_action = action_for code
obs_lst, rew, done, info_lst = env.execute selected_action, skip_frames: skip_frames
# puts "#{obs_lst}, #{rew}, #{done}, #{info_lst}" if debug
observation = OBS_AGGR[aggr_type].call obs_lst
tot_reward += rew
## NOTE: SWAP COMMENTS ON THE FOLLOWING to switch to novelty-based obs selection
# # The same observation represents the state both for action selection and for individual novelty
# # OPT: most obs will most likely have lower novelty, so place it first
# # TODO: I could add here a check if obs is already in represent_obs; in fact
# # though the probability is low (sequential markovian fully-observable env)
# novelty = compr.novelty observation, code
# represent_obs.unshift [observation, novelty]
# represent_obs.sort_by! &:last
# represent_obs.shift if represent_obs.size > nobs_per_ind
# Random sampling for representative obs
nobs += 1
represent_obs = observation if rand < 1.0/nobs
# Image selection by random sampling
env.render if render
break i if done
end
compr.train_set << represent_obs
# for novelty:
# represent_obs.each { |obs, _nov| compr.train_set << obs }
puts "=> Done! fitness: #{tot_reward}" if debug
# print tot_reward, ' ' # if debug
print "#{tot_reward}(#{runtime}) "
tot_reward
end
# Builds a function that return a list of fitnesses for a list of genotypes.
# Since Parallel runs in separate fork, this overload is needed to fetch out
# the training set before returning the fitness to the optimizer
# @param type the type of computation
# @return [lambda] function that evaluates the fitness of a list of genotype
# @note returned function has param genotypes [Array<gtype>] list of genotypes, return [Array<Numeric>] list of fitnesses for each genotype
def gen_fit_fn type, ntrials: ntrials_per_ind
return super unless type.nil? || type == :parallel
nprocs = Parallel.processor_count - 1 # it's actually faster this way
puts "Running in parallel on #{nprocs} processes"
-> (genotypes) do
print "Fits: "
fits, parall_infos = Parallel.map(0...genotypes.shape.first,
in_processes: nprocs, isolation: true) do |i|
# env = parall_envs[Parallel.worker_number]
env = parall_envs[i] # leveraging dynamic env allocation
# fit = fitness_one genotypes[i, true], env: env
fits = ntrials.times.map { fitness_one genotypes[i, true], env: env }
fit = fits.to_na.mean
print "[m#{fit}] "
[fit, compr.parall_info]
end.transpose
puts # newline here because I'm done `print`ing all ind fits
puts "Exporting training images"
parall_infos.each &compr.method(:add_from_parall_info)
puts "Training optimizer"
fits.to_na
end
end
# Return an action for an encoded observation
# The neural network is activated on the code, then its output is
# interpreted as a corresponding action
# @param code [Array] encoding for the current observation
# @return [Integer] action
# TODO: alternatives like softmax and such
def action_for code
output = net.activate code
nans = output.isnan
# this is a pretty reliable bug indicator
raise "\n\n\tNaN network output!!\n\n" if nans.any?
# action = output[0...6].max_index # limit to 6 actions
action = output.max_index
end
def update_opt
return false if @curr_ninputs == compr.code_size
puts " code_size: #{compr.code_size}"
diff = compr.code_size - @curr_ninputs
@curr_ninputs = compr.code_size
pl = net.struct.first(2).reduce(:*)
nw = diff * net.struct[1]
new_mu_val = 0 # value for the new means (0)
new_var_val = 0.0001 # value for the new variances (diagonal of covariance) (<<1)
new_cov_val = 0 # value for the other covariances (outside diagonal) (0)
old = case opt_type
when :XNES then opt
when :BDNES then opt.blocks.first
else raise NotImplementedError, "refactor and fill in this case block"
end
new_mu = old.mu.insert pl, [new_mu_val]*nw
new_sigma = old.sigma.insert [pl]*nw, new_cov_val, axis: 0
new_sigma = new_sigma.insert [pl]*nw, new_cov_val, axis: 1
new_sigma.diagonal[pl...(pl+nw)] = new_var_val
new_nes = NES::XNES.new new_mu.size, old.obj_fn, old.opt_type,
parallel_fit: old.parallel_fit, mu_init: new_mu, sigma_init: new_sigma,
**opt_opt
new_nes.instance_variable_set :@rng, old.rng # ensure rng continuity
new_nes.instance_variable_set :@best, old.best # ensure best continuity
case opt_type
when :XNES
@opt = new_nes
puts " new opt dims: #{opt.ndims}"
when :BDNES
opt.blocks[0] = new_nes
opt.ndims_lst[0] = new_mu.size
puts " new opt dims: #{opt.ndims_lst}"
else raise NotImplementedError, "refactor and fill in this case block"
end
puts " popsize: #{opt.popsize}"
puts " lrate: #{opt.lrate}"
# FIXME: I need to run these before I can use automatic popsize again!
# => update popsize in bdnes and its blocks before using it again
# if opt.kind_of? BDNES or something
# opt.instance_variable_set :popsize, blocks.map(&:popsize).max
# opt.blocks.each { |xnes| xnes.instance_variable_set :@popsize, opt.popsize }
# update net, since inputs have changed
@net = init_net netopts.merge({ninputs: compr.code_size})
puts " new net struct: #{net.struct}"
return true
end
# Run the experiment
def run ngens: max_ngens
@curr_ninputs = compr.code_size
ngens.times do |i|
$ngen = i # allows for conditional debugger calls `binding.pry if $ngen = n`
puts Time.now
puts "# Gen #{i+1}/#{ngens}"
# it just makes more sense run first, even though at first gen the trainset is empty
puts "Training compressor" if debug
compr.train
update_opt # if I have more centroids, I should update opt
opt.train
# Note: data analysis is done by extracting statistics from logs using regexes.
# Just `puts` anything you'd like to track, and save log to file
puts "Best fit so far: #{opt.best.first} -- " \
"Fit mean: #{opt.last_fits.mean} -- " \
"Fit stddev: #{opt.last_fits.stddev}\n" \
"Mu mean: #{opt.mu.mean} -- " \
"Mu stddev: #{opt.mu.stddev} -- " \
"Conv: #{opt.convergence}"
break if termination_criteria&.call(opt) # uhm currently unused
end
end
# Save experiment current state to file
def dump fname="dumps/atari_#{Time.now.strftime '%y%m%d_%H%M'}.bin"
raise NotImplementedError, "doesn't work with BDNES atm" if config[:opt][:type] == :BDNES
File.open(fname, 'wb') do |f|
Marshal.dump(
{ config: config,
best: opt.best.last,
mu: opt.mu,
sigma: opt.sigma,
centrs: compr.centrs
}, f)
end
puts "Experiment data dumped to `#{fname}`"
true
end
# Load experiment state from file
def load fname=Dir["dumps/atari_*.bin"].sort.last
hsh = File.open(fname, 'r') { |f| Marshal.load f }
initialize hsh[:config]
opt.instance_variable_set :@best, hsh[:best]
opt.instance_variable_set :@mu, hsh[:mu]
opt.instance_variable_set :@sigma, hsh[:sigma]
compr.instance_variable_set :@centrs, hsh[:centrs]
# Uhm haven't used that yet...
# what else needs to be done in order to be able to run `#show_ind` again?
puts "Experiment data loaded from `#{fname}`"
true
end
# Return an initialized exp from state on file
def self.load fname=Dir["atari_*.bin"].sort.last
# will initialize twice, but we're sure to have a conform `hsh[:config]`
hsh = File.open(fname, 'r') { |f| Marshal.load f }
new(hsh[:config]).tap { |exp| exp.load fname }
end
end
end
puts "USAGE: `bundle exec ruby experiments/atari.rb`" if __FILE__ == $0
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/atari_wrapper.rb | atari_wrapper.rb | require 'numo/narray'
module DNE
# Convenience wrapper for the Atari OpenAI Gym environments
class AtariWrapper
attr_reader :gym_env, :reset_obs, :reset_obs_py, :act_type, :act_size,
:obs_size, :skip_type, :downsample, :preproc, :row_div, :col_div
extend Forwardable
def_delegator :@gym_env, :render
def initialize gym_env, downsample: nil, skip_type: nil, preproc: nil
@skip_type = skip_type
@downsample = downsample
@preproc = preproc
@gym_env = gym_env
@reset_obs = reset
act_type, act_size = gym_env.action_space.to_s.match(/(.*)\((\d*)\)/).captures
raise "Not Atari act space" unless act_size.to_i.between?(6,18) && act_type == 'Discrete'
@act_type = act_type.downcase.to_sym
@act_size = Integer(act_size)
@obs_size = @reset_obs.size
end
# Converts pyimg into NArray, applying optional pre-processing and resampling
def to_img pyimg
# subtract `reset_obs` to clear background => imgs as "what changes"
pyimg -= reset_obs_py if preproc == :subtr_bg
# resample to target resolution
pyimg = pyimg[(0..-1).step(downsample[0]),
(0..-1).step(downsample[1])] if downsample
# average color channels, flatten to 1d array, convert to NArray
NImage[*pyimg.mean(2).ravel.tolist.to_a]
end
# calls reset, converts to NArray img
def reset
@reset_obs_py = gym_env.reset
to_img reset_obs_py
end
# converts the gym's python response to ruby
def gym_to_rb gym_ans
obs, rew, done, info = gym_ans.to_a
[to_img(obs), rew, done, info]
end
# executes an action, then frameskips; returns aggregation
def execute act, skip_frames: 0, type: skip_type
act_ans = gym_env.step(act)
skip_ans = skip_frames.times.map do
GymExperiment::SKIP_TYPE[type].call(act, gym_env)
end
all_ans = skip_ans.unshift(act_ans)
obs_lst, rew_lst, done_lst, info_lst = all_ans.map(&method(:gym_to_rb)).transpose
# obs_lst.each &DNE::Tools.method(:show_image) if debug
rew = rew_lst.reduce :+
done = done_lst.any?
[obs_lst, rew, done, info_lst]
end
end
end
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.