Making timeout for FB requests
[onlineproject.git] / online / app / controllers / user_controller.rb
blobf2122b025ea382dfaf1b5e7df7cb5e01590b22cc
1 require 'timeout'   
3 class UserController < ApplicationController
5   before_filter :source_statistic 
6   ensure_application_is_installed_by_facebook_user
7   before_filter :loading_static  
8   Feed_action = "Play now"
10   def source_statistic
11     @time_counter =  Time.now
12     @time_counter0 =  Time.now
14     if (params[:f]) && (params[:f].to_i != 0)
15       add_stat(0, VISITED, params[:f] ? params[:f].to_i : 0)
16     end         
17   end
18   
19   def loading_static    
20     @statics = Static.find(:first)
21     if @statics == nil
22       render :facebook_error
23     end
24   end
26   def processing_phraze (text_to_process, owner_name, friends_names,gender = "",number_of_friends = 0)
27     text = text_to_process
28     text = text.gsub("{owner_name}",owner_name)
29     text = text.gsub("{friends_names}",friends_names)
30     text = text.gsub("{number_of_friends}",number_of_friends.to_s)
31     text = text.gsub("{his/her}", gender == "female" ? "her": "his")
32     text = text.gsub("{he/she}",gender == "female" ? "she": "he")
33     text = text.gsub("{him/her}",gender == "female" ? "her": "him")
35     return text 
36     #text = text.gsub("{friends_names}",friends_names)
37   end 
38   def permission
39     @userF = session[:facebook_session].user
40     @fbuser = User.find(:first, :conditions => ["uid = ?", @userF.uid])
41     if @fbuser.blank? || @fbuser.deleted
42       if @userF.has_permission?("publish_stream") 
43         @fbuser = User.find(:first, :conditions => ["uid = ?", @userF.uid])
44         
45         if @fbuser && @fbuser.deleted
46           debug_message("User #{session[:facebook_session].user.uid} was already exist but he was in deleted status. So now he is totally deleted and will be added soon")
47           @fbuser.destroy
48           @fbuser = nil
49         end
50         #if user does not exist yet in DB inserting in DB
51         if @fbuser == nil
52           #getting user info
53           begin
54             #if user has  birthday
55             if @userF.birthday != nil
56               birthday_mask = /(\w+)\ (\d+)\, (\d+)/
57               dateOfBirth = birthday_mask.match(@userF.birthday)
58               #if birthday ok for us
59               if (Months[$1] == nil)
60                 birthday = ""
61               else
62                 birthday = Date.new(dateOfBirth[3].to_i,Months[dateOfBirth[1]],dateOfBirth[2].to_i)
63               end
64             else
65               birthday = ""
66             #end if @userF.birthday != nil
67             end
68             #gathering  affiliations
69             @affiliation  = ""
70             if @userF.affiliations
71               @userF.affiliations.each do |one_affiliation|
72                 @affiliation += one_affiliation.name + " | "
73               end
74             end
75             
76             #gathering other params
77             myParams = {
78                           :uid               => @userF.uid,
79                           :birthday          => birthday,
80                           :relation          => @userF.relationship_status,
81                           :gender            => @userF.sex,
82                           :first_name        => @userF.first_name,
83                           :last_name         => @userF.last_name,
84                           :status            => "WAS NOT SET YET" ,
85                           :hometown_location => (@userF.hometown_location != nil) ? @userF.hometown_location.country.to_s + "/"+  @userF.hometown_location.state.to_s + "/" + @userF.hometown_location.city.to_s : "",
86                           :affiliations      => @affiliation,
87                           :usermail          => @userF.email
88                       
89                         }
90           rescue
91             debug_message("Cannot get information about #{session[:facebook_session].user.uid}",false)
92             render :facebook_error
93           else
94             #saving user into DB
95             @fbuser = User.new(myParams)
96             debug_message("User #{session[:facebook_session].user.uid} was added to DB")
97             @fbuser.save
98             add_stat(@userF.uid, PERMISSION)
99            
100           #end of getting user info
101           end
102         #end if @fbuser == nil
103         end 
104         today_question_select 0
105         @question_number = "question1"
106         render :action => @question_number    
107       #if @userF.has_permission?("publish_stream")
108       end
109     else
110       today_question_select 0
111       @question_number = "question1"
112       render :action => @question_number 
113     #if user not in DB
114     end
115   end
116   
117   def today_question_select number
118     today_now = Time.now  
119     today = Date.new(today_now.year,today_now.month,today_now.day)
120     today_questions  = Stage.find(:all, :conditions => ["date = ?",  today ] ) 
121     @today_question = today_questions[number]
122     if @today_question.blank?
123       today_questions  = Stage.find(:all, :order => "date DESC"  )
124       @today_question = today_questions[number]
125       if @today_question.blank?
126         render :facebook_error
127       end
128     end 
129   end
131   def question1
132     today_question_select 0
133     user_has_published_once = false
134     user_has_published_once = question_processor
135     if user_has_published_once == true
136       @next_step = "question2"
137       render :action => "greetings"  
138     end
139   end
141   def question2
142     today_question_select 1
143     user_has_published_once = false
144     user_has_published_once = question_processor
145     if user_has_published_once == true
146       @next_step = "question3"
147       render :action => "greetings"  
148     end
149   end
151   def question3
153     today_question_select 2
154     user_has_published_once = false
155     user_has_published_once = question_processor
156     if user_has_published_once == true
157       @next_step = "question1"
158       render :action => "greetings" 
159     end
160   end
162   def question_processor
163     time_counter ("before of question_processor time was tooken")
165     user_has_published_once = false
166     users_array = []
167     session_new = Facebooker::Session.create
168     for i in 0...6
169       if params["friend_sel0#{i}"] != nil && params["friend_sel0#{i}"] != ""    
170         @userFB2 =Facebooker::User.new(params["friend_sel0#{i}"], session_new)
171         time_counter ("Creating one user")
172         users_array << @userFB2 
173         user_has_published_once = true
174       #end of if
175       end
176     #end of for
177     end 
178     
179     if user_has_published_once == true
181       begin
182         timeout 7 do
183           session_new.batch do 
184             users_array.each do |player| 
185               player.first_name
186             end 
187           end 
188         end
189       rescue TimeoutError 
190         Rails.logger.warn " >" * 15
191         Rails.logger.warn "     TIMEOUT FOR GETTING NAMES "
192         Rails.logger.warn " >" * 15
193         render :action => :facebook_error
194     
195       end
197       time_counter ("Batching first names")
198   
199       users_array.each do |player|
200         p player.first_name 
201       end
202       time_counter ("Showing result")
203       feeds_to_publish = [] 
205       @userFB = Facebooker::User.new(session[:facebook_session].user.uid, session_new)
206       time_counter ("Creating self user")
207       @user_local = User.find(:first, :conditions => ["uid = ?", session[:facebook_session].user.uid])
208       #@userFB.sex = session[:facebook_session].user.sex
209       time_counter ("Setting sex")
210       user_names = []
211       #for third time
212       self_publishing = ""
213       scenario_themself = ""
214       #preparing all names into array
215       
216       for i in 0..(users_array.size - 1)
217         user_names << users_array[i].first_name
218       end 
219    
220       time_counter ("Getting first_name")
221       #creating messages for list of friends
222       for i in 0..(users_array.size - 1)  
223         themessage = ""
224         user_names_new = user_names - [users_array[i].first_name]
225         if user_names_new.size == 0
226           themessage = ""
227         elsif user_names_new.size == 1
228           themessage = "#{user_names_new[0]}"
229         elsif user_names_new.size == 2
230           themessage = "#{user_names_new[0]} and #{user_names_new[1]}"
231         elsif user_names_new.size == 3
232           themessage = "#{user_names_new[0]}, #{user_names_new[1]} and #{user_names_new[2]}"
233         elsif user_names_new.size == 4
234           themessage = "#{user_names_new[0]}, #{user_names_new[1]},#{user_names_new[2]} and #{user_names_new[3]}"
235         end
236         #preparing for the third stage
237         if themessage != ""
238           self_publishing = users_array[i].first_name + ( users_array.size > 2 ? ", ":" and ") + themessage
239         else
240           self_publishing = users_array[i].first_name + ""
241         end
242         if themessage != ""
243           themessage += ""
244         end
245         session[:self_publishing] = self_publishing
246         #publishing
247          
248         scenario_friend = processing_phraze(@today_question.feed_useraction, users_array[i].first_name, themessage,users_array[i].sex,user_names.size())
249         scenario_themself = processing_phraze(@today_question.feed_selfaction, @user_local.first_name, self_publishing,@user_local.gender,user_names.size())
251         debug_message scenario_friend
252         new_params = Hash.new(0) 
253         new_params = { 
254                 :user_from   => @userFB,
255                 :user_to   => users_array[i],
256                 :main_message => scenario_friend
257                 }
258         feeds_to_publish.push new_params
259         time_counter ("Was added to hash")
260         
261       #end of for i in 0..users_array.size
262       end
263       
264       @user_local.friends_published += (user_names.size + 1)
265       @user_local.save
267       add_stat(0, PUBLISHED, user_names.size + 1)
268       
269       new_params = Hash.new(0) 
270       new_params = { 
271                   :user_from   => @userFB,
272                   :user_to   => @userFB,
273                   :main_message => scenario_themself,   
274                   }
275       feeds_to_publish.push new_params
276       threads = []  
277       threads << Thread.new do  
278         
279         
280         begin
281           timeout 10 do 
282             session_new.batch do 
283               feeds_to_publish.each {|one|
284                 publishing(one[:user_from],one[:user_to],one[:main_message],Feed_action,FB_app_link + "/?f=#{FROM_FEEDS}",processing_phraze(@today_question.feedtext1, @user_local.first_name, self_publishing,@user_local.gender,user_names.size ) ,FB_app_link + "/?f=#{FROM_FEEDS}",processing_phraze(@today_question.feedtext2, @user_local.first_name, self_publishing,@user_local.gender,user_names.size ),'image',Current_site + @today_question.feedpic.url(:normal),FB_app_link + "/?f=#{FROM_FEEDS}")
285               }
286               #session batch
287             end
288             time_counter ("Session batch")
289           end
290         rescue TimeoutError 
291           Rails.logger.warn " >" * 15
292           Rails.logger.warn "     TIMEOUT FOR PUBLISHING "
293           Rails.logger.warn " >" * 15
294         end
295       
296         
297       #thread end 
298       end
299       debug_message scenario_themself  
300     # if user_has_published_once == true
301     end
302     return user_has_published_once
303   end
305   def greetings
306     debug_message "Now session[:self_publishing] = '#{session[:self_publishing]}'"
307     if params[:fanbutton] != nil
308       redirect_to "http://www.facebook.com/pages/Chatting-and-Emailing-with-Nokia/10150115816675015"
309     end
311     if params[:mybutton] != nil
312       p "params[:next_step] = #{params[:next_step]}"
313       @question_number = params[:next_step]
314       case @question_number 
315         when "question1"
316           today_question_select 0
317         when "question2"
318           today_question_select 1
319         when "question3"
320           today_question_select 2
321       end
323       render :action => @question_number  
324     end 
325   end
327   def product
328   end
330   def fanpage
331   end
332   
333   def facebook_error
334   end
335   
336   def publishing(user_from,user_to,main_message,action_link_text,action_link_href,attachment_name,attachment_href,attachment_caption,media_type,media_src,media_href)
337     user_from.publish_to(user_to,
338         :message => main_message,
339         :action_links => [
340                 {
341                 :text => action_link_text,
342                 :href => action_link_href}
343                 ],
344         :attachment => {
345                 :name => attachment_name,
346                 :href => attachment_href,
347                 :caption => attachment_caption,
349                 :media => [
350                         {
351                           :type => media_type,
352                           :src =>  media_src,
353                           :href => media_href
354                         }
356                        ]})
357   end
358   
359   def time_counter (object)
360     the_time = Time.now - @time_counter
361     @time_counter = Time.now
362     p "#{object}: #{the_time.to_s}"
363   end