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