bitwarden-android/src/iOS/NFCReaderDelegate.cs

54 lines
1.6 KiB
C#
Raw Normal View History

2019-06-12 05:20:59 +03:00
using CoreNFC;
using Foundation;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Bit.iOS
{
public class NFCReaderDelegate : NFCNdefReaderSessionDelegate
{
private Regex _otpPattern = new Regex("^.*?([cbdefghijklnrtuv]{32,64})$");
private Action<bool, string> _callback;
public NFCReaderDelegate(Action<bool, string> callback)
{
_callback = callback;
}
public override void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
{
var results = new List<string>();
foreach (var message in messages)
2019-06-12 05:20:59 +03:00
{
foreach (var record in message.Records)
2019-06-12 05:20:59 +03:00
{
try
{
results.Add(new NSString(record.Payload, NSStringEncoding.UTF8));
}
catch { }
}
}
foreach (var result in results)
2019-06-12 05:20:59 +03:00
{
var matches = _otpPattern.Matches(result);
if (matches.Count > 0 && matches[0].Groups.Count > 1)
2019-06-12 05:20:59 +03:00
{
var otp = matches[0].Groups[1].ToString();
_callback.Invoke(true, otp);
return;
}
}
_callback.Invoke(false, "No tags were read.");
}
public override void DidInvalidate(NFCNdefReaderSession session, NSError error)
{
_callback.Invoke(false, error?.LocalizedDescription);
}
}
}