PNAccessDeniedCategory for sending the message in pubnub objective c - objective-c

I am trying to send the message by using pubnub.
But it gives me error for : PNAccessDeniedCategory
I am not finding any solution how to solve this.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:#"pub-c-..."subscribeKey:#"sub-c-..."];
self.client = [PubNub clientWithConfiguration:configuration];
//Subscription process results arrive to listener which should adopt to PNObjectEventListener protocol and registered using:
[self.client addListener:self];
//Listeners callbacks:
[self.client subscribeToChannels: #[#"test123"] withPresence:YES];
NSLog(#"channel-->%#",self.client.channels);
configuration.uuid = #"test123";
}
- (void)client:(PubNub *)client didReceiveStatus:(PNSubscribeStatus *)status {
if (status.category == PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
}
else if (status.category == PNConnectedCategory) {
// Connect event. You can do stuff like publish, and know you'll get it.
// Or just use the connected event to confirm you are subscribed for
// UI / internal notifications, etc
}
else if (status.category == PNReconnectedCategory) {
// Happens as part of our regular operation. This event happens when
// radio / connectivity is lost, then regained.
}
else if (status.category == PNDecryptionErrorCategory) {
// Handle messsage decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}else if (status.category == PNAccessDeniedCategory) {
Nslog(#"It gives me this error");
}
}
Please advice. Whether this error is because my account is expired and that is the reason it is not allowing me to access ?
Do i have to create another free account ? or have to create new key ?
Please help.

PubNub Access Manager
You have Access Manager add-on enabled on your keys and so it is just doing its job - denying un-granted access to your keys. You must grant all access to use your keys once this is enabled. When you enable Access Manager a dialog pops up with a warning:
Warning: This action will enable Access Manager on your keyset. If you
are already using this keyset in a production application, please be
aware you will need to grant access to all existing channels in order
to continue use without interruptions.
Here is a snapshot of that dialog:
You can disable Access Manager until you are ready to implement the proper granting logic on your server and you will no longer get this error.
Before you go live with your app, you should implement the necessary granting logic and enable Access Manager to protect your keys from being wrongfully used.

Related

Task Module call from Ms Teams in Bot Framework

I am looking to open a task module (Pop up - iframe with audio/video) in my bot that is connected to Teams channel. I am having issues following the sample code provided on the GitHub page.
I have tried to follow the sample and incorporate to my code by did not succeed.
In my bot.cs file I am creating card action of invoke type:
card.Buttons.Add(new CardAction("invoke", TaskModuleUIConstants.YouTube.ButtonTitle, null,null,null,
new Teams.Samples.TaskModule.Web.Models.BotFrameworkCardValue<string>()
{
Data = TaskModuleUIConstants.YouTube.Id
}));
In my BotController.cs that inherits from Controller
[HttpPost]
public async Task PostAsync()
{
// Delegate the processing of the HTTP POST to the adapter.
// The adapter will invoke the bot.
await _adapter.ProcessAsync(Request, Response, _bot);
}
public async Task<HttpResponseMessage> Post([FromBody] Activity activity)
{
if (activity.Type == ActivityTypes.Invoke)
{
return HandleInvokeMessages(activity);
}
return new HttpResponseMessage(HttpStatusCode.Accepted);
}
private HttpResponseMessage HandleInvokeMessages (Activity activity)
{
var activityValue = activity.Value.ToString();
if (activity.Name == "task/fetch")
{
var action = Newtonsoft.Json.JsonConvert.DeserializeObject<Teams.Samples.TaskModule.Web.Models.BotFrameworkCardValue<string>>(activityValue);
Teams.Samples.TaskModule.Web.Models.TaskInfo taskInfo = GetTaskInfo(action.Data);
Teams.Samples.TaskModule.Web.Models.TaskEnvelope taskEnvelope = new Teams.Samples.TaskModule.Web.Models.TaskEnvelope
{
Task = new Teams.Samples.TaskModule.Web.Models.Task()
{
Type = Teams.Samples.TaskModule.Web.Models.TaskType.Continue,
TaskInfo = taskInfo
}
};
return msg;
}
return new HttpResponseMessage(HttpStatusCode.Accepted);
}
There is more code as per the GitHub sample but I won't paste it here. Can someone point me into the correct direction ?
I have got to the stage that it is displaying a pop up window but the content and title comes from manifest file instead of creating actual iframe also no video is rendering. My goal is to render video within my teams using iframe container.
The important part from the sample:
This sample is deployed on Microsoft Azure and you can try it yourself by uploading Task Module CSharp.zip to one of your teams and/or as a personal app. (Sideloading must be enabled for your tenant; see step 6 here.) The app is running on the free Azure tier, so it may take a while to load if you haven't used it recently and it goes back to sleep quickly if it's not being used, but once it's loaded it's pretty snappy.
So,
Your Teams Admin MUST enable sideloading
Your bot MUST be sideloaded into Teams
The easiest way to do this would be download the sample manifest, open it in App Studio, then edit your bot information in. You then need to make sure Domains and permissions > Valid Domains are set for your bot. Also ensure you change the Tabs URLs to your own.
You also need to make sure that in your Tasks, the URLs they call ALL use https and not http. If anywhere in the chain is using http (like if you're using ngrok and http://localhost), it won't work.

How to use FaceID using Xamarin.forms?

What I need to implement that Face ID authentication will work on Xamarin.forms project?
You have to do this natively on your iOS project, and then expose it to your Forms project using a DependencyService or some kind of ioc.
You must add to your info.plist the NSFaceIDUsageDescription key, otherwise the app will crash when asking for authentication.
Here is a snippet that authenticates a user locally:
var context = new LAContext();
LAContextReplyHandler replyHandler;
NSError AuthError;
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
{
replyHandler = new LAContextReplyHandler((success, error) =>
{
// Handle authentication success or error
});
// Authenticate and ask for permission if needed.
context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Authenticate", replyHandler);
}

Unable to Register IOS device to Mobile First 8

I am able to see the iOS device under devices tab in MF, registered to my application. but pushing a notification fails with the below error:
An error occurred while the notification was sent. Internal server error. No devices found.
Upon reviewing IOS code, I noticed the below issue while invoking MFPPush.sharedInstance.registerDevice(nil)
Cannot retrieve a valid authorization header for header. Check resource and authorization server configuration.
I am using the code from the git sample. Below is the snippet throwing the error:
#IBAction func registerDevice(_ sender: AnyObject) {
print("Attempting Device registration with Mobile First")
WLAuthorizationManager.sharedInstance().obtainAccessToken(forScope: "push.mobileclient") { (token, error) -> Void in
if (error != nil) {
print("Did not recieve an access token from server: " + error.debugDescription)
} else {
WLClient.sharedInstance()?.setDeviceDisplayName("White Ipad", withCompletionHandler: { (error) in
if error == nil{
print("device display name is set")
}else{
print("error setting device name: " + error.debugDescription)
}
})
print("Recieved the following access token value: " + (token?.value ?? "no token"))
MFPPush.sharedInstance().registerDevice(nil) { (response, error) -> Void in
if error == nil {
self.enableButtons()
self.showAlert("Registered successfully with Mobile First")
print(response?.description ?? "")
} else {
self.showAlert("Registration failed with Mobile First. Error \(error?.localizedDescription)")
print(error?.localizedDescription ?? "")
}
}
}
}
}
Mobile First Config: I have followed the documentation and configured the UserLogin security check from the sample git project and have removed scope to push.mobileclient under security.
Reading the OAuth Security in MF, i understand the that token is necessary to access resources, but I am unable to figure out how to attach the token in registerDevice().
It seems to be you haven't configured Push Notifications properly in MobileFirst Server.
Make sure that you have added push.mobileclient scope in Security tab of your application. If you are not using any security check, you can add scope like below.
Check whether your application is configured valid iOS provisioning profile enabled with Push Capability
Make sure that you have uploaded valid sandbox/production certificates in Push tab of your particular app in MFP Operations Console.
More details : here
Make sure your app is enabled Push Capability in the project setting and also check you sending device token to MF Server using MFPPush.sharedInstance().sendDeviceToken(deviceToken) API in didRegisterForRemoteNotificationsWithDeviceToken method of AppDelegate file
-

PushNotificationIOS.requestPermissions() callback

I don't want to ask my users to allow notifications before they actually need them in the app.
So when a user schedules a local notification in my app I want to request notification permissions and if the user accepts then set the local notification.
The problem is that there doesn't seem to be any callback for PushNotificationIOS.requestPermissions(), meaning that if I call PushNotificationIOS.checkPermissions() right after it will run before the user has tabbed the alert window and return 0 in the permissions object, even though the user might accept.
So my question is if there is any way to request permissions and subsequently set a notification, or do I have to request permissions before I actually need to use them?
There is the option to add an event listener for when a device registers for push notifications.
PushNotificationIOS.addEventListener('register', this._onPushNotificationRegistration);
When you attempt to schedule your local notification you can check the permissions at that point and if you don't have permission yet, you could request them.
_prepareNotification(alertBody, soundName, badge) {
let notification = {
alertBody: alertBody,
applicationIconBadgeNumber: badge,
fireDate: new Date(Date.now() + (1000 * 10)).getTime(), // 10 seconds in the future
soundName: soundName
};
PushNotificationIOS.checkPermissions((permissions) => {
if (permissions.alert) {
this._scheduleNotification(notification);
} else {
this._requestNotificationPermissions(notification);
}
});
}
When you request permissions, store the notification that you want to send in your state.
_requestNotificationPermissions(notification) {
this.setState({
notificationToPost: notification
});
PushNotificationIOS.requestPermissions();
}
When the user allows you to send them notifications, then schedule it in the registration response.
_onPushNotificationRegistration(token) {
console.log('Registered for notifications', token);
if (this.state.notificationToPost) {
this._scheduleNotification(this.state.notificationToPost);
}
}
This is a rough example of how you might achieve what you require, I am sure that there are nuances around you application state that this doesn't cover, but hopefully it will give you some ideas.
I have put some of these ideas into a sample application that you can have a look at https://github.com/AidenMontgomery/react-native-sample.
The release notes for v0.28-rc has just been published and one of the new features is that PushNotificationIOS.requestPermissions() has been promisified, which is exactly what I needed. See the commit here.

Prevent getting old updates from Telegram Bot API using a web hook

I'm writing a Telegram bot and I'm using the official bot API. I've got a webhook server that handles requests and sends a 200 OK response for every request.
Before the server stops, the webhook is detached so Telegram does not send updates anymore. However, whenever I turn the bot on and set the webhook URL again, Telegram starts flooding the webhook server with old updates.
Is there any way I can prevent this without requesting /getUpdates repeatedly until I reach the last update?
Here's a heavily simplified version of how my code looks like:
var http = require('http'),
unirest = require('unirest'),
token = '***';
// Attach the webhook
unirest.post('https://api.telegram.org/bot' + token + '/setWebhook')
.field('url', 'https://example.com/api/update')
.end();
process.on('exit', function() {
// Detach the webhook
unirest.post('https://api.telegram.org/bot' + token + '/setWebhook')
.field('url', '')
.end();
});
// Handle requests
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Thanks!');
});
server.listen(80);
Thanks in advance.
The best way is to use update_id which is a specific number that increases on every new request (i.e. update). How to implement it?
First off, let's start with the following anonymous class (using PHP7):
$lastUpdateId = new class()
{
const FILE_PATH = "last-update-id.txt";
private $value = 1;
public function __construct()
{
$this->ensureFileExists();
$this->value = filesize(self::FILE_PATH) == 0
? 0 : (int)(file_get_contents(self::FILE_PATH));
}
public function set(int $lastUpdateId)
{
$this->ensureFileExists();
file_put_contents(self::FILE_PATH, $lastUpdateId);
$this->value = $lastUpdateId;
}
public function get(): int
{
return $this->value;
}
public function isNewRequest(int $updateId): bool
{
return $updateId > $this->value;
}
private function ensureFileExists()
{
if (!file_exists(self::FILE_PATH)) {
touch(self::FILE_PATH);
}
}
};
What the class does is clear: Handling the last update_id via a plain file.
Note: The class is tried to be as short as possible. It does not provide error-checking. Use your custom implementation (e.g. use SplFileObject instead of file_{get|put}_contents() functions) instead.
Now, there are two methods of getting updates: Long Polling xor WebHooks (check Telegram bot API for more details on each methods and all JSON properties). The above code (or similar) should be used in both cases.
Note: Currently, it is impossible to use both methods at the same time.
Long Polling Method (default)
This way, you send HTTPS requests to Telegram bot API, and you'd get updates as response in a JSON-formatted object. So, the following work can be done to get new updates (API, why using offset):
$botToken = "<token>";
$updates = json_decode(file_get_contents("https://api.telegram.org/bot{$botToken}/getUpdates?offset={$lastUpdateId->get()}"), true);
// Split updates from each other in $updates
// It is considered that one sample update is stored in $update
// See the section below
parseUpdate($update);
WebHook Method (preferred)
Requiring support for HTTPS POST method from your server, the best way of getting updates at-the-moment.
Initially, you must enable WebHooks for your bot, using the following request (more details):
https://api.telegram.org/bot<token>/setWebhook?url=<file>
Replace <token> with you bot token, and <file> with the address of your file which is going to accept new requests. Again, it must be HTTPS.
OK, the last step is creating your file at the specified URL:
// The update is sent
$update = $_POST;
// See the section below
parseUpdate($update);
From now, all requests and updates your bot will be directly sent to the file.
Implementation of parseUpdate()
Its implementation is totally up to you. However, to show how to use the class above in the implementation, this is a sample and short implementation for it:
function parseUpdate($update)
{
// Validate $update, first
// Actually, you should have a validation class for it
// Here, we suppose that: $update["update_id"] !== null
if ($lastUpdateId->isNewRequest($update["update_id"])) {
$lastUpdateId->set($update["update_id"]);
// New request, go on
} else {
// Old request (or possible file error)
// You may throw exceptions here
}
}
Enjoy!
Edit: Thanks to #Amir for suggesting editions made this answer more complete and useful.
When you server starts up you can record the timestamp and then use this to compare against incoming message date values. If the date is >= the timestamp when you started...the message is ok to be processed.
I am not sure if there is a way you can tell Telegram you are only interested in new updates, their retry mechanism is a feature so that messages aren't missed...even if your bot is offline.
In the webhook mode, Telegram servers send updates every minute until receives an OK response from the webhook program.
so I recommend these steps:
Check your webhook program that you specified its address as url parameter of the setWebhook method. Call its address in a browser. It does not produce an output to view, but clears that probably there is no error in your program.
Include a command that produces a '200 OK Status' header output in your program to assure that the program sends this header to the Telegram server.
I have the same issue, then I tried to reset the default webhook with
https://api.telegram.org/bot[mybotuniqueID]/setWebhook?url=
after that, i verified the current getUpdates query were the same old updates but I sent new requests through the telegram's bot chat
https://api.telegram.org/bot[mybotuniqueID]/getUpdates
when I set up my webhook again the webhook read the same old updates. Maybe the getUpdates method is not refreshing the JSON content.
NOTE:
in my case, it was working fine until I decided to change /set privacy bot settings from botfather