This commit is contained in:
29
Yavsc/Helpers/AuthHelpers.cs
Normal file
29
Yavsc/Helpers/AuthHelpers.cs
Normal file
@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Http.Authentication;
|
||||
|
||||
namespace Yavsc.Extensions {
|
||||
public static class HttpContextExtensions {
|
||||
public static IEnumerable<AuthenticationDescription> GetExternalProviders(this HttpContext context) {
|
||||
if (context == null) {
|
||||
throw new ArgumentNullException(nameof(context));
|
||||
}
|
||||
|
||||
return from description in context.Authentication.GetAuthenticationSchemes()
|
||||
where !string.IsNullOrEmpty(description.DisplayName)
|
||||
select description;
|
||||
}
|
||||
|
||||
public static bool IsProviderSupported(this HttpContext context, string provider) {
|
||||
if (context == null) {
|
||||
throw new ArgumentNullException(nameof(context));
|
||||
}
|
||||
|
||||
return (from description in context.GetExternalProviders()
|
||||
where string.Equals(description.AuthenticationScheme, provider, StringComparison.OrdinalIgnoreCase)
|
||||
select description).Any();
|
||||
}
|
||||
}
|
||||
}
|
21
Yavsc/Helpers/CompanyInfoHelpers.cs
Normal file
21
Yavsc/Helpers/CompanyInfoHelpers.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Yavsc.Model.societe.com;
|
||||
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
public static class ComapnyInfoHelpers {
|
||||
public static async Task<CompanyInfoMessage> CheckSiren(this HttpClient web,
|
||||
string siren, CompanyInfoSettings api)
|
||||
{
|
||||
using (var request = new HttpRequestMessage(HttpMethod.Get,
|
||||
string.Format(Constants.CompanyInfoUrl,siren,api.ApiKey))) {
|
||||
using (var response = await web.SendAsync(request)) {
|
||||
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
|
||||
return payload.ToObject<CompanyInfoMessage>();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
24
Yavsc/Helpers/EventHelpers.cs
Normal file
24
Yavsc/Helpers/EventHelpers.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Yavsc.Models.Booking;
|
||||
using Yavsc.Models.Messaging;
|
||||
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
public static class EventHelpers
|
||||
{
|
||||
public static YaEvent CreateEvent(this BookQuery query,
|
||||
IStringLocalizer SR)
|
||||
{
|
||||
var yaev = new YaEvent
|
||||
{
|
||||
Title = query.Client.UserName + SR["is asking you for a date"],
|
||||
Comment = (query.Previsional != null) ?
|
||||
SR["Deposit"] + string.Format(": {0:00}",
|
||||
query.Previsional) : SR["No deposit."],
|
||||
Description = SR["Address"] + ": " + query.Location.Address + "\n" +
|
||||
SR["Date"] + ": " + query.EventDate.ToString("D")
|
||||
};
|
||||
return yaev;
|
||||
}
|
||||
}
|
||||
}
|
23
Yavsc/Helpers/FileSystemHelpers.cs
Normal file
23
Yavsc/Helpers/FileSystemHelpers.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using System.IO;
|
||||
using Microsoft.AspNet.FileProviders;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
public static class FileSystemHelpers {
|
||||
public static IDirectoryContents GetFileContent(this Estimate estimate, string userFileDir)
|
||||
{
|
||||
if (estimate?.Command?.PerformerProfile?.Performer == null)
|
||||
return null;
|
||||
var fsp = new PhysicalFileProvider(
|
||||
Path.Combine(
|
||||
userFileDir,
|
||||
estimate.Command.PerformerProfile.Performer.UserName
|
||||
));
|
||||
return fsp.GetDirectoryContents(
|
||||
Path.Combine(Constants.UserBillsFilesDir, estimate.Id.ToString())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
101
Yavsc/Helpers/GoogleHelpers.cs
Normal file
101
Yavsc/Helpers/GoogleHelpers.cs
Normal file
@ -0,0 +1,101 @@
|
||||
//
|
||||
// GoogleHelpers.cs
|
||||
//
|
||||
// Author:
|
||||
// Paul Schneider <paul@pschneider.fr>
|
||||
//
|
||||
// Copyright (c) 2015 GNU GPL
|
||||
//
|
||||
// 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;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Auth;
|
||||
using Yavsc.Models.Google.Messaging;
|
||||
using Yavsc.Models.Messaging;
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Google helpers.
|
||||
/// </summary>
|
||||
public static class GoogleHelpers
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Notifies the event.
|
||||
/// </summary>
|
||||
/// <returns>The event.</returns>
|
||||
/// <param name="evpub">Evpub.</param>
|
||||
public static async Task<MessageWithPayloadResponse> NotifyEvent
|
||||
(this HttpClient channel, GoogleAuthSettings googleSettings, CircleEvent evpub) {
|
||||
// ASSERT ModelState.IsValid implies evpub.Circles != null
|
||||
//send a MessageWithPayload<YaEvent> to circle members
|
||||
// receive MessageWithPayloadResponse
|
||||
// "https://gcm-http.googleapis.com/gcm/send"
|
||||
|
||||
var regids = new List<string> ();
|
||||
foreach (var c in evpub.Circles)
|
||||
foreach (var u in c.Members) {
|
||||
regids.AddRange (u.Member.Devices.Select(d=>d.RegistrationId));
|
||||
}
|
||||
if (regids.Count>0) return null;
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, Constants.GCMNotificationUrl);
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Key", googleSettings.ApiKey);
|
||||
var msg = new MessageWithPayload<YaEvent> () {
|
||||
notification = new Notification() { title = evpub.Title, body = evpub.Description, icon = "event" },
|
||||
data = evpub , registration_ids = regids.ToArray() };
|
||||
var response = await channel.SendAsync(request);
|
||||
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
|
||||
return payload.Value<MessageWithPayloadResponse>();
|
||||
}
|
||||
|
||||
public static async Task<MessageWithPayloadResponse> NotifyEvent<Event>
|
||||
(this HttpClient channel, GoogleAuthSettings googleSettings, IEnumerable<string> regids, Event ev)
|
||||
where Event : YaEvent
|
||||
{
|
||||
if (regids == null)
|
||||
throw new NotImplementedException ("Notify & No GCM reg ids");
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, Constants.GCMNotificationUrl);
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Key", googleSettings.ApiKey);
|
||||
var msg = new MessageWithPayload<Event> () {
|
||||
notification = new Notification() { title = ev.Title,
|
||||
body = ev.Description + ev.Comment==null?
|
||||
"":"("+ev.Comment+")", icon = "icon" },
|
||||
data = ev, registration_ids = regids.ToArray() };
|
||||
|
||||
var response = await channel.SendAsync(request);
|
||||
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
|
||||
return payload.Value<MessageWithPayloadResponse>();
|
||||
}
|
||||
public static async Task<UserCredential> GetCredentialForGoogleApiAsync(this UserManager<ApplicationUser> userManager, ApplicationDbContext context, string uid)
|
||||
{
|
||||
var user = await userManager.FindByIdAsync(uid);
|
||||
var googleId = context.UserLogins.FirstOrDefault(
|
||||
x => x.UserId == uid
|
||||
).ProviderKey;
|
||||
if (string.IsNullOrEmpty(googleId))
|
||||
throw new InvalidOperationException("No Google login");
|
||||
var token = await context.GetTokensAsync(googleId);
|
||||
return new UserCredential(uid, token);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
28
Yavsc/Helpers/ListItemHelpers.cs
Normal file
28
Yavsc/Helpers/ListItemHelpers.cs
Normal file
@ -0,0 +1,28 @@
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Mvc.Rendering;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc {
|
||||
public static class ListItemHelpers {
|
||||
|
||||
public static List<SelectListItem> ActivityItems(
|
||||
this ApplicationDbContext _dbContext, string selectedCode)
|
||||
{
|
||||
var codeIsNull = (string.IsNullOrEmpty(selectedCode));
|
||||
List<SelectListItem> items;
|
||||
if (codeIsNull) items = _dbContext.Activities.Select(
|
||||
x=> new SelectListItem() {
|
||||
Value=x.Code, Text=x.Name
|
||||
} ).ToList();
|
||||
else items =
|
||||
_dbContext.Activities.Select(
|
||||
x=> new SelectListItem() {
|
||||
Value=x.Code, Text=x.Name,
|
||||
Selected = (x.Code == selectedCode)
|
||||
} ).ToList();
|
||||
return items;
|
||||
}
|
||||
}
|
||||
}
|
106
Yavsc/Helpers/SimpleJsonPostMethod.cs
Normal file
106
Yavsc/Helpers/SimpleJsonPostMethod.cs
Normal file
@ -0,0 +1,106 @@
|
||||
//
|
||||
// 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;
|
||||
using System.Net;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Yavsc.Model
|
||||
{
|
||||
/// <summary>
|
||||
/// Simple json post method.
|
||||
/// </summary>
|
||||
public class SimpleJsonPostMethod<TQuery,TAnswer>: IDisposable
|
||||
{
|
||||
internal HttpWebRequest request = null;
|
||||
internal HttpWebRequest Request { get { return request; } }
|
||||
|
||||
string CharSet {
|
||||
get { return Request.TransferEncoding; }
|
||||
set { Request.TransferEncoding=value;}
|
||||
}
|
||||
string Method { get { return Request.Method; } }
|
||||
/// <summary>
|
||||
/// Gets the path.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public string Path {
|
||||
get{ return Request.RequestUri.ToString(); }
|
||||
}
|
||||
/// <summary>
|
||||
/// Sets the credential.
|
||||
/// </summary>
|
||||
/// <param name="cred">Cred.</param>
|
||||
public void SetCredential(string cred) {
|
||||
Request.Headers.Set(HttpRequestHeader.Authorization,cred);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the Yavsc.Helpers.SimpleJsonPostMethod class.
|
||||
/// </summary>
|
||||
/// <param name="pathToMethod">Path to method.</param>
|
||||
public SimpleJsonPostMethod (string pathToMethod)
|
||||
{
|
||||
// ASSERT Request == null
|
||||
request = (HttpWebRequest) WebRequest.Create (pathToMethod);
|
||||
|
||||
Request.Method = "POST";
|
||||
Request.Accept = "application/json";
|
||||
Request.ContentType = "application/json";
|
||||
Request.SendChunked = true;
|
||||
Request.TransferEncoding = "UTF-8";
|
||||
}
|
||||
/// <summary>
|
||||
/// Invoke the specified query.
|
||||
/// </summary>
|
||||
/// <param name="query">Query.</param>
|
||||
public TAnswer Invoke(TQuery 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;
|
||||
}
|
||||
|
||||
#region IDisposable implementation
|
||||
|
||||
/// <summary>
|
||||
/// Releases all resource used by the Yavsc.Helpers.SimpleJsonPostMethod object.
|
||||
/// </summary>
|
||||
public void Dispose ()
|
||||
{
|
||||
if (Request != null) Request.Abort ();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
126
Yavsc/Helpers/TagHelpers.cs
Normal file
126
Yavsc/Helpers/TagHelpers.cs
Normal file
@ -0,0 +1,126 @@
|
||||
|
||||
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using MarkdownDeep;
|
||||
using Microsoft.AspNet.Mvc.Rendering;
|
||||
using Microsoft.AspNet.Razor.TagHelpers;
|
||||
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
[HtmlTargetElement("div", Attributes = MarkdownContentAttributeName)]
|
||||
[HtmlTargetElement("p", Attributes = "ismarkdown")]
|
||||
[HtmlTargetElement("markdown")]
|
||||
[OutputElementHint("p")]
|
||||
public class MarkdownTagHelper : TagHelper
|
||||
{
|
||||
private const string MarkdownContentAttributeName = "markdown";
|
||||
private const string MarkdownMarkAttributeName = "ismarkdown";
|
||||
|
||||
[HtmlAttributeName("site")]
|
||||
public SiteSettings Site { get; set; }
|
||||
|
||||
[HtmlAttributeName("base")]
|
||||
public string Base { get; set; }
|
||||
|
||||
[HtmlAttributeName(MarkdownContentAttributeName)]
|
||||
public string MarkdownContent { get; set; }
|
||||
|
||||
static Regex rxExtractLanguage = new Regex("^({{(.+)}}[\r\n])", RegexOptions.Compiled);
|
||||
private static string FormatCodePrettyPrint(MarkdownDeep.Markdown m, string code)
|
||||
{
|
||||
// Try to extract the language from the first line
|
||||
var match = rxExtractLanguage.Match(code);
|
||||
string language = null;
|
||||
|
||||
if (match.Success)
|
||||
{
|
||||
// Save the language
|
||||
var g = (Group)match.Groups[2];
|
||||
language = g.ToString();
|
||||
|
||||
// Remove the first line
|
||||
code = code.Substring(match.Groups[1].Length);
|
||||
}
|
||||
|
||||
// If not specified, look for a link definition called "default_syntax" and
|
||||
// grab the language from its title
|
||||
if (language == null)
|
||||
{
|
||||
var d = m.GetLinkDefinition("default_syntax");
|
||||
if (d != null)
|
||||
language = d.title;
|
||||
}
|
||||
|
||||
// Common replacements
|
||||
if (language == "C#")
|
||||
language = "csharp";
|
||||
if (language == "C++")
|
||||
language = "cpp";
|
||||
|
||||
// Wrap code in pre/code tags and add PrettyPrint attributes if necessary
|
||||
if (string.IsNullOrEmpty(language))
|
||||
return string.Format("<pre><code>{0}</code></pre>\n", code);
|
||||
else
|
||||
return string.Format("<pre class=\"prettyprint lang-{0}\"><code>{1}</code></pre>\n",
|
||||
language.ToLowerInvariant(), code);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Transforms a string of Markdown into HTML.
|
||||
/// </summary>
|
||||
/// <param name="helper">HtmlHelper - Not used, but required to make this an extension method.</param>
|
||||
/// <param name="text">The Markdown that should be transformed.</param>
|
||||
/// <param name="urlBaseLocation">The url Base Location.</param>
|
||||
/// <returns>The HTML representation of the supplied Markdown.</returns>
|
||||
public string Markdown(string text, string urlBaseLocation = "")
|
||||
{
|
||||
// Transform the supplied text (Markdown) into HTML.
|
||||
var markdownTransformer = GetMarkdownTransformer();
|
||||
markdownTransformer.UrlBaseLocation = urlBaseLocation;
|
||||
string html = markdownTransformer.Transform(text);
|
||||
// Wrap the html in an MvcHtmlString otherwise it'll be HtmlEncoded and displayed to the user as HTML :(
|
||||
return html;
|
||||
}
|
||||
|
||||
internal Markdown GetMarkdownTransformer()
|
||||
{
|
||||
var markdownTransformer = new Markdown();
|
||||
markdownTransformer.ExtraMode = true;
|
||||
markdownTransformer.NoFollowLinks = true;
|
||||
markdownTransformer.SafeMode = false;
|
||||
markdownTransformer.FormatCodeBlock = FormatCodePrettyPrint;
|
||||
markdownTransformer.ExtractHeadBlocks = true;
|
||||
markdownTransformer.UserBreaks = true;
|
||||
return markdownTransformer;
|
||||
}
|
||||
|
||||
public ModelExpression Content { get; set; }
|
||||
public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
|
||||
{
|
||||
if (output.TagName == "markdown")
|
||||
{
|
||||
output.TagName = null;
|
||||
}
|
||||
output.Attributes.RemoveAll("markdown");
|
||||
|
||||
var content = await GetContent(output);
|
||||
var markdown = content;
|
||||
var basePath = Base?.StartsWith("~") ?? false ?
|
||||
Constants.UserFilesDir +
|
||||
Base.Substring(1) : Base;
|
||||
var html = Markdown(markdown, basePath);
|
||||
output.Content.SetHtmlContent(html ?? "");
|
||||
}
|
||||
private async Task<string> GetContent(TagHelperOutput output)
|
||||
{
|
||||
if (MarkdownContent != null)
|
||||
return MarkdownContent;
|
||||
if (Content != null)
|
||||
return Content.Model?.ToString();
|
||||
return (await output.GetChildContentAsync(false)).GetContent();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user