facebook.rb 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. # Copyright (C) 2012-2015 Zammad Foundation, http://zammad-foundation.org/
  2. require 'koala'
  3. class Facebook
  4. attr_accessor :client, :account
  5. =begin
  6. client = Facebook.new('user_or_page_access_token')
  7. =end
  8. def initialize(access_token)
  9. connect(access_token)
  10. end
  11. =begin
  12. reconnect with other access_token
  13. client.connect('user_or_page_access_token')
  14. =end
  15. def connect(access_token)
  16. @client = Koala::Facebook::API.new(access_token)
  17. end
  18. =begin
  19. disconnect client
  20. client.disconnect
  21. =end
  22. def disconnect
  23. return if !@client
  24. @client = nil
  25. end
  26. =begin
  27. get pages of user
  28. pages = client.pages
  29. result
  30. [
  31. {
  32. id: '12345',
  33. name: 'Some Page Name',
  34. access_token, 'some_access_token_for_page',
  35. },
  36. ]
  37. =end
  38. def pages
  39. pages = []
  40. @client.get_connections('me', 'accounts').each do |page|
  41. pages.push(
  42. id: page['id'],
  43. name: page['name'],
  44. access_token: page['access_token'],
  45. )
  46. end
  47. pages
  48. end
  49. =begin
  50. get current user
  51. pages = current_user
  52. result
  53. {
  54. 'id' => '1234567890123456',
  55. 'name' => 'Page/User Name',
  56. 'access_token' => 'some_acces_token'
  57. }
  58. =end
  59. def current_user
  60. @client.get_object('me')
  61. end
  62. =begin
  63. get user of comment/post
  64. pages = user(comment_or_post)
  65. result
  66. ???
  67. =end
  68. def user(item)
  69. return if !item['from']
  70. return if !item['from']['id']
  71. cache_key = "FB:User:Lookup:#{item['from']['id']}"
  72. cache = Cache.get(cache_key)
  73. return cache if cache
  74. begin
  75. result = @client.get_object(item['from']['id'], fields: 'first_name,last_name,email')
  76. rescue
  77. result = @client.get_object(item['from']['id'], fields: 'name')
  78. end
  79. if result
  80. Cache.write(cache_key, result, { expires_in: 15.minutes })
  81. end
  82. result
  83. end
  84. def to_user(item)
  85. Rails.logger.debug { 'Create user from item...' }
  86. Rails.logger.debug { item.inspect }
  87. # do item_user lookup
  88. item_user = user(item)
  89. return if !item_user
  90. auth = Authorization.find_by(uid: item_user['id'], provider: 'facebook')
  91. # create or update user
  92. user_data = {
  93. image_source: "https://graph.facebook.com/#{item_user['id']}/picture?type=large",
  94. }
  95. if auth
  96. user = User.find(auth.user_id)
  97. map = {
  98. #note: 'description',
  99. }
  100. # ignore if value is already set
  101. map.each do |target, source|
  102. next if user[target].present?
  103. new_value = tweet_user.send(source).to_s
  104. next if new_value.blank?
  105. user_data[target] = new_value
  106. end
  107. user.update!(user_data)
  108. else
  109. user_data[:login] = item_user['id']
  110. if item_user['first_name'] && item_user['last_name']
  111. user_data[:firstname] = item_user['first_name']
  112. user_data[:lastname] = item_user['last_name']
  113. else
  114. user_data[:firstname] = item_user['name']
  115. end
  116. user_data[:active] = true
  117. user_data[:role_ids] = Role.signup_role_ids
  118. user = User.create(user_data)
  119. end
  120. if user_data[:image_source]
  121. avatar = Avatar.add(
  122. object: 'User',
  123. o_id: user.id,
  124. url: user_data[:image_source],
  125. source: 'facebook',
  126. deletable: true,
  127. updated_by_id: user.id,
  128. created_by_id: user.id,
  129. )
  130. # update user link
  131. if avatar && user.image != avatar.store_hash
  132. user.image = avatar.store_hash
  133. user.save
  134. end
  135. end
  136. # create authorization
  137. if !auth
  138. auth_data = {
  139. uid: item_user['id'],
  140. username: item_user['id'],
  141. user_id: user.id,
  142. provider: 'facebook'
  143. }
  144. Authorization.create(auth_data)
  145. end
  146. UserInfo.current_user_id = user.id
  147. user
  148. end
  149. def to_ticket(post, group_id, channel, page)
  150. Rails.logger.debug { 'Create ticket from post...' }
  151. Rails.logger.debug { post.inspect }
  152. Rails.logger.debug { group_id.inspect }
  153. user = to_user(post)
  154. return if !user
  155. # prepare title
  156. title = post['message']
  157. if title.length > 80
  158. title = "#{title[0, 80]}..."
  159. end
  160. state = get_state(page, post)
  161. Ticket.create!(
  162. customer_id: user.id,
  163. title: title,
  164. group_id: group_id,
  165. state: state,
  166. priority: Ticket::Priority.find_by(name: '2 normal'),
  167. preferences: {
  168. channel_id: channel.id,
  169. channel_fb_object_id: page['id'],
  170. facebook: {
  171. permalink_url: post['permalink_url'],
  172. }
  173. },
  174. )
  175. end
  176. def to_article(post, ticket, page)
  177. Rails.logger.debug { 'Create article from post...' }
  178. Rails.logger.debug { post.inspect }
  179. Rails.logger.debug { ticket.inspect }
  180. user = to_user(post)
  181. return if !user
  182. to = nil
  183. if post['to'] && post['to']['data']
  184. post['to']['data'].each do |to_entry|
  185. if !to
  186. to = ''
  187. else
  188. to += ', '
  189. end
  190. to += to_entry['name']
  191. end
  192. end
  193. feed_post = {
  194. from: post['from']['name'],
  195. to: to,
  196. body: post['message'],
  197. message_id: post['id'],
  198. type_id: Ticket::Article::Type.find_by(name: 'facebook feed post').id,
  199. }
  200. articles = []
  201. articles.push(feed_post)
  202. if post['comments'] && post['comments']['data']
  203. articles += nested_comments(post['comments']['data'], post['id'])
  204. end
  205. base_url = nil
  206. if ticket.preferences['facebook'] && ticket.preferences['facebook']['permalink_url']
  207. base_url = ticket.preferences['facebook']['permalink_url']
  208. end
  209. articles.each do |article|
  210. next if Ticket::Article.find_by(message_id: article[:message_id])
  211. # set ticket state to open if not new
  212. ticket_state = get_state(page, post, ticket)
  213. if ticket_state.name != ticket.state.name
  214. ticket.state = ticket_state
  215. ticket.save!
  216. end
  217. links = []
  218. if base_url
  219. url = base_url
  220. realtive_id = article[:message_id].split('_')[1]
  221. if realtive_id
  222. url += "?comment_id=#{realtive_id}"
  223. end
  224. links = [
  225. {
  226. url: url,
  227. target: '_blank',
  228. name: 'on Facebook',
  229. },
  230. ]
  231. end
  232. article = {
  233. #to: @account['name'],
  234. ticket_id: ticket.id,
  235. internal: false,
  236. sender_id: Ticket::Article::Sender.lookup(name: 'Customer').id,
  237. created_by_id: 1,
  238. updated_by_id: 1,
  239. preferences: {
  240. links: links,
  241. },
  242. }.merge(article)
  243. Ticket::Article.create(article)
  244. end
  245. end
  246. def to_group(post, group_id, channel, page)
  247. Rails.logger.debug { 'import post' }
  248. return if !post['message']
  249. ticket = nil
  250. # use transaction
  251. Transaction.execute(reset_user_id: true) do
  252. existing_article = Ticket::Article.find_by(message_id: post['id'])
  253. ticket = if existing_article
  254. existing_article.ticket
  255. else
  256. to_ticket(post, group_id, channel, page)
  257. end
  258. to_article(post, ticket, page)
  259. end
  260. ticket
  261. end
  262. def from_article(article)
  263. post = nil
  264. if article[:type] != 'facebook feed comment'
  265. raise "Can't handle unknown facebook article type '#{article[:type]}'."
  266. end
  267. Rails.logger.debug { 'Create feed comment from article...' }
  268. post = @client.put_comment(article[:in_reply_to], article[:body])
  269. Rails.logger.debug { post.inspect }
  270. @client.get_object(post['id'])
  271. end
  272. private
  273. def get_state(page, post, ticket = nil)
  274. # no changes in post is from page user it self
  275. if post['from'] && post['from']['id'].to_s == page['id'].to_s
  276. if !ticket
  277. return Ticket::State.find_by(name: 'closed') if !ticket
  278. end
  279. return ticket.state
  280. end
  281. state = Ticket::State.find_by(default_create: true)
  282. return state if !ticket
  283. return ticket.state if ticket.state_id == state.id
  284. Ticket::State.find_by(default_follow_up: true)
  285. end
  286. def access_token_for_page(lookup)
  287. access_token = nil
  288. pages.each do |page|
  289. next if !lookup[:page_id] && !lookup[:page]
  290. next if lookup[:page_id] && lookup[:page_id].to_s != page[:id]
  291. next if lookup[:page] && lookup[:page] != page[:name]
  292. access_token = page[:access_token]
  293. break
  294. end
  295. access_token
  296. end
  297. def nested_comments(comments, in_reply_to)
  298. Rails.logger.debug { 'Fetching nested comments...' }
  299. Rails.logger.debug { comments.inspect }
  300. result = []
  301. return result if comments.blank?
  302. comments.each do |comment|
  303. user = to_user(comment)
  304. next if !user
  305. article_data = {
  306. from: "#{user.firstname} #{user.lastname}",
  307. body: comment['message'],
  308. message_id: comment['id'],
  309. type_id: Ticket::Article::Type.find_by(name: 'facebook feed comment').id,
  310. in_reply_to: in_reply_to
  311. }
  312. result.push(article_data)
  313. sub_comments = @client.get_object("#{comment['id']}/comments", fields: 'id,from,to,message,created_time')
  314. sub_articles = nested_comments(sub_comments, comment['id'])
  315. result += sub_articles
  316. end
  317. result
  318. end
  319. end