facebook.rb 9.0 KB

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