some
[appoyo.git] / app / controllers / users_controller.rb~
blob2a10a39f382242c6a825c604673725c64e376605
1 require 'net/http'
2 require 'uri'
3 require 'json'
4 require 'csv'
6 class UsersController < ApplicationController
7   # before_filter :set_current_user
8   
9   
10   except_funcs = [:home, :processcallback, :fakejawaker, :facebookapp, :stat, :auth, :api, :statistic_to_csv,:sign_out]
11   #before_filter :check_auth, :only => [:stat]
12   before_filter :source_statistic,  :except => except_funcs
13   before_filter :create_facebook_session,  :except => except_funcs
14   before_filter :set_facebook_session,  :except => except_funcs
15   before_filter :checking_jawaker_session,  :except => except_funcs
16   before_filter :facebook_logout,           :except => except_funcs
17   before_filter :check_facebook_session,    :except => except_funcs
20   def check_auth
21      if (cookies[:auth] != "ok")
22        debug_message ("Admin not log in",false)
23        redirect_to "http://jawaker.com/fb/auth"  
24     end
25     debug_message ("Admin log in, OK")
26   end
27   
28   #authification
29   def auth
30     debug_message ("Authification:")
31     if (params[:login])
32       if (params[:login] == FBlogin) and (params[:password] == FBpassword)
33         cookies[:auth] = "ok" 
34         flash[:notice] = 'Successfully logged in'                  
35         respond_to do |format|
36           format.html { redirect_to("http://jawaker.com/fb/stat") }
37         end        
38       else
39         flash[:notice] = 'Incorrect login and/or password'
40       end
41     end    
42   #def auth 
43   end
45   def sign_out
46     cookies[:auth] = "false" 
47     respond_to do |format|
48       format.html { render :action => "auth" }
49     end
50   end
52   #protect_from_forgery :except => processcallback
53   def source_statistic
54     #add statistic by source
55     if (params[:from]) && (params[:from].to_i != 0)
56       add_stat(0, VISITED, params[:from] ? params[:from].to_i : 0)
57     end
58     
59     if !params[:facebook_id].blank? && params[:api_action].blank?
60        redirect_to "http://www.jawaker.com/users/new?facebook_id=" + params[:facebook_id]
61     end         
62   end
63   
64   def check_facebook_session
65     if session[:facebook_session].blank?
66       if params[:locale].blank?
67         redirect_to Current_site
68       else
69         redirect_to Current_site + "?locale=" + params[:locale].to_s
70       end
71     end
72   end
73   def facebook_logout
74     begin
75       @facebook_locale = session[:facebook_session].user.locale
76     rescue
77       @facebook_locale = nil
78     end
79     #getting and setting language info
80     if params[:locale] && params[:locale] != ""
81       I18n.locale = params[:locale]
82     end
83     unless params[:logout].blank?
84       session[:facebook_session] = nil
85       facebook_session = nil
86       cookies[:_connect_tutorial_session] = nil
87       if params[:locale].blank?
88         redirect_to Current_site
89         return
90       else
91         redirect_to Current_site + "?locale=" + params[:locale].to_s
92         return
93       end
95     end
96   end
97   
98   def api
99     #public feed after invited user
100     if params[:api_action] == "publish_about_invited"
101       @operation_result = "SUCCESS"
102       #preparing to publish
103       add_stat(params[:facebook_id], REWARDED)
104       session_new = Facebooker::Session.create
105       @userFB = Facebooker::User.new(params[:facebook_id], session_new)   
106       begin
107         @userFB.publish_to(@userFB,
108                           :message => "has recieved "  + params[:tokens] + " tokens for inviting his friend with nickname " + params[:nickname] + " in Jawaker",
109                           :action_links => [{
110                                   :text => 'See my results',
111                                   :href => "http://apps.facebook.com/jawaker"},
112                                   {
113                                   :text => 'Try to beat him',
114                                   :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}"}
115                                   ],
116                           :attachment => {
117                                   :name => "The rank of this user is increasing",
118                                   :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}",
119                                   :caption => 'Jawaker is a multiplayer card game website for the Arab world. Register now and start playing one of our online card games for FREE!',
120                                   :description => 'Start your first game right now',
121                                   :media => [
122                                           {
123                                           :type => 'image',
124                                           :src => "http://jawaker.com/images/hp_mascot_ar-trans.png",
125                                           :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}"}
127                                          ]})
129        rescue Facebooker::Session::SpecialUserAuthorizationRequired
130          @operation_result = "SPECIAL_USER_AUTHORIZATION_REQUIRED"
132        rescue
133         @operation_result = "UNKNOWN_ERROR"
134        end
136        render :layout => false
137      end
138     
139   end
140   
141   def checking_jawaker_session
142     unless RAILS_ENV == "development"          
143       @temp_cookies = false  
144             #if jsession_id was sent  - set cookies
145       if !params[:jsession_id].blank?
146         cookies[:_session_id] = params[:jsession_id]
147         @temp_cookies = true
148         cookies[:www_redirect] = true
149       end
150       #redirect with  cookies 
151       if request.env["HTTP_HOST"].include?("www")
152         redirect_to "http://jawaker.com/fb/?jsession_id=" + cookies[:_session_id].to_s
153         return
154       end    
155       @answer_result = false
156       debug_message("Session id cookie: #{cookies[:_session_id]}, temp_cookies: #{@temp_cookies}")
157       if (cookies[:_session_id] && !(cookies[:_session_id].blank?)) # @temp_cookies
158         begin
159           #checking if user still online in Jawaker
160           res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V','token' => 'R45ASL5V','api_action'=>'check_session','session_id' =>  cookies[:_session_id]})
161           @answer_result = res.body
162           debug_message("Information about state of Jawaker logging was got: " + @answer_result.to_s)
163           if (!@answer_result.include?("true")) && (!@answer_result.include?("false"))
164             debug_message("Jawaker API does not work properly",false)
165           end
166           
167           if @answer_result
168             if @answer_result.include?("false")
169               @answer_result = false
170             else
171               @answer_result = true
172             end          
173           end         
174         rescue
175           debug_message("Cannot connect Jawaker",false)
176         end
177       end
178           
179       if (@temp_cookies == false) && ((cookies[:_session_id].blank?) || (@answer_result == false))     
180         if cookies[:_session_id].blank?
181           debug_message("cookies[:_session_id].blank",false)
182         end       
183         if @answer_result == false  
184           debug_message("User not loging in",false)
185         end  
186         
187         redirect_to "http://jawaker.com/login" 
188        
189         
190        
191       end 
192     #end of unless RAILS_ENV == "development"
193     end 
194   end
195   # step 1 
196   def home
197     unless session[:facebook_session].blank?
198       #user permisssion         
199       begin
200         if session[:facebook_session].user.has_permission?('publish_stream')
201           @myway = "invitefriend"
202         else
203           @myway = "permission"
204         end
205         debug_message("User already loggined so he redirected to permission/invitation page")
206         if params[:locale].blank?
207           redirect_to Current_site + @myway
208         else
209           redirect_to Current_site + @myway + "?locale=" + params[:locale].to_s
210         end
211       
212       rescue 
213         debug_message("Cannot get status of user permission... I continue this home page",false)
214       end
215     #end of unless session[:facebook_session].blank?   
216     end
217   end
218    
219   #  step 2
220   def permission
221     #  Step 2 if loggined 
222     debugger
223     begin
224       if session[:facebook_session].user.has_permission?('publish_stream')
225         if params[:locale].blank?
226           params[:locale] = nil
227         end       
228         debug_message("User already has permission so he redirected to invitation page")
229         redirect_to Current_site + "invitefriend" + "?locale=" + params[:locale].to_s
230         return
231       end             
232     rescue 
233         debug_message("Cannot get status of user permission... Redirect to home page and logout",false)
234         redirect_to Current_site + "?logout=yes" + "?locale=" + params[:locale].to_s
235         return
236     end
237       
238     @someUser =  session[:facebook_session].user
239     #saving localy
240     @fbfriend = Fbfriend.find(:first, :conditions => ["facebook_id = '?'", @someUser.uid])
241     if @fbfriend.blank?
242       #preparing list of friends for Jawaker
243       my_friends = []
244       #rescue stage for no frieds
245       begin
246         for friend in @someUser.friends
247           my_friends.push(friend.uid)
248         end
249         #sending registration info to Jawaker
250         begin
251           res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V','token' => 'R45ASL5V','api_action'=>'registration', 'facebook_id'=>@someUser.uid, 'friend_list' => my_friends.join(','),'session_id' => cookies[:_session_id]  })
252           debug_message("FB.id and List of friends after registration for user  were sent")
253         rescue
254           debug_message("Problem with Jawaker connection",false)
255           raise Connection_problem_with_jawaker
256         end
257         myParams = {
258                       :facebook_id     => @someUser.uid,
259                       :friends_list    => my_friends.join(',')
260                     }
261         @fbfriend = Fbfriend.new(myParams)
262         @fbfriend.save
263         
264         add_stat(@someUser.uid,CONNECTED)
265         debug_message("Information was added in MW local DB")
266       rescue
267         debug_message("Cannot get friend list, user was logout and redirect",false)
268         redirect_to "http://jawaker.com/fb?logout=yes"
269       end
270     end
271       #p "FAKE sending private info of user: [:political, :pic_small, :name, :quotes,  :tv, :meeting_sex, :hs_info, :timezone, :relationship_status, :hometown_location, :about_me, :music, :work_history, :sex, :religion, :activities,  :movies,  :education_history, :birthday, :first_name, :meeting_for, :last_name, :interests, :current_location, :pic, :books, :affiliations, :locale]"
272     
274   end
276   # step 3
277   def invitefriend
278     #permission adding to Jawaker
279     if params[:permission] == "publish_stream"
280       add_stat(session[:facebook_session].user.uid,PERMISSION)
281       begin
282         res = Net::HTTP.post_form(URI.parse(Jawaker_link), {'token' => 'R45ASL5V','api_action' => 'permission_set', 'permission' => 'publish_stream', 'facebook_id' => session[:facebook_session].user.uid})
283         debug_message("Updating about permision was sent")
284       rescue 
285         debug_message("Cannot connect to Jawaker or some problems with getting info from FB",false)
286       end
287     end
289     #public "registration" message on feed
290     if (params[:permission] == "publish_stream")
291       begin
292         #preparing for public first feed
293         session_new = Facebooker::Session.create
294         @userFB = Facebooker::User.new(session[:facebook_session].user.uid, session_new)
295         #publishing first message
296         @userFB.publish_to(@userFB,
297                         :message => "has connected his Facebook and Jawaker accounts",
298                         :action_links => [
299                                 {
300                                 :text => 'Visit Jawaker  Ø¥Ø°Ù‡Ø¨ Ø¥Ù„Ù‰ Ø¬ÙˆØ§ÙƒØ±',
301                                 :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}"}
302                                 ],
303                         :attachment => {
304                                 :name => "لنلعب Ø§Ù„ورق Ø¹Ù„Ù‰ Ø¬ÙˆØ§ÙƒØ±. Ø¥Ø°Ù‡Ø¨ Ø¥Ù„Ù‰ Ø¬ÙˆØ§ÙƒØ± ÙˆØ§Ù„عب Ø§Ù„آن",
305                                 :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}",
306                                 :caption => "Let's play cards together on Jawaker. Visit Jawaker now and start playing.",
308                                 :media => [
309                                         {
310                                           :type => 'image',
311                                           :src => "http://jawaker.com/fb/logo_of_jawaker.png",
312                                           :href => "http://jawaker.com/fb/?from=#{FROM_FEED}"
313                                         }
315                                        ]})
316         debug_message("First message was published into stream")
317       rescue
318         debug_message("Cannot publish to Jawaker or some problems with getting info from FB",false)
319       end
320     #logged_in?  & permission
321     end
323     #getting friend list who is already registered
324     my_friends = []
325     @answer_result = nil
326     begin
327       for friend in session[:facebook_session].user.friends
328          my_friends.push(friend.uid)
329       end
330       #sending list of friends and getting list who are already connected to exclude invitation
331       res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V', 'api_action'=>'connected_friends','facebook_id' =>  session[:facebook_session].user.uid,'friend_list' => my_friends.join(',') })
332       @answer_result = res.body.split(',')
333       debug_message("Information about already registered friends was gotten")
334       if @answer_result 
335         debug_message ("List of friends :" + @answer_result.join(' '))
336       end
337     rescue
338       debug_message("Cannot get facebook friend list from FB or cannot connect Jawaker",false)
339     end 
340   # invitefriend
341   end
343   #public feed after request from Jawaker
344   def publish_game_result
345     @operation_result = "SUCCESS"
346     #preparing to publish
347     session_new = Facebooker::Session.create
348     @userFB = Facebooker::User.new(params[:facebook_id], session_new)
349     begin
351       @userFB.publish_to(@userFB,
352                         :message => "has won a big elephant",
353                         :action_links => [{
354                                 :text => 'See my results',
355                                 :href => "http://apps.facebook.com/testjawaker"},
356                                 {
357                                 :text => 'Try to beat him',
358                                 :href => "http://jawaker.com"}
359                                 ],
360                         :attachment => {
361                                 :name => "Now I've won " + params[:tokens] + " tokens and I'm " + params[:rank] + "th between my friends!",
362                                 :href => 'http://jawaker.com',
363                                 :caption => 'Jawaker is a multiplayer card game website for the Arab world. Register now and start playing one of our online card games for FREE!',
364                                 :description => 'Start your first game right now',
365                                 :media => [
366                                         {
367                                         :type => 'image',
368                                         :src => "http://jawaker.com/images/hp_mascot_ar-trans.png",
369                                         :href => "http://jawaker.com"}
371                                        ]})
373     rescue Facebooker::Session::SpecialUserAuthorizationRequired
374       @operation_result = "SPECIAL_USER_AUTHORIZATION_REQUIRED"
375     rescue
376       @operation_result = "UNKNOWN_ERROR"
377     end
378     render :layout => false
379   end
381   
383   #processing local callback
384   def localcallback     
385     #updating information about invited friends
386     unless params[:ids].blank?
387           
388       add_stat(0,INVITED_NUMBER,params[:ids].size)    
389       begin
390         res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V', 'api_action'=>'invited_friends','facebook_id'=>session[:facebook_session].user.uid, 'number_of_friends' =>params[:ids].size})
391         debug_message("Localcallback: information about nuber invited friends was sent to Jawaker")
392       rescue 
393         debug_message("Localcallback: Some FB(get user.uid) or connection problem",false)
394       end
395     end
397     if cookies[:www_redirect] == "true"
398       cookies[:www_redirect] = nil
399       redirect_to "http://www.jawaker.com/games"
400       return
401     else
402       redirect_to "http://jawaker.com/games"
403       return
404     end
405   end
406   
407   #statistic
408   def stat 
409       #Totally like Radio App statistic
410       #Date statistics
411       current_date = Date.new(2010,01,23)
412       today_now = Time.now 
413       today = Date.new(today_now.year,today_now.month,today_now.day)
414       @date_range = (current_date..today).to_a
415       @data_pack = []
416       @total    = Hash.new(0)
417       @date_range.each {|date|
418         @query_params = Hash.new(0)
419         @query_params[:created_at] = date
420         @query_string = "DATE(created_at) = :created_at" 
421         @statistic  = Stat.find(:all, :conditions => [@query_string ,@query_params])
422         one_pack = Hash.new(0)
423         
424         @statistic.each {|stat|      
425           case stat[:action]           
426             when INVITED_NUMBER
427               one_pack[INVITED_NUMBER]+= stat[:extra]
428               @total [INVITED_NUMBER]+=stat[:extra]
429             when CONNECTED,PERMISSION, DELETED,REWARDED
430               one_pack[ stat[:action]]+= 1
431               @total[ stat[:action]]+= 1
432             when VISITED
433               case stat[:extra]      
434                 when FROM_INVITATION, FROM_FEED
435                    one_pack[stat[:extra]]+= 1
436                    @total[stat[:extra]]+= 1
437                end
438           end
439       
440         }
441         @data_pack.push one_pack
442           
443    }
444     @data_pack.reverse!
445     #end of new statistics  
446   end
448    def statistic_to_csv
449     stat
450     @data_pack.reverse!
451     @titles  = "Date,Connected,Status Permissions,Unistalled,Rewarded,Invitations Sent,Source by Invitation,Source by Feed".split(",")
452     report = StringIO.new
453     CSV::Writer.generate(report, ',') do |title|
454       title << @titles    
455       @data_pack.each_with_index {|data, i|       
456         title <<  [@date_range[i],data[CONNECTED],data[PERMISSION],data[DELETED],data[REWARDED],data[INVITED_NUMBER],data[FROM_INVITATION],data[FROM_FEED]]
457       }
458       title <<  ["Total",@total[CONNECTED],@total[PERMISSION],@total[DELETED],@total[REWARDED],@total[INVITED_NUMBER],@total[FROM_INVITATION],@total[FROM_FEED]]
459     end   
460     report.rewind
461     time_now = Time.now.to_formatted_s(:number)
462     file = File.open("#{RAILS_ROOT}/public/#{time_now}.csv", "wb")
463     file.write(report.read)
464     file.close  
465     redirect_to "/fb/#{time_now}.csv"
466   end
467   #processing callback from facebook
468   def processcallback
469     #unistaliing
470     if params[:fb_sig_uninstall] == "1"
471       begin
472         res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V','api_action'=>'deleted','facebook_id'=>params[:fb_sig_user]})
473         debug_message("Information about deleted user  was sent")
474       rescue
475         debug_message("Cannot connect Jawaker",false)
476       end
477       @fbfriend = Fbfriend.find(:first, :conditions => ["facebook_id = ?", params[:fb_sig_user]])
478       if @fbfriend != nil
479         @fbfriend.destroy
480         debug_message("User " + params[:fb_sig_user].to_s + " was destroyed from local MW DB")
481         add_stat(params[:fb_sig_user], DELETED)
482       end
483     end
484     #if kind of callback (deleted, given permission)- give know to Jawaker
485   end
486   
487   #publication in FB
488   def facebookapp
489     @answer_result = nil
490     #if user is loggined in facebook and in our list
491     
492     if (session[:facebook_session])
493       User.sessionkey      =  session[:facebook_session].session_key
494       User.sessionkey_time =  DateTime.now
495       debug_message("Session key was taken") 
496     end
497     
498     if false #(session[:facebook_session])
499       #if (session[:facebook_session].user.has_added_app)
500       begin
501         #getting friend list who is already registered
502         my_friends = []
503         my_friends.push(session[:facebook_session].user.uid)
504         for friend in session[:facebook_session].user.friends
505           my_friends.push(friend.uid)
506         end
507         #sending list of friends and getting list who are already connected to exclude invitation
508         res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V','api_action'=>'get_jawaker_rank', 'friend_list' => my_friends.join(',') })
509         @answer_result = JSON.parse(res.body)
510       rescue
511         "facebookapp B O O M!"
512       end
513     end
514     render :layout => false
515   end
517   def fakejawaker
518     #layout 'simple'
519     p " > > > G E T   R E S U L T S"
520     p params
521     @json_data = Hash.new(0)
523     case params[:api_action]
525       when "registration"
526       p " > > > USER REGISTERED"
529      when "deleted"
530       p " > > > USER DELETED"
532       when "permission_set"
534       p " > > > PERMISSION SET"
536       when "friend_list_update"
537        p " > > >  FREIND LIST UPDATE"
539        when "connected_friends"
540        
541        
542       when "check_session"
543         @just_data = "true"
544        #@json_data[:friend_list] = [43422890,33334444]
545        #p " > > > GIVING REGISTERED USER FRIENDS"
547         #@json_data0 = []
548       when "get_jawaker_ranks"
549         p " > > > GET JAWAKER RANKS"
551        @json_data0 = [521325397,749095503,687665098,514733981,1382916266,516054981]
552        @json_data1 = ["batman","soccerman","killer_of_devil","just_me","Kolobok","Knight"]
553        @json_data2 =  [ 122,455,566,3335,33334,55555]
555        friends_list = []
557         for i in 0..@json_data0.size-1
558           @data_pack = {:nickname =>  @json_data1[i], :facebook_id =>  @json_data0[i], :tokens =>  @json_data2[i]}
559            friends_list.push(@data_pack)
560         end
563        @json_data[:friends_list] = friends_list
564     #end of case params[:mw_action]
565     end
567     render :layout => false
568   end
569   
570   #changing status
571   def status_change 
572     #creating querry
573     debug_message("Session_time: #{User.sessionkey_time}, key: #{User.sessionkey} ")
574     
575     @fbusers = Fbfriend.find(:all) 
576     #calculating of number hours since last session
577     time_since_last_session = (User.sessionkey_time != nil ) ? Date.day_fraction_to_time(DateTime.now - User.sessionkey_time ) : [1] 
578     notice_message = ""
579     #if user exists and time more than one hour (first position in array)
580     if (@fbusers == []) || (time_since_last_session[0] > 0)
581       if @fbusers == []
582         flash[:notice] = "No one was choosen"
583       else
584         flash[:notice] = Message_reload_app_page
585       end
586     else
587       session = Facebooker::Session.create
588       session.session_key = User.sessionkey
589       threads = []  
590       threads << Thread.new do   
591         #update each user from querry
592         @fbusers.each do |fbuser|   
593           @userFB = Facebooker::User.new(fbuser.facebook_id , session)
594           begin 
595             @userFB.set_status(params[:new_status])         
596             #fbuser.update_attributes(:status => params[:new_status])
597             debug_message("User's #{fbuser.facebook_id} status now is '#{params[:new_status]}'")
598           rescue Facebooker::Session::ExtendedPermissionRequired
599             debug_message("User #{fbuser.facebook_id } does not have permission")
600             #fbuser.update_attributes(:deleted => Deleted)
601             #add_stat(fbuser.uid, DELETED)
602           rescue
603             debug_message("Unknown mistake trying to change status #{fbuser.uid}",false)
604           end        
605         end
606        #end threads << Thread.new do
607       end
608       flash[:notice] = 'Statuses for this groupping are being changed. It will take about '+ (@fbusers.size*2).to_s+' seconds. All users without status permission will be  deleted'
609     end
610     
611     respond_to do |format|
612       format.html { redirect_to("/stat") }
613       format.xml  { head :ok }
614     end 
615   #end def status_change
616   end
617   #sending of notification
618   def notification_send  
620     @fbusers = Fbfriend.find(:all) 
621     #if they exists
622     if @fbusers != []
623       #preparing list of users to send them
624       ids = []
625       @fbusers.each do |fbuser|
626          ids.push(fbuser.facebook_id )
627       end
628       batch_size = 20     
629       #sending
630       @total_sent = 0
631       begin
632         new_session = Facebooker::Session.create
633         ids.each_slice(Max_notification_per_time) do |current_batch| 
634           new_session.batch do 
635             current_batch.each_slice(batch_size ) do |small_batch| 
636               new_session.send_notification(small_batch, params[:notification],"app_to_user")
637             end 
638             #@total_sent += result 
639           end 
640         end
641         debug_message("#{ids.size} notifications were sent")
642         flash[:notice] = 'Notification to this groupping was successfully sended'
643       rescue
644         flash[:notice] = ' Error with sending occured'
645       end    
646     else
647       flash[:notice] = 'No one exists to send them notification'
648     end   
649     #debugger  
650     new_params = Hash.new(0) 
651     new_params = { 
652                   :age      => params[:age],
653                   :gender   => params[:gender],
654                   :relation => params[:relation]               
655                   }
656     #viewing processing
657     respond_to do |format|
658       format.html { redirect_to(users_url) }
659       format.xml  { head :ok }
660     end
661   #end notification_send
662   end