fixes GCM id sending to server

main
Paul Schneider 10 years ago
parent 50736c6684
commit 07e82f9f14
13 changed files with 366 additions and 53 deletions

@ -0,0 +1,103 @@
//
// PostJson.cs
//
// Author:
// Paul Schneider <paulschneider@free.fr>
//
// Copyright (c) 2015 Paul Schneider
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Net;
using System.IO;
using System.Json;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System;
namespace Yavsc.Helpers
{
/// <summary>
/// Simple json post method.
/// </summary>
public class SimpleJsonPostMethod : IDisposable
{
private HttpWebRequest request=null;
/// <summary>
/// Initializes a new instance of the Yavsc.Helpers.SimpleJsonPostMethod class.
/// </summary>
/// <param name="pathToMethod">Path to method.</param>
public SimpleJsonPostMethod (string pathToMethod, string authorizationHeader = null)
{
request = (HttpWebRequest) WebRequest.Create (
BasePath + pathToMethod);
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
request.SendChunked = true;
request.TransferEncoding = "UTF-8";
if (authorizationHeader!=null)
request.Headers.Add($"Authorization: Bearer {authorizationHeader}");
}
public static string BasePath { get; private set; } = "http://dev.pschneider.fr/api/";
public void Dispose()
{
request.Abort();
}
/// <summary>
/// Invoke the specified query.
/// </summary>
/// <param name="query">Query.</param>
public TAnswer Invoke<TAnswer>(object query)
{
using (Stream streamQuery = request.GetRequestStream()) {
using (StreamWriter writer = new StreamWriter(streamQuery)) {
writer.Write (JsonConvert.SerializeObject(query));
}}
TAnswer ans = default (TAnswer);
using (WebResponse response = request.GetResponse ()) {
using (Stream responseStream = response.GetResponseStream ()) {
using (StreamReader rdr = new StreamReader (responseStream)) {
ans = (TAnswer) JsonConvert.DeserializeObject<TAnswer> (rdr.ReadToEnd ());
}
}
response.Close();
}
return ans;
}
public async Task<JsonValue> InvokeJson(object query)
{
JsonValue jsonDoc=null;
using (Stream streamQuery = request.GetRequestStream()) {
using (StreamWriter writer = new StreamWriter(streamQuery)) {
writer.Write (JsonConvert.SerializeObject(query));
}}
using (WebResponse response = request.GetResponse ()) {
using (Stream stream = response.GetResponseStream ()) {
if (stream.Length>0)
jsonDoc = await Task.Run (() => JsonObject.Load (stream));
}
response.Close();
}
return jsonDoc;
}
}
}

@ -20,6 +20,8 @@ using System.Net.Http;
using System.Text; using System.Text;
using BookAStar.Model.Auth.Account; using BookAStar.Model.Auth.Account;
using BookAStar.Droid.OAuth; using BookAStar.Droid.OAuth;
using Yavsc.Helpers;
using Yavsc.Models.Identity;
namespace BookAStar.Droid namespace BookAStar.Droid
{ {
@ -257,23 +259,57 @@ namespace BookAStar.Droid
throw new NotImplementedException("Auth_Error"); throw new NotImplementedException("Auth_Error");
} }
public class GCMDeclaration : IGCMDeclaration
{
public string DeviceId
{ get; set; }
public string GCMRegistrationId
{ get; set; }
public string Model
{ get; set; }
public string Platform
{ get; set; }
public GoogleCloudMobileDeclaration GetDeviceInfo() public string Version
{ get; set; }
}
public IGCMDeclaration GetDeviceInfo()
{ {
var devinfo = DeviceInfo.Plugin.CrossDeviceInfo.Current; var devinfo = DeviceInfo.Plugin.CrossDeviceInfo.Current;
return new GoogleCloudMobileDeclaration return new GCMDeclaration
{ {
DeviceId = devinfo.Id, DeviceId = devinfo.Id,
GCMRegistrationId = MainSettings.GoogleRegId,
Model = devinfo.Model, Model = devinfo.Model,
Platform = devinfo.Platform.ToString(), Platform = devinfo.Platform.ToString(),
Version = devinfo.Version, Version = devinfo.Version
GCMRegistrationId = MainSettings.GoogleRegId
}; };
} }
public void PostDeviceInfo() public TAnswer InvokeApi<TAnswer>(string method, object arg)
{
using (var m =
new SimpleJsonPostMethod(method,
MainSettings.CurrentUser.YavscTokens.AccessToken
))
{ {
throw new NotImplementedException(); return m.Invoke<TAnswer>(arg);
}
}
public object InvokeApi(string method, object arg)
{
using (var m =
new SimpleJsonPostMethod(method,
MainSettings.CurrentUser.YavscTokens.AccessToken
))
{
return m.InvokeJson(arg);
}
} }
} }
} }

@ -8,11 +8,12 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xamarin.Forms; using Xamarin.Forms;
using Xamarin.Forms.Xaml; using Xamarin.Forms.Xaml;
using Yavsc.Helpers;
/* /*
Glyphish icons from Glyphish icons from
http://www.glyphish.com/ http://www.glyphish.com/
under under
http://creativecommons.org/licenses/by/3.0/us/ http://creativecommons.org/licenses/by/3.0/us/
support them by buying the full set / Retina versions support them by buying the full set / Retina versions
*/ */
@ -82,35 +83,12 @@ namespace BookAStar
else deviceInfoPage.Focus(); else deviceInfoPage.Focus();
} }
public async void RegisterThisDevice() public async Task PostDeviceInfo()
{ {
HttpClient client = new HttpClient(); var res = PlateformSpecificInstance.InvokeApi(
// var request = new HttpRequestMessage(HttpMethod.Post, MainSettings.MobileRegistrationUrl); "gcm/register", PlateformSpecificInstance.GetDeviceInfo());
// request.Headers.Authorization
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", MainSettings.CurrentUser.YavscTokens.AccessToken);
/* client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
);*/
var info =PlateformSpecificInstance.GetDeviceInfo();
/* var serSettings = new JsonSerializerSettings(); serSettings.Formatting = Formatting.None; serSettings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;*/
client.MaxResponseContentBufferSize = 256000;
using ( client)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(info);
/*
var dataString = JsonConvert.SerializeObject(info,serSettings); */
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(MainSettings.MobileRegistrationUrl, content);
if (response.IsSuccessStatusCode)
Debug.WriteLine(@"Device info successfully saved.");
}
} }
} }
} }

@ -126,16 +126,14 @@
<Folder Include="Model\Workflow\" /> <Folder Include="Model\Workflow\" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Json.NET.Web, Version=1.0.49.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="Json.NET.Web">
<HintPath>..\..\packages\Json.NET.Web.1.0.49\lib\portable45-net45+win8+wpa81\Json.NET.Web.dll</HintPath> <HintPath>..\..\packages\Json.NET.Web.1.0.49\lib\portable45-net45+win8+wpa81\Json.NET.Web.dll</HintPath>
<Private>True</Private>
</Reference> </Reference>
<Reference Include="Mono.Android"> <Reference Include="Mono.Android">
<HintPath>..\..\..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\MonoAndroid\v6.0\Mono.Android.dll</HintPath> <HintPath>..\..\..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\MonoAndroid\v6.0\Mono.Android.dll</HintPath>
</Reference> </Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <Reference Include="Newtonsoft.Json">
<HintPath>..\..\packages\Newtonsoft.Json.9.0.1\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.Json.dll</HintPath> <HintPath>..\..\packages\Newtonsoft.Json.9.0.1\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference> </Reference>
<Reference Include="Plugin.Settings, Version=2.1.0.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="Plugin.Settings, Version=2.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\Xam.Plugins.Settings.2.1.0\lib\portable-net45+wp8+wpa81+win8+MonoAndroid10+MonoTouch10+Xamarin.iOS10+UAP10\Plugin.Settings.dll</HintPath> <HintPath>..\..\packages\Xam.Plugins.Settings.2.1.0\lib\portable-net45+wp8+wpa81+win8+MonoAndroid10+MonoTouch10+Xamarin.iOS10+UAP10\Plugin.Settings.dll</HintPath>
@ -162,6 +160,12 @@
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Yavsc.Client\Yavsc.Client.csproj">
<Project>{67F9D3A8-F71E-4428-913F-C37AE82CDB24}</Project>
<Name>Yavsc.Client</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<Import Project="..\..\packages\Xamarin.Forms.2.3.0.107\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets" Condition="Exists('..\..\packages\Xamarin.Forms.2.3.0.107\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets')" /> <Import Project="..\..\packages\Xamarin.Forms.2.3.0.107\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets" Condition="Exists('..\..\packages\Xamarin.Forms.2.3.0.107\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">

@ -5,12 +5,13 @@ using System.Linq;
using System.Text; using System.Text;
using Xamarin.Forms; using Xamarin.Forms;
using Yavsc.Models.Identity;
namespace BookAStar namespace BookAStar
{ {
public class DeviceInfoPage : ContentPage public class DeviceInfoPage : ContentPage
{ {
public DeviceInfoPage(GoogleCloudMobileDeclaration infos) public DeviceInfoPage(IGCMDeclaration infos)
{ {
Content = new StackLayout Content = new StackLayout
{ {

@ -6,7 +6,7 @@ using Plugin.Settings.Abstractions;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms; using Xamarin.Forms;
namespace BookAStar namespace BookAStar
@ -76,7 +76,12 @@ namespace BookAStar
AppSettings.AddOrUpdateValue<string>(GoogleRegIdKey, value); AppSettings.AddOrUpdateValue<string>(GoogleRegIdKey, value);
// TODO If it changed, and there's an identified user, // TODO If it changed, and there's an identified user,
// Inform the server of it. // Inform the server of it.
if (oldregid != value) App.CurrentApp.RegisterThisDevice(); if (oldregid != value)
{
Task.Run( async () => {
await App.CurrentApp.PostDeviceInfo();
});
}
} }
get { return AppSettings.GetValueOrDefault<string>(GoogleRegIdKey); } get { return AppSettings.GetValueOrDefault<string>(GoogleRegIdKey); }
} }
@ -126,7 +131,9 @@ namespace BookAStar
{ {
if (olduserid != value.Id) if (olduserid != value.Id)
{ {
App.CurrentApp.RegisterThisDevice(); Task.Run(async () => {
await App.CurrentApp.PostDeviceInfo();
});
} }
} }
} }

@ -1,4 +1,5 @@
using BookAStar.Model.Auth.Account; using BookAStar.Model.Auth.Account;
using Yavsc.Models.Identity;
namespace BookAStar namespace BookAStar
{ {
@ -16,10 +17,11 @@ namespace BookAStar
void RevokeAccount(string userName); void RevokeAccount(string userName);
GoogleCloudMobileDeclaration GetDeviceInfo(); IGCMDeclaration GetDeviceInfo();
void PostDeviceInfo(); TAnswer InvokeApi<TAnswer>(string method, object arg);
object InvokeApi(string method, object arg);
} }
} }

@ -1,12 +1,36 @@
using System;
using Yavsc.Models;
using Yavsc.Models.Identity;
namespace BookAStar.Model.Auth.Account namespace BookAStar.Model.Auth.Account
{ {
public class GoogleCloudMobileDeclaration public class GoogleCloudMobileDeclaration : IGoogleCloudMobileDeclaration
{ {
public string GCMRegistrationId { get; set; } public string GCMRegistrationId { get; set; }
public string DeviceId { get; set; } public string DeviceId { get; set; }
public string Model { get; set; } public string Model { get; set; }
public string Platform { get; set; } public string Platform { get; set; }
public string Version { get; set; } public string Version { get; set; }
public IApplicationUser DeviceOwner
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string DeviceOwnerId
{
get;
set;
}
} }
} }

@ -0,0 +1,128 @@
//
// PostJson.cs
//
// Author:
// Paul Schneider <paulschneider@free.fr>
//
// Copyright (c) 2015 Paul Schneider
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Net;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
namespace Yavsc.Helpers
{
/// <summary>
/// Simple json post method.
/// </summary>
public class NotSoSimpleJsonPostMethod : IDisposable
{
private HttpWebRequest request = null;
/// <summary>
/// Initializes a new instance of the Yavsc.Helpers.SimpleJsonPostMethod class.
/// </summary>
/// <param name="pathToMethod">Path to method.</param>
public NotSoSimpleJsonPostMethod(string pathToMethod, string authorizationHeader = null)
{
request = (HttpWebRequest)WebRequest.Create(pathToMethod);
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
// request.SendChunked = true;
// request.TransferEncoding = "UTF-8";
request.Headers = new WebHeaderCollection();
if (authorizationHeader != null)
request.Headers["Authorization"] = "Bearer " + authorizationHeader;
}
public void Dispose()
{
request.Abort();
}
/// <summary>
/// Invoke the specified query.
/// </summary>
/// <param name="query">Query.</param>
public async Task<TAnswer> Invoke<TAnswer>(object query)
{
using (Stream streamQuery = await request.GetRequestStreamAsync())
{
using (StreamWriter writer = new StreamWriter(streamQuery))
{
writer.Write(JsonConvert.SerializeObject(query));
}
}
TAnswer ans = default(TAnswer);
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader rdr = new StreamReader(responseStream))
{
ans = (TAnswer)JsonConvert.DeserializeObject<TAnswer>(rdr.ReadToEnd());
}
}
}
return ans;
}
public async Task<object> InvokeAnonymous(object query)
{
object result = null;
using (Stream streamQuery = await request.GetRequestStreamAsync())
{
using (StreamWriter writer = new StreamWriter(streamQuery))
{
var json = JsonConvert.SerializeObject(query);
writer.Write(json);
}
}
try
{
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
if (stream.Length > 0)
{
using (var sr = new StreamReader(stream))
{
var json = await sr.ReadToEndAsync();
result = JsonConvert.DeserializeObject(json);
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message.ToString());
}
return result;
}
}
}

@ -1,13 +1,18 @@
namespace Yavsc.Models.Identity namespace Yavsc.Models.Identity
{ {
public interface IGoogleCloudMobileDeclaration public interface IGCMDeclaration
{ {
string DeviceId { get; set; } string DeviceId { get; set; }
IApplicationUser DeviceOwner { get; set; }
string DeviceOwnerId { get; set; }
string GCMRegistrationId { get; set; } string GCMRegistrationId { get; set; }
string Model { get; set; } string Model { get; set; }
string Platform { get; set; } string Platform { get; set; }
string Version { get; set; } string Version { get; set; }
}
public interface IGoogleCloudMobileDeclaration: IGCMDeclaration
{
IApplicationUser DeviceOwner { get; set; }
string DeviceOwnerId { get; set; }
} }
} }

@ -35,6 +35,7 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Helpers\SimpleJsonPostMethod.cs" />
<Compile Include="IAccountBalance.cs" /> <Compile Include="IAccountBalance.cs" />
<Compile Include="IApplicationUser.cs" /> <Compile Include="IApplicationUser.cs" />
<Compile Include="IBlog.cs" /> <Compile Include="IBlog.cs" />
@ -47,7 +48,19 @@
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" /> <None Include="packages.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<Reference Include="Json.NET.Web, Version=1.0.49.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Json.NET.Web.1.0.49\lib\portable45-net45+win8+wpa81\Json.NET.Web.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.8.0.3\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<Import Project="..\packages\Xamarin.Forms.2.0.0.6482\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets" Condition="Exists('..\packages\Xamarin.Forms.2.0.0.6482\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets')" /> <Import Project="..\packages\Xamarin.Forms.2.0.0.6482\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets" Condition="Exists('..\packages\Xamarin.Forms.2.0.0.6482\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets')" />

@ -1,3 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="Json.NET.Web" version="1.0.49" targetFramework="portable45-net45+win8+wpa81" />
<package id="Newtonsoft.Json" version="8.0.3" targetFramework="portable45-net45+win8+wpa81" />
</packages> </packages>

@ -0,0 +1,10 @@
{
"version": "1.0.0-*",
"frameworks": {
"net45+win+wpa81+MonoAndroid10+Xamarin.iOS10+MonoTouch10": {
"bin": {
"assembly": "../../../../../../../Program Files (x86)/Reference Assemblies/Microsoft/Framework/MonoAndroid/v1.0/mscorlib.dll"
}
}
}
}
Loading…