11import  asyncio 
2+ import  logging 
23
34from  queue  import  SimpleQueue 
45from  typing  import  Union 
56from  pubnub .endpoints .pubsub .subscribe  import  Subscribe 
7+ from  pubnub .models .consumer .pubsub  import  PNMessageResult 
8+ from  pubnub .models .server .subscribe  import  SubscribeMessage 
69from  pubnub .pubnub  import  PubNub 
710from  pubnub .event_engine .models  import  effects , events 
811from  pubnub .models .consumer .common  import  PNStatus 
9- from  pubnub .workers  import  SubscribeMessageWorker 
1012
1113
1214class  ManagedEffect :
1315    pubnub : PubNub  =  None 
1416    event_engine  =  None 
1517    effect : Union [effects .PNManageableEffect , effects .PNCancelEffect ]
18+     stop_event  =  None 
1619
1720    def  set_pn (self , pubnub : PubNub ):
1821        self .pubnub  =  pubnub 
@@ -30,28 +33,36 @@ def run_async(self):
3033        pass 
3134
3235    def  stop (self ):
33-         pass 
36+         logging .debug (f'stop called on { self .__class__ .__name__ }  )
37+         if  self .stop_event :
38+             logging .debug (f'stop_event({ id (self .stop_event )} { self .__class__ .__name__ }  )
39+             self .stop_event .set ()
40+ 
41+     def  get_new_stop_event (self ):
42+         event  =  asyncio .Event ()
43+         logging .debug (f'creating new stop_event({ id (event )} { self .__class__ .__name__ }  )
44+         return  event 
3445
3546
3647class  ManageHandshakeEffect (ManagedEffect ):
3748    def  run (self ):
3849        channels  =  self .effect .channels 
3950        groups  =  self .effect .groups 
4051        if  hasattr (self .pubnub , 'event_loop' ):
52+             self .stop_event  =  self .get_new_stop_event ()
53+ 
4154            loop : asyncio .AbstractEventLoop  =  self .pubnub .event_loop 
4255            if  loop .is_running ():
43-                 loop .create_task (self .handshake_async (channels , groups ))
56+                 loop .create_task (self .handshake_async (channels , groups ,  self . stop_event ))
4457            else :
45-                 loop .run_until_complete (self .handshake_async (channels , groups ))
58+                 loop .run_until_complete (self .handshake_async (channels , groups ,  self . stop_event ))
4659        else :
4760            # TODO:  the synchronous way 
4861            pass 
4962
50-     def  stop (self ):
51-         pass 
52- 
53-     async  def  handshake_async (self , channels , groups ):
54-         handshake  =  await  Subscribe (self .pubnub ).channels (channels ).channel_groups (groups ).future ()
63+     async  def  handshake_async (self , channels , groups , stop_event ):
64+         request  =  Subscribe (self .pubnub ).channels (channels ).channel_groups (groups ).cancellation_event (stop_event )
65+         handshake  =  await  request .future ()
5566        if  not  handshake .status .error :
5667            cursor  =  handshake .result ['t' ]
5768            timetoken  =  cursor ['t' ]
@@ -70,31 +81,39 @@ def run(self):
7081        region  =  self .effect .region 
7182
7283        if  hasattr (self .pubnub , 'event_loop' ):
84+             self .stop_event  =  self .get_new_stop_event ()
7385            loop : asyncio .AbstractEventLoop  =  self .pubnub .event_loop 
74-             coro  =  self .receive_messages_async (channels , groups , timetoken , region )
7586            if  loop .is_running ():
76-                 loop .create_task (coro )
87+                 loop .create_task (self . receive_messages_async ( channels ,  groups ,  timetoken ,  region ) )
7788            else :
78-                 loop .run_until_complete (coro )
89+                 loop .run_until_complete (self . receive_messages_async ( channels ,  groups ,  timetoken ,  region ) )
7990        else :
8091            # TODO:  the synchronous way 
8192            pass 
8293
83-     def  stop (self ):
84-         pass 
85- 
8694    async  def  receive_messages_async (self , channels , groups , timetoken , region ):
87-         response  =  await  Subscribe (self .pubnub ).channels (channels ).channel_groups (groups ).timetoken (timetoken ) \
88-             .region (region ).future ()
89- 
90-         if  not  response .status .error :
91-             cursor  =  response .result ['t' ]
92-             timetoken  =  cursor ['t' ]
93-             region  =  cursor ['r' ]
94-             messages  =  response .result ['m' ]
95-             print (response .result )
96-             recieve_success  =  events .ReceiveSuccessEvent (timetoken , region = region , messages = messages )
97-             self .event_engine .trigger (recieve_success )
95+         subscribe  =  Subscribe (self .pubnub )
96+         if  channels :
97+             subscribe .channels (channels )
98+         if  groups :
99+             subscribe .channel_groups (groups )
100+         if  timetoken :
101+             subscribe .timetoken (timetoken )
102+         if  region :
103+             subscribe .region (region )
104+ 
105+         subscribe .cancellation_event (self .stop_event )
106+         response  =  await  subscribe .future ()
107+ 
108+         if  response  and  response .result :
109+             if  not  response .status .error :
110+                 cursor  =  response .result ['t' ]
111+                 timetoken  =  cursor ['t' ]
112+                 region  =  cursor ['r' ]
113+                 messages  =  response .result ['m' ]
114+                 recieve_success  =  events .ReceiveSuccessEvent (timetoken , region = region , messages = messages )
115+                 self .event_engine .trigger (recieve_success )
116+         self .stop_event .set ()
98117
99118
100119class  ManagedEffectFactory :
@@ -120,7 +139,6 @@ class EmitEffect:
120139    def  set_pn (self , pubnub : PubNub ):
121140        self .pubnub  =  pubnub 
122141        self .queue  =  SimpleQueue 
123-         self .message_worker  =  SubscribeMessageWorker (self .pubnub , None , None , None )
124142
125143    def  emit (self , effect : effects .PNEmittableEffect ):
126144        if  isinstance (effect , effects .EmitMessagesEffect ):
@@ -129,7 +147,17 @@ def emit(self, effect: effects.PNEmittableEffect):
129147            self .emit_status (effect )
130148
131149    def  emit_message (self , effect : effects .EmitMessagesEffect ):
132-         self .pubnub ._subscription_manager ._listener_manager .announce_message ('foo' )
150+         for  message  in  effect .messages :
151+             subscribe_message  =  SubscribeMessage ().from_json (message )
152+             pn_message_result  =  PNMessageResult (
153+                 message = subscribe_message .payload ,
154+                 subscription = subscribe_message .subscription_match ,
155+                 channel = subscribe_message .channel ,
156+                 timetoken = int (message ['p' ]['t' ]),
157+                 user_metadata = subscribe_message .publish_metadata ,
158+                 publisher = subscribe_message .issuing_client_id 
159+             )
160+             self .pubnub ._subscription_manager ._listener_manager .announce_message (pn_message_result )
133161
134162    def  emit_status (self , effect : effects .EmitStatusEffect ):
135163        pn_status  =  PNStatus ()
0 commit comments