Giter VIP home page Giter VIP logo

javascript's Introduction

PubNub JavaScript SDK (V4)

Build Status Codacy Badge npm Bower Known Vulnerabilities

This is the official PubNub JavaScript SDK repository.

PubNub takes care of the infrastructure and APIs needed for the realtime communication layer of your application. Work on your app's logic and let PubNub handle sending and receiving data across the world in less than 100ms.

Get keys

You will need the publish and subscribe keys to authenticate your app. Get your keys from the Admin Portal.

Tutorial Video

Getting Started with PubNub JS SDK

Watch Getting Started with PubNub JS SDK on Dashcam

Configure PubNub

  1. Integrate the JavaScript SDK into your project:

  2. Configure your keys:

pubnub = new PubNub({
  publishKey : "myPublishKey",
  subscribeKey : "mySubscribeKey",
  uuid: "myUniqueUUID"
})

Add event listeners

pubnub.addListener({
  message: function (m) {
    // handle messages
  },
  presence: function (p) {
    // handle presence  
  },
  signal: function (s) {
    // handle signals
  },
  objects: (objectEvent) => {
    // handle objects
  },
  messageAction: function (ma) {
    // handle message actions
  },
  file: function (event) {
    // handle files  
  },
  status: function (s) {
  // handle status  
  },
});

Publish/subscribe

var publishPayload = {
    channel : "hello_world",
    message: {
        title: "greeting",
        description: "This is my first message!"
    }
}

pubnub.publish(publishPayload, function(status, response) {
    console.log(status, response);
})

pubnub.subscribe({
    channels: ["hello_world"]
});

Documentation

Support

If you need help or have a general question, contact [email protected].

javascript's People

Contributors

aaronlevy avatar anovikov1984 avatar are avatar are-pubnub avatar budgetpreneur avatar client-engineering-bot avatar crimsonred avatar davidnub avatar dependabot[bot] avatar frederickbrock avatar grydstedt avatar jasonpoe avatar jeffgreen7 avatar jskrzypek avatar juliangruber avatar jzucker2 avatar kerumen avatar kirill-konshin avatar manuelfernando avatar maxpresman avatar michaljolender avatar mjdickinson avatar mohitpubnub avatar parfeon avatar phairow avatar pubnubcraig avatar seba-aln avatar stephenlb avatar techwritermat avatar thomasconner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javascript's Issues

Listener exception generates status 400, error should contain contextual error information

Hi,

It took me a few days to track down the source of a strange subscription bug.

In my case, I had a listener with a presence function such as:

  presence: (presenceEvent) => {
    const { uuid, action } = presenceEvent;
    const someVar = null.replace('foo', 'bar'); // Throws

Upon connection and subscription withPresence, this generates a status listener event with code 400 and empty errorData:

statusEvent:{
   "statusCode": 400,
   "error": true,
   "operation": "PNSubscribeOperation",
   "errorData": {},
   "category": "PNUnknownCategory"
}

I went in and added debug to show me the e.stack on line 237 of core/components/endpoint.js:

    responseP
      .then((result) => {
        if (callback) {
          callback(status, result);
        } else if (promiseComponent) {
          promiseComponent.fulfill(result);
        }
      })
      .catch((e) => {
        console.log(`onResponse caught error at ${JSON.stringify(e.stack, null, 3)}`);  // DEBUG HERE
        
        if (callback) {
          let errorData = e;

          if (endpoint.getOperation() === operationConstants.PNSubscribeOperation) {
            errorData = {
              statusCode: 400,
              error: true,
              operation: endpoint.getOperation(),
              errorData: e,
              category: categoryConstants.PNUnknownCategory,
            };
          }

          callback(errorData, null);
        } else if (promiseComponent) {
          promiseComponent.reject(new PubNubError('PubNub call failed, check status for details', e));
        }
      });

The response was pretty obvious:

onResponse caught error at "TypeError: Cannot read properties of undefined (reading 'replace')\n    at Object.presence ..... pubnub-javascript/lib/core/components/endpoint.js:235:17\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)"

It would have saved me a lot of time if the errorData contained at least some information.

SDKError: Ti is not defined

Background:
When we started using pubnub (v 4.37.x), we started getting could not load bridge.js error.
Issue is described here which is still open #266

bridge.js belongs to vm2, it's used by pubnub -> degenerator -> vm2.
webpack couldn't handle contents of vm2 (bridge.js).

In order to fix this issue, we used pubnub.min.js from pubnub/dist/titanium/pubnub.min.js

Below was the fix added in webpack config:

resolve: {
      extensions: ['.tsx', '.ts', '.js'],
      alias: {
        pubnub: path.resolve(appModulesDir, 'pubnub', 'dist', 'titanium', 'pubnub.min.js')
      }
},

This temporary fix worked for sometime.
But now we are getting different error "SDKError: Ti is not defined" on below line -

https://github.com/pubnub/javascript/blob/master/lib/networking/modules/titanium.js#L27

Can someone please suggest what might be causing this problem?

Environment Details:
Node v14.18.3
NPM v6.14.15
Webpack v4.46.0

Exception being thrown on load in Firefox

I'm not entirely sure if this is a problem with the library or our implementation, however it seems to be working in all other browsers.

this function here Is throwing the exception can't convert undefined to object, specifically on the ? 'px' : '' line.

The full error is

NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument arg 0 [nsIDOMWindow.getComputedStyle]
[Break On This Error]   

? 'px' : ''

The code that I'm calling pubnub from is

item_template = _.template $('#post-stream-item-tmpl').text()
schema = $.parseJSON($('#post-stream-item-schema').text())['5']
channels = $('#post-stream-item-tmpl').data 'channel'

callback = (schemaless_data) ->
    console.log schemaless_data
    data = datascheme.load schema, schemaless_data
    if data.v
        if data.v >= 2 and data.type is "discussion"
            this_dtf = dtf data.content.post_date
            data.content.formatted_date_time = this_dtf()

            for id, stock of data.content.stocks
                stock.url = stock.page_slug.split('-').join('/')
                data.content.stocks[id] = stock

            rendered = item_template data.content
            line = $($.parseHTML rendered)
            line.hide().prependTo($(".live-stream")).slideDown 500
            line.data 'tmpl-data', JSON.stringify data.content

            update_datetime line, this_dtf
            return

history_callback = (history_data) ->
    messages = history_data.shift()
    for message in messages
        callback message

pubnub = PUBNUB.init
    publish_key: 'redacted'
    subscribe_key: 'redacted'
    ssl: no

pubnub.ready()

for channel in channels.split(',')
    console.log "channel: #{channel}"
    pubnub.history
        channel: channel
        limit: 50
    , history_callback

pubnub.subscribe
    channel: channels
    callback: callback

The channel console.log appears in firebug before the error occurs.

If it will help I can email you a link to our private testing site so you can see the issue for yourself. I understand details are rather sparse in this issue, I'm stumped as to what's going wrong.

Thanks,
Jacob

.ready() not defined using PUBNUB.secure

When initializing with PUBNUB.secure() call instead of PUBNUB.init(), the .ready() function is not provided.

Two questions:

  1. Isn't .ready() needed when including pubnub in <head>? (I can't move it to last element in body for my solution.)
  2. Can I expect .secure() to be a pure extension of what init() creates?

example code:

    if (Messaging.Settings.Cipher) {
      provider = PUBNUB.secure({
        subscribe_key: Messaging.Settings.SubscriptionKey,
        ssl: Messaging.Settings.Secure || false,
        origin: Messaging.Settings.Origin,
        cipher_key: Messaging.Settings.Cipher
      });
    }
    else {
      provider = PUBNUB.init({
        subscribe_key: Messaging.Settings.SubscriptionKey,
        ssl: Messaging.Settings.Secure || false,
        origin: Messaging.Settings.Origin
      });
    }

    provider.ready();   // must use this since we are using pubnub in head

Any chance this libary will be updated to support Service Workers

Using this in a chrome extension development:

https://chrome.google.com/webstore/detail/nodejs-v8-inspector-manag/gnhhdgbaldcilmgcpfddgdbkhjohddkj?hl=en
https://microsoftedge.microsoft.com/addons/detail/nodejs-v8-inspector-ma/injfmegnapmoakbmnmnecjabigpdjeme

and moving to MV3 which uses ServiceWorkers and not background scripts... I'm running into issues with this library. I was able to get around a "window undefined" issue by setting listenToBrowserNetworkEvents to false, however another problem now is that the library uses superagent which in turn uses XHR. And unfortunately, XHR is not supported by MV3

Workers no longer provide XMLHttpRequest, but instead support the more modern fetch() https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/

So again, any feedback on this would be greatly appreciated.

objects event listener is not triggered when a new channel membership is added

Expected Behaviour

Calling pubnub.objects.setChannelMembers and pubnub.objects.setChannelMetadata should trigger objects event listener.

Actual Behaviour

The objects event listener is not triggered, regardless if the pubnub.objects.setChannelMembers and pubnub.objects.setChannelMetadata is called by the event listener owner to add himself/herself as a member to a channel, or is called by another user to add the event listener owner a member to a channel.

How to handle multiple instances in node

I can't find an answer to this anywhere.

It's recommended to have a different uuid for each user or device. This uuid is used in the constructor function, when calling new PubNub. This means that on your server there will be a zillion pubnub instances? Should creating these be memoized? Do they persist a connection which needs to be closed?

Consider the following code:

export const sendUserNotification = (userId: string, channel: Channel, message: Notification) => {
  const pubnub = new PubNub({
    publishKey: PUBNUB_PUBLISH_KEY,
    subscribeKey: PUBNUB_SUBSCRIBE_KEY,
    uuid: userId,
  });
  return pubnub.publish({ channel, message });
};

is it ok to just new one up whenever you need it? Will it be garbage collected when the function closes, or will this create a memory leak?

CVE-2021-23406 - update superagent-proxy dependency to v 3.0.0

This is a request to update the superagent-proxy dependency to version 3.0.0.

The superagent-proxy dependency currently introduces remote code execution vulnerability via [email protected][email protected][email protected][email protected].

[email protected] resolves this vulnerability with an update to [email protected]: TooTallNate/superagent-proxy@1a5b9f3

References:
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-23406
https://httptoolkit.tech/blog/npm-pac-proxy-agent-vulnerability/

messages not compressed

From the documentation is sounds as if message compression is supported by the JS API. On inspection with the browsers developer tools this seems to be false.
https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#methods

sendByPost boolean Optional false When true, the SDK uses HTTP POST to publish the messages. The message is sent in the BODY of the request, instead of the query string when HTTP GET is used. Also the messages are compressed thus reducing the size of the messages. Using HTTP POST to publish messages adheres to RESTful API best practices.

vm2 (via pac-proxy-agent) causes build failures in webpack

We recently attempted to upgrade our version of pubnub but we're blocked by similar issues to the one highlighted by:
#239

In our case, vm2 makes a call to require(coffee-script) and attempts to call readFileSync on a file called bridge.js that it supplies both of which cause our build to fail.

It looks like we should be able to work around it by patching out the dependency on pac-proxy-agent. Basically, I have two questions:

  • under what circumstances would pubnub use pac proxies (if ever)
  • if the pubnub client doesn't use pac proxies, would it be possible for pubnub to patch out it's dependency on pac-proxy-agent since vm2 seems to be causing issues for some users using webpack?

Edit: we're currently on 4.29.7, we've attempted to upgrade to a couple of different versions but any greater version than our current version caused these issues.

get_file_url should support both token manager token and auth key like other endpoints

Problem
1- We are using access manager
2- Uploading image is working
2- While getFileUrl returns 403 as auth query param is missing from the URL

image

Request URL: http://ps1.pndsn.com/v1/files/sub-c-63321534-3032-46d3-af6f-74f7903e3dff/channels/7c0c5ea3-5290-4635-9add-db52305ce8db-team-team-10407-7c0c5ea3-5290-4635-9add-db52305ce8db/files/3f5f57df-10b5-49d8-b898-9276c81bda16/5ab4d4ac2000007d06eb2c56.jpeg?uuid=7c0c5ea3-5290-4635-9add-db52305ce8db-abdallanayer0754&pnsdk=PubNub-JS-Web%2F7.2.0%20RCC%2F0.13.0
Request Method: GET
Status Code: 403 Forbidden

while other endpoints have an isAuthSupported flag, getFileUrl is not an endpoint and it doesnot have isAuthSupported flag

Desired Solution:
getFileUrl should work with the access manager as other endpoints do example (generate_upload_url)

Allow to send Json-RPC messages over POST

Allow to send JSON data over POST messages to create a JSON-RPC communication channel, both for notifications (no response) or for remote calls (response, maybe only first is accepted by caller). To do it correctly according to the Json-RPC over HTTP specification, it's prefered to do it over POST messages instead of using a GET request as PubNub Javascript client does currently. Also this would allow to don't need to escape characters, so they could be send faster and using less bandwidth, so JSON structures could be bigger using the same space.

Allow to send data as ArrayBuffer and Blob

Currently PubNub allow to send data in the basic types (number, string, object, text...). I propose to allow to send it as ArrayBuffer and Blob, so it can be send also on binary form, for example using MessagePack, so data don't get lenght increased.

event.returnValue is deprecated

On Chromium v31, event.returnValue is deprecated and raise a warning, and recommends to use event.preventDefault() instead.

Use real WebSockets

Allow to use native WebSockets if desired instead of the implemented WebSocket Client Specification.

Is `subscribeRequestTimeout` a supported API parameter?

In this issue - pubnub/react#1 - @are indicates that using subscribeRequestTimeout is an appropriate way to handle this timeout which causes warnings in Android React Native with the default configuration, however this is not in the JS SDK documentation as far as I can see, and isn't in @types/pubnub. I opened a PR with the DefinitelyTyped project here DefinitelyTyped/DefinitelyTyped#60003 , but there is reluctance to add an undocumented option into the library if it's possible that may disappear sometime in the future.

Can you all provide any clarifying comment on whether it's appropriate to add it to the Typescript types?

PubNub v7.2.0 import/require cycles warning

After upgrading to PubNub v7.2.0 we started getting this warning message about the import cycles.

Require cycles are allowed but can result in uninitialized values. Consider refactoring to remove the need for a cycle.

Screen Shot 2022-09-26 at 11 38 44 AM

4.34.0: Increase in size of compared to previous version

Hello,

We noticed that there was an order of magnitude in the size of the build for this project.

https://www.npmjs.com/package/pubnub/v/4.33.1 (6.23 MB)
https://www.npmjs.com/package/pubnub/v/4.34.0 (35.9 MB)

We don't use this project directly but it came in as a transitive dependency. We had to chase down why our build had a dramatic increase between yesterday and today (we deploy to AWS lambda and this size increase pushed our build over the permitted size).

Just wanted to point this out as it might break others too.

Thanks!

[enhancement] Add missing bower.json.

Hey, maintainer(s) of pubnub/javascript!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library pubnub/javascript is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "pubnub/javascript",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Stack overflow in IE11 when using "modern" library

I've confirmed that this does not happen in IE 10, but I can reproduce it every time in IE11 (Win 8.1) using both the modern/pubnub.min.js and modern/pubnub.js. Here is the call stack from from the non-minified version.

screen shot 2013-10-31 at 11 08 34 am

Node.js publish error callback is misleading/non-standard

The standard callback signature in node is (err[, data...]) which is passed as the last argument to a function call.

Using the Node api, pubnub.publish takes parameters and a cb which looks like the standard cb pattern but is not.

The parameters publish passes back is just an array formatted like [ Number, “Status”, “Time Token”] which is non-standard.

Even worse the callback will 'sometimes' be called with an error (I assume 4xx kinds of errors) while other times it won't be called at all (5xx kinds of errors) because params.error is called instead.

This error callback parameter is easy to overlook since the api seems to follow the standard node cb pattern but actually requires a second error handler. If the error handler parameter is left out it can cause apis that sometimes never call back which can cause awful things to happen like requests hanging open forever.

Please consider changing the api to be more standard.

Undocumented callback arguments

A your API reference at https://www.pubnub.com/docs/javascript/api/reference.html#subscribe does not describe the arguments being passed to the callbacks, I started to add code like this to my callback method:

log('callback called with', arguments.length, 'argument(s)');
for (var i = 0; i < arguments.length; i += 1) {
    log('    ', i + 1, ':', arguments[i]);
}

And thus, I realized that your small examples only care about the first first argument for the callback parameter: message.

The other three arguments are not documented.

Here are my conclusions, please verify and update the API reference:

  • message, just as described in the documentation
  • bucket, this looks like an array of currently received messages, put into an array along with a timestamp: [ [ message ], timestamp ] (with message being the first argument to the callback
  • channelID, the ID of the channel that was subscribed to
  • someNumber, a floating point number (I have no clue what this is)

Listener callback is invoked multiple times when message is published and when calling subscribe multiple times

Edit: Changed the title to be more representative of the bug at hand.

Seeing some interesting behavior differences after upgrading to version 4.34.0.

Services currently enabled on my key:

  • Storage and playback
  • Stream controller
  • Access Manager

Context here is a simple chat application. On message publish, a client receives that message via subscribing to the channel. However, a special situation here is we are subscribed to a channel group.

  • Upon first publish, the client correctly hears a single event, and the handler is called once.
    • Also push a signal to the subscribed channel group. Observe still the handler is called once. (We have attached a channel for this signal onto the channel group).
  • Publish a 2nd message now, and also publish another signal to the subscribed channel group.
  • Observe that the handler is called multiple times.
    • I've seen a varying amount of invocations, sometimes its 4 calls to the handler, sometimes 3, sometimes its just 1.

Affected version: 4.34.0
Unaffected version: 4.33.1

Actual outcome:
Multiple invocations to the handler.

Expected outcome:
A single invocation to the handler.

Unable to add a Channel with a period to a Channel Group

Hello,

I'm trying to follow the documentation for adding channels to a channel group, and even using the exact same code outlined in the docs:

pubnub.channelGroups.addChannels({
   channels: ["chats.room1", "chats.room2", "alerts.system"],
   channelGroup: "cg_user123"
})

from: https://www.pubnub.com/docs/channels/subscribe#channel-groups

I get the following error:

text: '{"status": 400, "message": "Reserved character in input parameters.", "service": "channel-registry", "error": true}'`

If I remove the periods and just do ['chatsroom1', 'chatsroom2', 'alertssystem'] then it works just fine. Any reason why this would be erroring out? I'm under the impression that the period in channel names is valid, and even recommended.

Any help is appreciated. Thanks!

SyntaxError: Unexpected string in vm2

hello!

I'm trying to upgrade to the latest pubnub (4.37.0) in our webpack'ed nodejs app. It installs fine, but at runtime I see the following error which creates a fatal error:

/Users/bcanzanella/code/codestream/shared/agent/dist/agent.js:225193
	__webpack_require__("./node_modules/vm2/lib sync recursive"),
	                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected string
    at wrapSafe (internal/modules/cjs/loader.js:1033:16)
    at Module._compile (internal/modules/cjs/loader.js:1081:27)
    at Object..js (internal/modules/cjs/loader.js:1155:10)
    at Module.load (internal/modules/cjs/loader.js:982:32)
    at internal/modules/cjs/loader.js:823:14
    at Function._load (electron/js2c/asar_bundle.js:5:12913)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

vm2 appears to be a dependency of a dependency... from pubnub:

bcanzanella@C02FG42AMD6P:~/code/codestream/shared/agent [develop]$ npm list vm2
[email protected] /Users/bcanzanella/code/codestream/shared/agent
└─┬ [email protected]
  └─┬ [email protected]
    └─┬ [email protected]
      └─┬ [email protected]
        └─┬ [email protected]
          └─┬ [email protected]
            └── [email protected] 

pubnub version 4.33.1 works (which doesn't have a dependency on a dependency on vm2).

I just wanted to see if you had any guidance for how to resolve this? thanks!

pubnub.push.listChannels only return 500 channels MAX

const res = await pubnub.push.listChannels({
device: string,
pushGateway: string,
environment: string,
topic: string
})

console.log(res.channels.lenght) // only return 500 max

there is no mentioned of any paginations in docs if exist
WHY ???????????????????????????????????????????????????????????

This is hilarious

`Buffer` is not a browser method

PubNub client has been failing for us since we upgraded to the latest Webpack, which no longer polyfills nodejs methods.

Screen Shot 2022-09-06 at 9 40 43 PM

The issue here is that this library uses a non standard global Buffer method. There may be a case where this is failing for others who have upgraded to the latest compilers too.

Some thoughts:

  1. Convert to using browser standards for buffers.
  2. If that is not in the timelines, perhaps make the error more graceful, with the library explicitly checking for if Buffer exists. I wouldn't be surprised if other users of PubNub are not aware their client started failing due to a webpack upgrade.

As an aside, are there docs on where/how to handle errors like this? We weren't aware of the issue for months as nothing obvious was erroring within the addListener({message method, and logVerbosity:true did not surface any errors.

Channel names are not properly encoded

If you create a channel name with a # in it, it will not properly encode and thus subscription will fail. For example, create a channel named something like "BaseName#123456789". A get request is made where the channel name is in the URL and it fails due to the #. This only appears to be an issue on the most recent version: 3.5.43. It works correctly on previous versions, including 3.5.4.

The fix appears to be as simple as adding # to the list of characters that are encoded. Specifically, adding it to Line 169 (and probably Line 173) of the modern version of pubnub.js. In the encode() and encode_param() functions.

Conversion to Expo-Modules

Using React : 17.0.1
react-native: 0.64.2
pubNub: 4.32.1
pubNub-react: 2.1.0
Expo SDK: 43

Recently Expo deprecated react-native-unimodules in favor of Expo-Modules. I was working on converting our project but learned that pubNub uses "isomorphic-webCrypto" which has:

"@unimodules/core": "*", 
 "@unimodules/react-native-adapter": "*" 

listed as dependencies.
This installs those two packages making a conversion to Expo-modules impossible due to a "dual symbol" in 12 expo packages due to a conflict between "libExpoModulesCore" and "UMReactNativeAdapter".
I was wondering if you know if there will be a conversion to Expo-Modules anytime soon
Thank you !

❌  duplicate symbol '_EXCanAskAgain' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_EXExpiresKey' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_EXGrantedKey' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_EXPermissionExpiresNever' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_EXStatusKey' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_OBJC_CLASS_$_EXPermissionsService' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_OBJC_IVAR_$_EXPermissionsService._moduleRegistry' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_OBJC_IVAR_$_EXPermissionsService._requesters' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_OBJC_IVAR_$_EXPermissionsService._requestersByClass' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_OBJC_METACLASS_$_EXPermissionsService' in
┌─ libExpoModulesCore.a(EXPermissionsService.o)
└─ UMReactNativeAdapter(EXPermissionsService.o)

❌  duplicate symbol '_OBJC_CLASS_$_EXReactNativeUserNotificationCenterProxy' in
┌─ libExpoModulesCore.a(EXReactNativeUserNotificationCenterProxy.o)
└─ UMReactNativeAdapter(EXReactNativeUserNotificationCenterProxy.o)

❌  duplicate symbol '_OBJC_METACLASS_$_EXReactNativeUserNotificationCenterProxy' in
┌─ libExpoModulesCore.a(EXReactNativeUserNotificationCenterProxy.o)
└─ UMReactNativeAdapter(EXReactNativeUserNotificationCenterProxy.o)


❌  ld: 12 duplicate symbols for architecture x86_64



❌  clang: error: linker command failed with exit code 1 (use -v to see invocation)

Subscribe api keeps pending

Subscribe api keeps pending, with no status change
Have no idea what happened?
Any solution to tackle this down?

messageCounts returns 1 extra

Expected Behaviour

Calling pubnub.messageCounts from user1 after receiving a new message from user2 should return a count of 1 in the corresponding channel

Actual Behaviour

When user1 has received a message from user2 for the very first time, messageCounts returns 2 for the newly made channel. All future messages correctly increment messageCounts by 1.

Has anyone else seen this problem before?

Also, how could I begin debugging this if it is a problem on my end?

XHR requests when offline

On Modern library 3.6.2, when using it while being offline (no internet) the library enters in a loop making failing GET requests, wasting battery and filling browser console of garbage. I think if it gets a failure it should use the Offline API to check if the browser has in fact an internet connection and register an event to when it comes back instead of doing requests in a loop. Also, it would be nice that when it gets offline it would raise an event to notify to the user.

Make Node.js version compatible with Browserify

When using Browserify, the Node.js version export and use some internal references to the 'http' module that are not fixed by the shim, leading to a crash. PubNub should be compatible with Broserify since it already has support for browser clients.

    require('http').globalAgent.maxSockets = Infinity;

Uncaught TypeError: Cannot set property 'maxSockets' of undefined

PAM not working with Pubnub's socket.io client

I'm updating my sample Pubnub socket.io code to make use of PAM and have already done the following things -

  1. Turned on the PAM feature in my account
  2. Executed code to grant channel level permissions to my auth keys
  3. Verified publishing and subscribing over the channel using the auth key using the Pubnub JS client

Now when i try the code below to use both a broadcast (read-only) channel and a chat channel (read-write), it doesn't work. I keep getting an error in the console every second

- GET http://ps11.pubnub.com/subscribe/<sub key>/broadcast%2Cchat/0/0?uuid=71a07f02-3ff5-4903-9abd-d6aaab219607&auth=F4530130-49C6-9319-68A2E6E-br-ro&pnsdk=PubNub-JS-Web%2F3.5.47 - 403 Forbidden

If i just setup a broadcast channel, i get a 403 error once but receiving broadcasts works. If i just setup a chat channel, i get no errors.

<!DOCTYPE html>
<html>
<head>
    <title>Pubnub sender</title>
    <script src="http://cdn.pubnub.com/socket.io.min.js"></script>
    <script>
        var pubnub_setup = {
            channel       : 'unused',
            auth_key      : 'unused',
            presence      : false,
            publish_key   : 'my_pub_key',
            subscribe_key : 'my_sub_key'
        };

        // This method needs to work with both - pubnub socket.io library and the
        // original socket.io library.
        // Note - I have verified that multiplexing works in the pubnub case
        function add_connection(channel_name, auth_key) {
            pubnub_setup.channel = channel_name;
            pubnub_setup.auth_key = auth_key;
            return(io.connect('http://pubsub.pubnub.com/' + channel_name, pubnub_setup));
        }

        // To send a message on this channel, open the console on the browser page and
        // type -> broadcast.send('Hi');
        broadcast = add_connection('broadcast', 'F4530130-49C6-9319-68A2E6E-br-ro');
        broadcast.on('connect', function() { console.log('Broadcast connection Estabished!')});
        broadcast.on('message', function(data) { console.log('Broadcast msg - ' + data)});

        // To send a message on this channel, open the console on the browser page and
        // type -> chat.send('Hi');
        chat = add_connection('chat', '386758D0-29E4-45DF-A581887-ch-rw');
        chat.on('connect', function() { console.log('Chat connection Estabished!')});
        chat.on('message', function(data) { console.log('Chat msg - ' + data)});
    </script>
</head>
<body>

</body>
</html>

Strange error events with node.js

I wrote a node.js script which essentially does this:

// some code here

pubnub.subscribe({
    channel: 'some channel id',
    callback: function () {/* … */},
    connect: function () {/* … */},
    disconnect: function () {/* … */},
    reconnect: function () {/* … */},
    error: function (error) {
        if (error === undefined) {
            throw new Error('unexpected error: ' +
                            util.inspect(error));
        }
        /* … */
    }
});

// some code here

Here is what I caught:

Error: unexpected error: undefined
    at <anonymous> (<the line of my throw statement above>)
    at SELF.subscribe.xdr.fail (~/node_modules/pubnub/pubnub.js:637:25)
    at done (~/node_modules/pubnub/pubnub.js:1084:23)
    at finished (~/node_modules/pubnub/pubnub.js:1068:32)
    at IncomingMessage.<anonymous> (~/node_modules/pubnub/pubnub.js:1124:17)
    at IncomingMessage.EventEmitter.emit (events.js:126:20)
    at IncomingMessage._emitEnd (http.js:366:10)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
    at Socket.socketOnData [as ondata] (http.js:1367:20)
    at TCP.onread (net.js:404:27)

This is node.js v0.8.16 with [email protected].

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.