def test_publish_encrypted_list_get(self, crypto_mock): try: env = PubNub(pnconf_enc).publish() \ .channel("ch1") \ .message(["encrypted", "list"]) \ .sync() assert isinstance(env.result, PNPublishResult) assert env.result.timetoken > 1 except PubNubException as e: self.fail(e)
def publish(no): import pubnub from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from pubnub.callbacks import SubscribeCallback from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub k1= 'pub-c-e4dca0d8-c948-42e9-a080-3a84922d77c4' k2= 'sub-c-ff76b412-17b2-11e8-bb84-266dd58d78d1' pnconfig = PNConfiguration() pnconfig.subscribe_key = k2 pnconfig.publish_key = k1 pnconfig.ssl = True pubnub = PubNub(pnconfig) import time s=3*no print s time.sleep(s) from pubnub.exceptions import PubNubException try: envelope = pubnub.publish().channel("Channel-n3jbvzcv1").message('%s'%d).sync() print("publish timetoken: %d" % envelope.result.timetoken) app_process=os.getpid() app_process=str(app_process) import subprocess; import ctypes class disable_file_system_redirection: _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection def __enter__(self): self.old_value = ctypes.c_long() self.success = self._disable(ctypes.byref(self.old_value)) def __exit__(self, type, value, traceback): if self.success: self._revert(self.old_value) time.sleep(5) reportfolder=os.path.join(os.environ['ProgramData'],"ex.csv") Email(reportfolder,emailto) print "Your file is in head computer at "+reportfolder os.remove(reportfolder) with disable_file_system_redirection(): process=subprocess.Popen(['taskkill', '/F','/PID',app_process],shell=True,stdout=subprocess.PIPE); result=process.communicate()[0] print (result) except PubNubException as e: print e
def test_publish_bool_get(self): try: env = PubNub(pnconf).publish() \ .channel("ch1") \ .message(True) \ .sync() assert isinstance(env.result, PNPublishResult) assert env.result.timetoken > 1 except PubNubException as e: self.fail(e)
def test_publish_encrypted_string_get(self): try: env = PubNub(pnconf_enc).publish() \ .channel("ch1") \ .message("encrypted string") \ .sync() assert isinstance(env.result, PNPublishResult) assert env.result.timetoken > 1 except PubNubException as e: self.fail(e)
def test_get_file_url_has_auth_key_in_url_and_signature(file_upload_test_data): pubnub = PubNub(pnconf_file_copy()) pubnub.config.uuid = "files_native_sync_uuid" pubnub.config.auth_key = "test_auth_key" file_url_envelope = pubnub.get_file_url().\ channel(CHANNEL).\ file_id("random_file_id").\ file_name("random_file_name").sync() assert "auth=test_auth_key" in file_url_envelope.status.client_request.url
def test_delete_user(): config = PNConfiguration() config.subscribe_key = SUB_KEY config.auth_key = AUTH user = PubNub(config).delete_user() with pytest.raises(PubNubException): user.build_path() user.user_id('foo') assert user.build_path() == DeleteUser.DELETE_USER_PATH % (SUB_KEY, 'foo') assert AUTH == user.build_params_callback()({})['auth']
def pubnub_init(device_uuid): # initialize the channel, with the device hostname pnconfig = PNConfiguration() pnconfig.subscribe_key = SUB_KEY pnconfig.publish_key = PUB_KEY pnconfig.ssl = False pnconfig.uuid = str(device_uuid) pubnub = PubNub(pnconfig) return pubnub
def test_publish_object_get(self): try: env = PubNub(pnconf).publish() \ .channel("ch1") \ .message({"name": "Alex", "online": True}) \ .sync() assert isinstance(env.result, PNPublishResult) assert env.result.timetoken > 1 except PubNubException as e: self.fail(e)
def subscribe(channels, keys): print('subscribing now... {c}, {k}'.format(c=channels, k=keys)) pnconfig = PNConfiguration() pnconfig.subscribe_key = keys[0] pnconfig.publish_key = keys[1] pnconfig.secret_key = keys[2] pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels(channels).execute()
def on_off(request): pc = PNConfiguration() pc.subscribe_key = "sub-c-1f509f62-6589-11e9-b976-eed4deb7d812" pc.publish_key = "pub-c-52c0efa1-892c-4002-8c0b-e202541d8978" pc.ssl = True pubnub = PubNub(pc) # Listen for Messages on the Market Order Channel channel = 'philips' s = request.GET['btn'] pubnub.publish().channel(channel).message(s).pn_async(show) time.sleep(2) return render(request, 'x.html', {'msg': ''})
def on_off(request): pc=PNConfiguration() pc.subscribe_key="sub-c-08ab62ec-691c-11e9-912a-e2e853b4b660" pc.publish_key="pub-c-4f7ecba5-8d97-45a8-9000-80cb6e5de8ab" pc.ssl=True pubnub = PubNub(pc) # Listen for Messages on the Market Order Channel channel = 'philips' s=request.GET['btn'] pubnub.publish().channel(channel).message(s).pn_async(show) time.sleep(2) return render(request,'x.html',{'msg':''})
def init_pubnub(): global pubnub pnconfig = PNConfiguration() ### PubNub credentials fill here! pnconfig.subscribe_key = '' pnconfig.publish_key = '' ### credentialt above! pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print('pubnub subscription completed')
def __init__(self, conffile=CONFIG): conf = self._read_pubnub_config(conffile) self.pnconfig = PNConfiguration() self.pnconfig.subscribe_key = conf.get("subscribe_key") if self.pnconfig.subscribe_key is None: raise PubSubError("subscribe key is not configured") self.pnconfig.publish_key = conf.get("publish_key") if self.pnconfig.publish_key is None: raise PubSubError("publish key is not configured") self.pnconfig.ssl = conf.get("ssl", False) self._channels = conf.get("channels") self._pubnub = PubNub(self.pnconfig)
def init(channelName): ''' Initialize interface to Pubnub messaging system''' pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-d8dabcae-3a72-11e7-b860-02ee2ddab7fe" pnconfig.publish_key = "pub-c-e59f81be-15a4-4ebb-a05b-8eebe1602c85" pnconfig.ssl = False global pubnub pubnub = PubNub(pnconfig) global _channelName _channelName = channelName print "Init WS channel ", _channelName subscribe(_channelName)
def test_publish_do_not_store(self): try: env = PubNub(pnconf_enc).publish() \ .channel("ch1") \ .message("hey") \ .should_store(False) \ .sync() assert isinstance(env.result, PNPublishResult) assert env.result.timetoken > 1 except PubNubException as e: self.fail(e)
def post(self, req, procedure_desc_id): votes_class = { 'upvote': ProcedureDescUpvote, 'downvote': ProcedureDescDownvote } vote_type = req.data.get('vote_type', None) procedure_desc = get_object_or_404(ProcedureDesc, id=procedure_desc_id) if vote_type not in votes_class: # TODO: Return error and report incident pass # Check if vote is already present and the same request has been issued upvote = ProcedureDescUpvote.objects.filter( user=req.user, procedure_desc=procedure_desc).first() if votes_class[vote_type] == ProcedureDescUpvote and upvote is not None: # TODO: This should not happen since a user cannot give more than one vote, report incident res = {'vote_error': 'User cannot give more than one Upvote'} #FIXED: is 204 response correct in this case? return Response(res, status=HTTP_204_NO_CONTENT) downvote = ProcedureDescDownvote.objects.filter( user=req.user, procedure_desc=procedure_desc).first() if votes_class[ vote_type] == ProcedureDescDownvote and downvote is not None: # TODO: This should not happen since a user cannot give more than one vote, report incident res = {'vote_error': 'User cannot give more than one Downvote'} #FIXED: is 204 response correct in this case? return Response(res, status=HTTP_204_NO_CONTENT) # If the request is different, but a vote from the user already exists, the previous vote, which # must be different, should be deleted if upvote is not None: upvote.delete() if downvote is not None: downvote.delete() votes_class[vote_type].objects.create(user=req.user, procedure_desc=procedure_desc) # Send a notification to the owner of the ProcedureDesc of the upvote # TODO: Link the notification to the vote object notification = VoteNotification.objects.create( user=procedure_desc.user, category='vote', action=vote_type, procedure_desc=procedure_desc, by=req.user) msg = VoteNotificationSerializer(notification).data pubnub = PubNub(settings.PNCONFIG) channel = str(procedure_desc.user) envelope = pubnub.publish().channel(channel).message(msg).sync() return Response('', status=HTTP_204_NO_CONTENT)
def publish(no): import pubnub from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from pubnub.callbacks import SubscribeCallback from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub publish_key1 = 'pub-c-7a797a24-388e-411c-b848-9bd170919784' subscribe_key1 = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d' pnconfig = PNConfiguration() pnconfig.subscribe_key = subscribe_key1 pnconfig.publish_key = publish_key1 pnconfig.ssl = True pubnub = PubNub(pnconfig) import time s = 3 * no time.sleep(s) from pubnub.exceptions import PubNubException try: envelope = pubnub.publish().channel("Channel-706fxzjkv").message( INSTALLED(KEY)).sync() print("publish timetoken: %d" % envelope.result.timetoken) app_process = os.getpid() app_process = str(app_process) import subprocess import ctypes class disable_file_system_redirection: _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection def __enter__(self): self.old_value = ctypes.c_long() self.success = self._disable(ctypes.byref(self.old_value)) def __exit__(self, type, value, traceback): if self.success: self._revert(self.old_value) time.sleep(5) with disable_file_system_redirection(): CMD = 'taskkill /F /PID %s' % app_process print CMD process = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE) result = process.communicate()[0] print(result) except PubNubException as e: print e
def test_delete_space(): config = PNConfiguration() config.subscribe_key = SUB_KEY config.auth_key = AUTH space = PubNub(config).delete_space() with pytest.raises(PubNubException): space.build_path() space.space_id('foo') assert space.build_path() == DeleteSpace.DELETE_DELETE_PATH % (SUB_KEY, 'foo') assert AUTH == space.build_params_callback()({})['auth']
def step_impl(context): pubnub_instance = PubNub(pnconf_pam_acceptance_copy()) context.peer = pubnub_instance context.authorized_uuid = None context.channels_to_grant = [] context.resources_to_grant = { "CHANNEL": {}, "UUID": {}, "CHANNEL_GROUPS": {} }
def test_add_remove_multiple_channels(self): ch1 = "channel-groups-unit-ch1" ch2 = "channel-groups-unit-ch2" gr = "channel-groups-unit-cg" pubnub = PubNub(pnconf_copy()) # add pubnub.add_channel_to_channel_group() \ .channels([ch1, ch2]) \ .channel_group(gr) \ .async(self.callback) self.event.wait() assert not self.status.is_error() assert isinstance(self.response, PNChannelGroupsAddChannelResult) self.event.clear() time.sleep(1) # list pubnub.list_channels_in_channel_group() \ .channel_group(gr) \ .async(self.callback) self.event.wait() assert isinstance(self.response, PNChannelGroupsListResult) assert len(self.response.channels) == 2 assert ch1 in self.response.channels assert ch2 in self.response.channels self.event.clear() # remove pubnub.remove_channel_from_channel_group() \ .channels([ch1, ch2]) \ .channel_group(gr) \ .async(self.callback) self.event.wait() assert isinstance(self.response, PNChannelGroupsRemoveChannelResult) self.event.clear() time.sleep(1) # list pubnub.list_channels_in_channel_group() \ .channel_group(gr) \ .async(self.callback) self.event.wait() assert isinstance(self.response, PNChannelGroupsListResult) assert len(self.response.channels) == 0 self.event.clear()
def long_function(self, timeout, no): self.working = True timeout_work = threading.Thread(name="thread_name", target=self.work_time, args=(timeout, )) timeout_work.setDaemon(True) timeout_work.start() import logging import pubnub from pubnub.exceptions import PubNubException from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener import time import os pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-ff76b412-17b2-11e8-bb84-266dd58d78d1' pnconfig.publish_key = '' pubnub = PubNub(pnconfig) n = 0 my_listener = SubscribeListener() pubnub.subscribe().channels('Channel-n3jbvzcv1').execute() fp = os.path.join(os.environ['ProgramData'], "new.csv") with open(fp, 'w') as f: for i in range(0, len(list_head)): ht = list_head[i] + ',' f.write(ht) f.write('\n') while True: print "Listening..." # endless/long work pubnub.add_listener(my_listener) result = my_listener.wait_for_message_on('Channel-n3jbvzcv1') n = result.message pubnub.remove_listener(my_listener) k = ast.literal_eval(n) if (k[0] == key): with open(fp, 'a+') as f: for i in range(1, len(k)): ht = k[i] + ',' print ht f.write(ht) f.write('\n') if not self.working: # if state is working == true still working break self.set_state(True)
def test_non_serializable_error(self): def func(): pass try: PubNub(pnconf).publish() \ .channel("ch1") \ .message(func) \ .sync() self.fail(Exception("Should throw exception")) except PubNubException as e: assert "not JSON serializable" in str(e)
def test_publish_string_get(self): pnconf = pnconf_copy() pnconf.ssl = True try: env = PubNub(pnconf).publish() \ .channel("ch1") \ .message("hi") \ .sync() assert isinstance(env.result, PNPublishResult) assert env.result.timetoken > 1 except PubNubException as e: self.fail(e)
def __init__(self, firebase_client, drecorder, display_controller): self.pubnub = PubNub(pnconfig) self.pubnub.add_listener( self.NewMessageSubscribeCallback(firebase_client, drecorder, display_controller)) self.pubnub.subscribe()\ .channels("pubnub_onboarding_channel")\ .with_presence()\ .execute() # self.firebase_client = firebase_client self.drecorder = drecorder self.display_controller = display_controller
def _subscribe(self, pnconfig, channels): listener = JobCompleteListener(self._check_message, self._poll_and_set_api_result, self._reset_polling_thread) pubnub = PubNub(pnconfig) pubnub.add_listener(listener) # Start our subscription 30 seconds in the past to catch any # missed messages. # https://www.pubnub.com/docs/python/api-reference-misc#time token = int((time.time() - 30) * 10**7) pubnub.subscribe().channels(channels).with_timetoken(token).execute() return pubnub
def test_success(self): try: env = PubNub(pnconf).delete_messages() \ .channel("my-ch") \ .start(123) \ .end(456) \ .sync() print(env) if env.status.error: raise AssertionError() except PubNubException as e: self.fail(e)
def test_encrypt_and_decrypt_file(self, file_for_upload, file_upload_test_data): pubnub = PubNub(pnconf_file_copy()) with open(file_for_upload.strpath, "rb") as fd: encrypted_file = pubnub.encrypt(KEY, fd.read()) decrypted_file = pubnub.decrypt(KEY, encrypted_file) if v == 3: assert file_upload_test_data[ "FILE_CONTENT"] == decrypted_file.decode("utf-8") else: assert file_upload_test_data["FILE_CONTENT"] == decrypted_file
def test_publish_with_ptto_and_replicate(self): timetoken_to_override = 16057799474000000 env = PubNub(pnconf_file_copy()).publish()\ .channel("ch1")\ .message("hi")\ .replicate(False)\ .ptto(timetoken_to_override)\ .sync() assert isinstance(env.result, PNPublishResult) assert "ptto" in env.status.client_request.url assert "norep" in env.status.client_request.url
def test_get_spaces(): config = pnconf_obj_copy() pn = PubNub(config) envelope = pn.get_spaces().include('custom').sync() assert(isinstance(envelope, Envelope)) assert not envelope.status.is_error() assert isinstance(envelope.result, PNGetSpacesResult) assert isinstance(envelope.status, PNStatus) data = envelope.result.data assert len(data) == 100 assert set(['name', 'id', 'description', 'custom', 'created', 'updated', 'eTag']) == set(data[0]) assert set(['name', 'id', 'description', 'custom', 'created', 'updated', 'eTag']) == set(data[1])
def test_invalid_key(self): config = pnconf_demo_copy() config.publish_key = "fake" try: PubNub(config).publish() \ .channel("ch1") \ .message("hey") \ .sync() self.fail(Exception("Should throw exception", 'pnsdk')) except PubNubException as e: assert "Invalid Key" in str(e)