fetch larger images from Facebook with Koala using the get_connection method - ruby

The documentation of the Koala gem gives an example how to fetch posts from Facebook, including a picture.
client = Koala::Facebook::API.new(oauth_token)
client.get_connection('someuser', 'posts',
{limit: #options[:max_items],
fields: ['message', 'id', 'from', 'type',
'picture', 'link', 'created_time', 'updated_time'
]})
Below this example the documentation makes a note:
You can pass a ‘type’ hash key with a value of ‘small’, ‘normal’, ‘large’, or ‘square’ to obtain different picture sizes, with the default being ‘square’. Also, you may need the user_photos permission.
Unfortunately, this doesn't seem to work:
client.get_connection("officialstackoverflow", "posts",
{limit: 5, type: "large", fields: [:picture, :message, :type]})
Unfortunately, I get the same picture as I would get when omitting the type param. How do I have to pass the type hash correctly?

Related

Mailchimp API Node - create campaign for list based on tags

I'm making an async api request with a firebase cloud function to create a campaign within mailchimp for a specific set of users from a list. I read in the documentation that this can be done with tags this way I can build my own structure. I'm building a donation system for a nonprofit and would like the tag to represent the name of a client who is currently being donated to.
Below is my firebase function. I'm stuck at the segment_opts object. I want to define a segment based on whether the list member has a tag equivalent my clients name.
The doc says segment_opts is "An object representing all segmentation options. This object should contain a saved_segment_id to use an existing segment, or you can create a new segment by including both match and conditions options.". I don't have any other segments set up so I figured I'd create a new one that specifies the tags to contain the client's name.
This post helped me get to this point. Stackoverflow post
I now see that condition is supposed to be a Segment Type but in the dropdown I don't see an option for Tags. Here is a link to the documentation reference. Reference
const response = await mailchimp.post('/campaigns', {
type: 'regular',
recipients: {
list_id: functions.config().mailchimp.test,
segment_opts: {
"match": "any",
"conditions": match: 'any',
conditions: [
{
condition_type: 'StaticSegment',
field: 'static_segment',
op: 'static_is',
value: ??? (Int),
},
],
}
},
});
For now I removed segment_opts and will settle on sending campaign to entire list until I figure out how to segment by tags. This version works and creates a campaign within my mailchimp account and from the UI I can see the segment options offered in the documentation but don't see an option to filter by tags
const response = await mailchimp.post('/campaigns', {
type: 'regular',
recipients: {
list_id: functions.config().mailchimp.test,
},
settings: {
subject_line: `${firstName} has been funded!`,
preview_text: `$${goal} has been raised for ${firstName}.`,
title: `${firstName} has been funded`,
from_name: 'Organization name',
reply_to: 'org_email#gmail.com',
},
});
Here is a screenshot of the dropdown options in Mailchimp dashboard.
This is what I have for my campaign segment options. Here I'm checking for two conditions. Is the SITE merge tag = the site variable I pass in, and also does the member belong to the tag/segment called tagName. However, I can't pass a tagName, only a tagId which I lookup beforehand.
'segment_opts':
{
'match': 'all',
'conditions': [
{
'condition_type': 'TextMerge',
'field': 'SITE',
'op': 'is',
'value': site
},
{
'condition_type': 'StaticSegment',
'field': 'static_segment',
'op': 'static_is',
'value': tagId
}
]
}
To get the tagId I use this Python function:
tagId, segments = self.getSegmentIdFromTagName(tagName)
This is the Python code to get the tagId from the tagName, which gets all the Segments/Tags from the system and then looks for the name you pass in:
def getSegmentIdFromTagName(self,reqTagName,segments=None):
audienceId = self.audienceId
reqId = None
if not segments:
segments = self.mcClient.lists.segments.all(list_id=audienceId,get_all=True)
for segment in segments['segments']:
segName = segment['name']
segId = segment['id']
if segName == reqTagName:
reqId = segId
break
return reqId,segments

Array.indexOf isnt a function

The app i made is a movie website that shows movies based on your search. You can also add favorites, however its not linked to your profile. So the solution i came up with was to make another value in the profile initial state in redux.
export const profileInitialState = [
{pass: '123', user: 'daniel', email: 'daniel#123.com', favourites: 'batman' },
]
interface IProfileState {
pass: string,
user: string,
email: string,
favourites?: string
}
and just map it from there
{data.profileReducer.slice(data.profileReducer.indexOf( {user: currUser, pass: password, email: email}, 1)).map(info =>
<p key={data.profileReducer.length + 1.5} > {info.favourites} </p>)}
and even thought it works perfectly in the console, it tell me profileReducer.indexOf is not a function when i implement it in my code.
First of all, Array.prototype.indexOf() can't be used to find the index of object elements in the array.
How to get index of object by its property in JavaScript?. This link describes how you can get the index of array elements.
The error can be caused by a few reasons
data.profileReduceris undefinded or null
data.profileReducer is not an array

Updating Contentful entry with a link/reference field

The Contentful documentation is pretty sparse. I want to update a field on an entry that is a Link to another entry ("Reference" is what they call it in the CMS UI).
Does anyone know what format they want this in when using the Contentful Management API?
type ||= #mgmt.content_types.find(
ENV['CONTENTFUL_SPACE_ID'], 'comments'
)
entry = type.entries.create(
title: params[:title],
article: params[:article]
)
Where :article is the entry ID as a string. This returns:
undefined method `id' for "7L4IpEtsdffds8EsmoWMGIgy":String
Extracted source (around line #74):
#72 case field.type
#73 when ContentType::LINK then
*74 { sys: { type: field.type, linkType: field.link_type, id: attribute.id } } if attribute
#75 when ContentType::ARRAY then
#76 parse_fields_array(attribute)
#77 when ContentType::LOCATION then
I've also tried to replace params[:article] with #client.entry(params[:article]) thinking they may want the whole object but it returns the same error only it sees the same argument as an empty string.
I have also tried this upon #DavidLitvak's suggestion:
link = Contentful::Management::Link.new({
sys: {
type: 'Link',
linkType: 'Entry',
id: params[:article]
}
})
entry = type.entries.create(
title: params[:title],
article: link
)
And although this does not throw an error, the article field shows up without an entry while the title field is populated.
Also note that I am using the Ruby gem: contentful-management.
What you need to send is the Link for the referenced article.
You can do this like:
entry = type.entries.create(
title: params[:title],
article: Contentful::Management::Link.new({
sys: {
id: params[:article],
type: 'Link',
linkType: 'Entry'
}
})
)
You can find more information on how Links work here: https://www.contentful.com/developers/docs/concepts/links/

How to get id from post route in Sinatra

I have a factory that is creating a student. All of the required fields are being filled in and created in the factory. When I post a new student, I am never getting that student, just the one created in the factory? How Can I get the id of the new student from the POST?
students.rb
FactoryGirl.define do
factory :student do
sequence(:id)
sequence(:first_name){|n| "Tom"}
sequence(:last_name) {|n| "Dick"}
sequence(:password) {|n| "test"}
sequence(:email){ |n| "person#{n}#example.com" }
school
end
end
student_spec.rb
require File.dirname(__FILE__) + '/spec_helper'
describe 'admin' do
before :all do
#student=FactoryGirl.create(:student)
end
it 'should save student information' do
params={
post:{
first_name: 'Abraham',
last_name: 'Lincoln',
address: '1400 Pennsylvania Ave.',
city: 'Washington',
state: 'D.C.',
zip: '11111',
email: 'alincoln#whitehouse.gov',
password: 'I cant tell a lie',
major: 'Law',
level: 'Graduate',
employment: 'President',
participation: 'Yes',
participation_research: 'No',
what_doing_now: 'Watching a Play',
ethnicity: 'White',
eth_other: 'none',
education_level: 'Doctorate',
hometown: 'Springfield, IL',
twitter_handle: '#TheRealAbe',
facebook_url: 'therealabe',
prior_education: 'None',
prior_AS: 'None',
prior_BS: 'None',
prior_MS: 'None',
prior_Other: 'None',
awards_honors: 'Ended Civil War',
scholarships: 'Full',
other_inbre_funding: 'yes',
deleted: 'false'
}
}
post '/admin/students/add/', params, {'rack.session'=>{student_id:#student.id, admin_authorized:true}}
updated_student = Student.get(#student.id)
expect(updated_student.first_name).to eql('Abraham')
#expect(updated_student.last_name).to eql('Dick')
#expect(updated_student.address).to eql('1400 Pennsylvania Ave.')
end
end
I can't know for certain without seeing the route, but it seems to me that you are calling POST twice, once in the route, and once within the params hash. However, without seeing your routes, I can't be sure if that's an issue.
Another thought comes from reading your spec. Are you attempting to create a new student(POST) or are you attempting to edit the student? If you are attempting to edit an existing student, this should probably be referring to a separate route, PUT or a PATCH by RESTful conventions. As was mentioned above, a POST route does not need an id, precisely because it is creating a new student, which is where it will create the id, and the id is set by the database, not manually.
a reference to the above: http://guides.rubyonrails.org/v2.3.11/routing.html
I hope this at least points in the right direction. :D

How to get email_ids only (not G+ id) from Events API

I'm using Google APIs to get the user's calendar events and contacts.
While fetching the contacts, I get the response in the following manner:-
[
{
'phones': [],
'image_path': '',
'id': 'ID',
'emails': ['email1'],
'name': ABC
},
{
'phones': [],
'image_path': '',
'id': 'ID',
'emails': ['email2'],
'name': DEF
}
]
While fetching the events, I get the follwoing response:-
[
{
'attendees': [{
'organizer': True,
'displayName': 'ABC',
'id': 'Google+ Id',
'responseStatus': 'accepted'
}, {
'self': True,
'displayName': 'DEF',
'id': 'Google+ id',
'responseStatus': 'accepted'
}],
'organizer': {
'displayName': 'ABC',
'id': 'Google+ id'
},
'creator': {
'displayName': 'ABC',
'id': 'Google+ id'
},
},
{
'organizer': {
'self': True,
'displayName': 'DEF',
'email': 'email2'
},
'creator': {
'self': True,
'displayName': 'DEF',
'email': 'email2'
},
}
]
As you can see that while fetching events, (in attendees, organizers, creators) I get Google+ id in some cases and email_ids in other cases. This does not maintain a uniformity in my code.
Since I've fetched the user contacts as well, and I search the contacts via their email_ids. If I don't get an email_id in attendees, organizers, or creators, I won't be able to reference the contact object.
How can I make sure that I get only the email_ids in attendees, not the Google+ id.
According to Google Calendar API docs
Optional query parameters
alwaysIncludeEmail
boolean Whether to always include a value in the email field for the
organizer, creator and attendees, even if no real email is available
(i.e. a generated, non-working value will be provided). The use of
this option is discouraged and should only be used by clients which
cannot handle the absence of an email address value in the mentioned
places. Optional. The default is False.
Anyway it is not encouraged to use it , because sometimes no real email is available.
Work around:
You can use G+ API to fetch user Email through providing his/her email.
email
This scope requests that your app be given access to:
the user's Google account email address. You access the email address by calling people.get, which returns the emails array (or by calling people.getOpenIdConnect, which returns the email property in OIDC-compliant format).
the name of the Google Apps domain, if any, that the user belongs to. The domain name is returned as the domain property from
people.get (or hd property from getOpenIdConnect)
This email scope is equivalent to and replaces the https://www.googleapis.com/auth/userinfo.email scope.

Resources