Last active
December 15, 2015 17:50
-
-
Save keimpema/5299562 to your computer and use it in GitHub Desktop.
Retrieving location data from OpenPaths.cc using DevDefined.Oauth library (http://nuget.org/packages/DevDefined.OAuth). Code is based on http://www.markerstudio.com/technical/2009/09/net-oauth-sample-working-with-justintv .
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class OpenPathsRequest | |
{ | |
private static DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); | |
private const string accessKey = "your personal access key"; | |
private const string secretKey = "your personal secret"; | |
private const string url = "https://openpaths.cc/api/1"; | |
private OAuthSession session; | |
public OpenPathsRequest() | |
{ | |
var consumerContext = new OAuthConsumerContext | |
{ | |
ConsumerKey = accessKey, | |
ConsumerSecret = secretKey, | |
SignatureMethod = SignatureMethod.HmacSha1, | |
UseHeaderForOAuthParameters = true | |
}; | |
session = new OAuthSession(consumerContext, url, url, url); | |
} | |
private string GetWebResponseAsString(HttpWebResponse response) | |
{ | |
Encoding enc = System.Text.Encoding.GetEncoding(1252); | |
StreamReader loResponseStream = new StreamReader(response.GetResponseStream(), enc); | |
return loResponseStream.ReadToEnd(); | |
} | |
private double UtcToUnixTimestamp(DateTime utcDateTime) | |
{ | |
var unixTimestamp = (utcDateTime - epoch).TotalSeconds; | |
return unixTimestamp; | |
} | |
public string GetResponse(DateTime? utcStartTime = null, DateTime? utcEndTime = null, int numPoints = 0) | |
{ | |
var pars = new Dictionary<string, object>(); | |
if (utcStartTime.HasValue) | |
{ | |
pars.Add("start_time", (long)UtcToUnixTimestamp(utcStartTime.Value)); | |
} | |
if (utcEndTime.HasValue) | |
{ | |
pars.Add("end_time", (long)UtcToUnixTimestamp(utcEndTime.Value)); | |
} | |
if (numPoints != 0) | |
{ | |
pars.Add("num_points", numPoints); | |
} | |
// openpaths.cc requires signing before adding query parameters | |
// (I believe this is not according to the oauth specs but it works) | |
var request = session.Request().Get().ForUrl(url).SignWithoutToken(); | |
if (pars.Count > 0) | |
{ | |
request = request.WithQueryParameters(pars); | |
} | |
var response = request.ToWebResponse(); | |
var result = GetWebResponseAsString(response); | |
return result; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var now = DateTime.UtcNow; | |
var request = new OpenPathsRequest(); | |
var response = request.GetResponse(now.AddHours(-12), now, 5); | |
Console.WriteLine(response); | |
Console.WriteLine("Press any key..."); | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment