Merge from booking branch

This commit is contained in:
Paul Schneider 2015-11-17 22:22:59 +01:00
commit 9a2652739b
266 changed files with 12833 additions and 2337 deletions

View file

@ -0,0 +1,116 @@
//
// AccountController.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.Web.Http;
using System.Net.Http;
using Yavsc.Model.RolesAndMembers;
using System.Web.Security;
using System.Web.Profile;
using Yavsc.Helpers;
using System.Collections.Specialized;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Account controller.
/// </summary>
public class AccountController : YavscController
{
/// <summary>
/// Register the specified model.
/// </summary>
/// <param name="model">Model.</param>
[Authorize ()]
[ValidateAjaxAttribute]
public HttpResponseMessage Register ([FromBody] RegisterClientModel model)
{
if (ModelState.IsValid) {
if (model.IsApprouved)
if (!Roles.IsUserInRole ("Admin"))
if (!Roles.IsUserInRole ("FrontOffice")) {
ModelState.AddModelError ("Register",
"Since you're not member of Admin or FrontOffice groups, " +
"you cannot ask for a pre-approuved registration");
return DefaultResponse ();
}
MembershipCreateStatus mcs;
var user = Membership.CreateUser (
model.UserName,
model.Password,
model.Email,
model.Question,
model.Answer,
model.IsApprouved,
out mcs);
switch (mcs) {
case MembershipCreateStatus.DuplicateEmail:
ModelState.AddModelError ("Email", "Cette adresse e-mail correspond " +
"à un compte utilisateur existant");
break;
case MembershipCreateStatus.DuplicateUserName:
ModelState.AddModelError ("UserName", "Ce nom d'utilisateur est " +
"déjà enregistré");
break;
case MembershipCreateStatus.Success:
if (!model.IsApprouved)
Url.SendActivationMessage (user);
ProfileBase prtu = ProfileBase.Create (model.UserName);
prtu.SetPropertyValue ("Name", model.Name);
prtu.SetPropertyValue ("Address", model.Address);
prtu.SetPropertyValue ("CityAndState", model.CityAndState);
prtu.SetPropertyValue ("Mobile", model.Mobile);
prtu.SetPropertyValue ("Phone", model.Phone);
prtu.SetPropertyValue ("ZipCode", model.ZipCode);
break;
default:
break;
}
}
return DefaultResponse ();
}
/// <summary>
/// Resets the password.
/// </summary>
/// <param name="model">Model.</param>
[ValidateAjax]
public void ResetPassword (LostPasswordModel model)
{
StringDictionary errors;
MembershipUser user;
YavscHelpers.ValidatePasswordReset (model, out errors, out user);
foreach (string key in errors.Keys)
ModelState.AddModelError (key, errors [key]);
if (user != null && ModelState.IsValid)
Url.SendActivationMessage (user);
}
[ValidateAjax]
[Authorize(Roles="Admin")]
public void AddUserToRole(UserRole model)
{
Roles.AddUserToRole (model.UserName, model.Role);
}
}
}

View file

@ -0,0 +1,55 @@
//
// AuthorizationDenied.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.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Profile;
using System.Web.Security;
using Yavsc.Formatters;
using Yavsc.Helpers;
using Yavsc.Model;
using Yavsc.Model.FrontOffice;
using Yavsc.Model.RolesAndMembers;
using Yavsc.Model.WorkFlow;
using System.IO;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Authorization denied.
/// </summary>
public class AuthorizationDenied : HttpRequestException {
/// <summary>
/// Initializes a new instance of the Yavsc.ApiControllers.AuthorizationDenied class.
/// </summary>
/// <param name="msg">Message.</param>
public AuthorizationDenied(string msg) : base(msg)
{
}
}
}

View file

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Http;
using Yavsc.Model.WorkFlow;
using System.Collections.Specialized;
using Yavsc.Model.FrontOffice;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Basket controller.
/// Maintains a collection of articles
/// qualified with name value pairs
/// </summary>
public class BasketController : ApiController
{
/// <summary>
/// The wfmgr.
/// </summary>
protected WorkFlowManager wfmgr = null;
/// <summary>
/// Initialize the specified controllerContext.
/// </summary>
/// <param name="controllerContext">Controller context.</param>
protected override void Initialize (System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize (controllerContext);
wfmgr = new WorkFlowManager ();
}
/// <summary>
/// Gets the current basket, creates a new one, if it doesn't exist.
/// </summary>
/// <value>The current basket.</value>
protected CommandSet CurrentBasket {
get {
CommandSet b = wfmgr.GetCommands (Membership.GetUser ().UserName);
if (b == null) b = new CommandSet ();
return b;
}
}
/// <summary>
/// Create the specified basket item using specified command parameters.
/// </summary>
/// <param name="cmdParams">Command parameters.</param>
[Authorize]
public long Create(NameValueCollection cmdParams)
{
// HttpContext.Current.Request.Files
Command cmd = new Command(cmdParams, HttpContext.Current.Request.Files);
CurrentBasket.Add (cmd);
return cmd.Id;
}
/// <summary>
/// Read the specified basket item.
/// </summary>
/// <param name="itemid">Itemid.</param>
[Authorize]
Command Read(long itemid){
return CurrentBasket[itemid];
}
/// <summary>
/// Update the specified item parameter using the specified value.
/// </summary>
/// <param name="itemid">Item identifier.</param>
/// <param name="param">Parameter name.</param>
/// <param name="value">Value.</param>
[Authorize]
public void UpdateParam(long itemid, string param, string value)
{
CurrentBasket [itemid].Parameters [param] = value;
}
/// <summary>
/// Delete the specified item.
/// </summary>
/// <param name="itemid">Item identifier.</param>
[Authorize]
public void Delete(long itemid)
{
CurrentBasket.Remove (itemid);
}
}
}

View file

@ -0,0 +1,256 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Http;
using Npgsql.Web.Blog;
using Yavsc.Model.Blogs;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Diagnostics;
using Yavsc.Formatters;
using Yavsc.Model;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Blogs API controller.
/// </summary>
public class BlogsController : YavscController
{
/// <summary>
/// Tag the specified model.
/// </summary>
/// <param name="model">Model.</param>
[Authorize,
AcceptVerbs ("POST")]
public void Tag (PostTag model) {
if (ModelState.IsValid) {
BlogManager.GetForEditing (model.PostId);
BlogManager.Tag (model.PostId, model.Tag);
}
}
static string [] officalTags = new string[] { "Artistes", "Accueil", "Événements", "Mentions légales", "Admin", "Web" } ;
/// <summary>
/// Tags the specified pattern.
/// </summary>
/// <param name="pattern">Pattern.</param>
[ValidateAjaxAttribute]
public IEnumerable<string> Tags(string pattern)
{
return officalTags;
}
/// <summary>
/// Untag the specified model.
/// </summary>
/// <param name="model">Model.</param>
[Authorize,
AcceptVerbs ("POST")]
public void Untag (PostTag model) {
if (ModelState.IsValid) {
BlogManager.GetForEditing (model.PostId);
BlogManager.Untag (model.PostId, model.Tag);
}
}
/// <summary>
/// Removes the post.
/// </summary>
/// <param name="user">User.</param>
/// <param name="title">Title.</param>
[Authorize, ValidateAjaxAttribute, HttpPost]
public void RemoveTitle(string user, string title) {
if (Membership.GetUser ().UserName != user)
if (!Roles.IsUserInRole("Admin"))
throw new AuthorizationDenied (user);
BlogManager.RemoveTitle (user, title);
}
/// <summary>
/// Removes the tag.
/// </summary>
/// <param name="tagid">Tagid.</param>
[Authorize, ValidateAjaxAttribute, HttpPost]
public void RemoveTag([FromBody] long tagid) {
throw new NotImplementedException ();
}
/// <summary>
/// The allowed media types.
/// </summary>
protected string[] allowedMediaTypes = {
"text/plain",
"text/x-tex",
"text/html",
"image/png",
"image/gif",
"image/jpeg",
"image/x-xcf",
"application/pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
};
/// <summary>
/// Posts the file.
/// </summary>
/// <returns>The file.</returns>
[Authorize, HttpPost]
public async Task<HttpResponseMessage> PostFile(long id) {
if (!(Request.Content.Headers.ContentType.MediaType=="multipart/form-data"))
throw new HttpRequestException ("not a multipart/form-data request");
BlogEntry be = BlogManager.GetPost (id);
if (be.Author != Membership.GetUser ().UserName)
throw new AuthorizationDenied ("b"+id);
string root = HttpContext.Current.Server.MapPath("~/bfiles/"+id);
DirectoryInfo di = new DirectoryInfo (root);
if (!di.Exists) di.Create ();
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider) ;
var invalidChars = Path.GetInvalidFileNameChars();
foreach (var f in provider.FileData) {
string filename = f.LocalFileName;
string orgname = f.Headers.ContentDisposition.FileName;
Trace.WriteLine(filename);
string nicename = HttpUtility.UrlDecode(orgname) ;
if (orgname.StartsWith("\"") && orgname.EndsWith("\"") && orgname.Length > 2)
nicename = orgname.Substring(1,orgname.Length-2);
nicename = new string (nicename.Where( x=> !invalidChars.Contains(x)).ToArray());
nicename = nicename.Replace(' ','_');
var dest = Path.Combine(root,nicename);
var fi = new FileInfo(dest);
if (fi.Exists) fi.Delete();
File.Move(filename, fi.FullName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
/// <summary>
/// Create the specified blog entry.
/// </summary>
/// <param name="bp">Bp.</param>
[Authorize, HttpPost]
public long Create (BasePost bp)
{
return BlogManager.Post (User.Identity.Name, bp.Title, "", bp.Visible, null);
}
[Authorize, HttpPost]
public void Note (long id, int note)
{
if (note < 0 || note > 100)
throw new ArgumentException ("0<=note<=100");
BlogManager.Note (id, note);
}
/// <summary>
/// Searchs the file.
/// </summary>
/// <returns>The file.</returns>
/// <param name="id">Postid.</param>
/// <param name="terms">Terms.</param>
[HttpGet]
public async Task<HttpResponseMessage> SearchFile(long id, string terms) {
throw new NotImplementedException ();
}
/// <summary>
/// Sets the photo.
/// </summary>
/// <param name="id">Identifier.</param>
/// <param name="photo">Photo.</param>
[Authorize, HttpPost, ValidateAjaxAttribute]
public void SetPhoto(long id, [FromBody] string photo)
{
BlogManager.Provider.UpdatePostPhoto (id, photo);
}
/// <summary>
/// Import the specified id.
/// </summary>
/// <param name="id">Identifier.</param>
[Authorize, HttpPost, ValidateAjaxAttribute]
public async Task<HttpResponseMessage> Import(long id) {
if (!(Request.Content.Headers.ContentType.MediaType=="multipart/form-data"))
throw new HttpRequestException ("not a multipart/form-data request");
BlogEntry be = BlogManager.GetPost (id);
if (be.Author != Membership.GetUser ().UserName)
throw new AuthorizationDenied ("post: "+id);
string root = HttpContext.Current.Server.MapPath("~/bfiles/"+id);
DirectoryInfo di = new DirectoryInfo (root);
if (!di.Exists) di.Create ();
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
//IEnumerable<HttpContent> data =
await Request.Content.ReadAsMultipartAsync(provider) ;
var invalidChars = Path.GetInvalidFileNameChars();
List<string> bodies = new List<string>();
foreach (var f in provider.FileData) {
string filename = f.LocalFileName;
string nicename= f.Headers.ContentDisposition.FileName;
var filtered = new string (nicename.Where( x=> !invalidChars.Contains(x)).ToArray());
FileInfo fi = new FileInfo(filtered);
FileInfo fo = new FileInfo(filtered+".md");
FileInfo fp = new FileInfo (Path.Combine(root,filename));
if (fi.Exists) fi.Delete();
fp.MoveTo(fi.FullName);
// TODO Get the mime type
using (Process p = new Process ()) {
p.StartInfo.WorkingDirectory = root;
p.StartInfo = new ProcessStartInfo ();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "/usr/bin/pandoc";
p.StartInfo.Arguments =
string.Format (" -o '{0}' -t markdown '{1}'",
fo.FullName,
fi.FullName);
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start ();
p.WaitForExit ();
if (p.ExitCode != 0) {
return Request.CreateResponse (HttpStatusCode.InternalServerError,
"# Import failed with exit code: " + p.ExitCode + "---\n"
+ LocalizedText.ImportException + "---\n"
+ p.StandardError.ReadToEnd() + "---\n"
+ p.StandardOutput.ReadToEnd()
);
}
}
bodies.Add(fo.OpenText().ReadToEnd());
fi.Delete();
fo.Delete();
}
return Request.CreateResponse(HttpStatusCode.OK,string.Join("\n---\n",bodies),new SimpleFormatter("text/plain"));
}
catch (System.Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
}
}

View file

@ -0,0 +1,204 @@
//
// CalendarController.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.Web.Http;
using Yavsc.Model.RolesAndMembers;
using System.Web.Security;
using Yavsc.Model.Google;
using Yavsc.Helpers;
using System.Web.Profile;
using Yavsc.Model.Circles;
using Yavsc.Model.Calendar;
using System.Web.Http.Routing;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Night flash controller.
/// </summary>
public class CalendarController: ApiController
{
YaEvent[] getTestList()
{
return new YaEvent[] {
new YaEvent () {
Description = "Test Descr",
Title = "Night club special bubble party",
Location = new Position () {
Longitude = 0,
Latitude = 0
}
},
new YaEvent () {
Title = "Test2",
Photo = "http://bla/im.png",
Location = new Position () {
Longitude = 0,
Latitude = 0
}
},
new YaEvent () {
Description = "Test Descr",
Title = "Night club special bubble party",
Location = new Position () {
Longitude = 0,
Latitude = 0
}
},
new YaEvent () {
Title = "Test2",
Photo = "http://bla/im.png",
Location = new Position () {
Longitude = 0,
Latitude = 0
}
}
};
}
/// <summary>
/// List events according the specified search arguments.
/// </summary>
/// <param name="args">Arguments.</param>
[ValidateAjaxAttribute]
[HttpGet]
public YaEvent[] List ([FromUri] PositionAndKeyphrase args)
{
return getTestList();
}
/// <summary>
/// Provider the specified ProviderId.
/// </summary>
/// <param name="ProviderId">Provider identifier.</param>
[HttpGet]
public ProviderPublicInfo ProviderInfo ([FromUri] string ProviderId)
{
return new ProviderPublicInfo () {
DisplayName = "Yavsc clubing",
WebPage = "http://yavsc.pschneider.fr/",
Calendar = new Schedule () {
Period = Periodicity.ThreeM,
WeekDays = new OpenDay[] { new OpenDay () { Day = WeekDay.Saturday,
Start = new TimeSpan(18,00,00),
End = new TimeSpan(2,00,00)
} },
Validity = new Period[] { new Period() {
Start = new DateTime(2015,5,29),
End = new DateTime(2015,5,30)} }
},
Description = "Yavsc Entertainment Production, Yet another private party",
LogoImgLocator = "http://yavsc.pschneider.fr/favicon.png",
Location = new Position () { Longitude = 0, Latitude = 0 },
LocationType = "Salle des fêtes"
};
}
/// <summary>
/// Posts the image.
/// </summary>
/// <returns>The image.</returns>
/// <param name="NFProvId">NF prov identifier.</param>
public string PostImage([FromUri] string NFProvId)
{
return null;
}
/// <summary>
/// Posts the event.
/// </summary>
/// <returns>The event identifier.</returns>
/// <param name="ev">Ev.</param>
public int PostEvent ([FromBody] ProvidedEvent ev)
{
throw new NotImplementedException();
}
/// <summary>
/// Registers with push notifications enabled.
/// </summary>
/// <param name="model">Model.</param>
[ValidateAjax]
public void RegisterWithPushNotifications(GCMRegisterModel model)
{
if (ModelState.IsValid) {
MembershipCreateStatus mcs;
var user = Membership.CreateUser (
model.UserName,
model.Password,
model.Email,
null,
null,
false,
out mcs);
switch (mcs) {
case MembershipCreateStatus.DuplicateEmail:
ModelState.AddModelError ("Email", "Cette adresse e-mail correspond " +
"à un compte utilisateur existant");
break;
case MembershipCreateStatus.DuplicateUserName:
ModelState.AddModelError ("Author", "Ce nom d'utilisateur est " +
"déjà enregistré");
break;
case MembershipCreateStatus.Success:
Url.SendActivationMessage (user);
// TODO set registration id
throw new NotImplementedException ();
}
}
}
/// <summary>
/// Sets the registration identifier.
/// </summary>
/// <param name="registrationId">Registration identifier.</param>
[Authorize]
public void SetRegistrationId(string registrationId)
{
// TODO set registration id
setRegistrationId (Membership.GetUser ().UserName, registrationId);
}
private void setRegistrationId(string username, string regid) {
ProfileBase pr = ProfileBase.Create(username);
pr.SetPropertyValue ("gregid", regid);
}
/// <summary>
/// Notifies the event.
/// </summary>
/// <param name="evpub">Evpub.</param>
public MessageWithPayloadResponse NotifyEvent(EventPub evpub) {
SimpleJsonPostMethod<MessageWithPayload<YaEvent>,MessageWithPayloadResponse> r =
new SimpleJsonPostMethod<MessageWithPayload<YaEvent>,MessageWithPayloadResponse>(
"https://gcm-http.googleapis.com/gcm/send");
using (r) {
var msg = new MessageWithPayload<YaEvent> () { data = new YaEvent[] { (YaEvent)evpub } };
msg.to = string.Join (" ", Circle.Union (evpub.Circles));
return r.Invoke (msg);
}
}
}
}

View file

@ -0,0 +1,138 @@
//
// CircleController.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.Web.Http;
using Yavsc.Model.RolesAndMembers;
using System.Collections.Generic;
using Yavsc.Model.Circles;
using System.Web.Security;
using System.Collections.Specialized;
using Yavsc.Model;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Circle controller.
/// </summary>
public class CircleController : ApiController
{
/// <summary>
/// Create the specified circle.
/// </summary>
/// <param name="model">Model.</param>
[Authorize,
AcceptVerbs ("POST")]
public long Create(Circle model)
{
string user = Membership.GetUser ().UserName;
return CircleManager.DefaultProvider.Create (user, model.Title, model.Members);
}
/// <summary>
/// Add the specified users to the circle.
/// </summary>
/// <param name="id">Circle Identifier.</param>
/// <param name="username">username.</param>
[Authorize,
AcceptVerbs ("POST")]
public void Add(long id, string username)
{
checkIsOwner (CircleManager.DefaultProvider.Get (id));
CircleManager.DefaultProvider.AddMember (id, username);
}
/// <summary>
/// Delete the circle specified by id.
/// </summary>
/// <param name="id">Identifier.</param>
[Authorize,
AcceptVerbs ("GET")]
public void Delete(long id)
{
checkIsOwner (CircleManager.DefaultProvider.Get (id));
CircleManager.DefaultProvider.Delete (id);
}
/// <summary>
/// Removes the user from circle.
/// </summary>
/// <param name="id">Identifier.</param>
/// <param name="username">Username.</param>
[Authorize,
AcceptVerbs ("GET")]
public void RemoveUserFromCircle(long id, string username)
{
checkIsOwner (CircleManager.DefaultProvider.Get(id));
CircleManager.DefaultProvider.RemoveMembership (id,username);
}
private void checkIsOwner(CircleBase c)
{
string user = Membership.GetUser ().UserName;
if (c.Owner != user)
throw new AccessViolationException ("You're not owner of this circle");
}
/// <summary>
/// Get the circle specified id.
/// </summary>
/// <param name="id">Identifier.</param>
[Authorize,
AcceptVerbs ("GET")]
public Circle Get(long id)
{
var c = CircleManager.DefaultProvider.GetMembers (id);
checkIsOwner (c);
return c;
}
/// <summary>
/// List the circles
/// </summary>
[Authorize,
AcceptVerbs ("GET")]
public IEnumerable<CircleBase> List()
{
string user = Membership.GetUser ().UserName;
return CircleManager.DefaultProvider.List (user);
}
/// <summary>
/// List the circles
/// </summary>
[Authorize,
AcceptVerbs ("POST")]
public void Update(CircleBase circle)
{
string user = Membership.GetUser ().UserName;
CircleBase current = CircleManager.DefaultProvider.Get (circle.Id);
if (current.Owner != user)
throw new AuthorizationDenied ("Your not owner of circle at id "+circle.Id);
CircleManager.DefaultProvider.UpdateCircle (circle);
}
}
}

View file

@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Profile;
using System.Web.Security;
using Yavsc.Formatters;
using Yavsc.Helpers;
using Yavsc.Model;
using Yavsc.Model.FrontOffice;
using Yavsc.Model.RolesAndMembers;
using Yavsc.Model.WorkFlow;
using System.IO;
using Yavsc.Model.FrontOffice.Catalog;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Front office controller.
/// </summary>
public class FrontOfficeController : ApiController
{
/// <summary>
/// The wfmgr.
/// </summary>
protected WorkFlowManager wfmgr = null;
/// <summary>
/// Initialize the specified controllerContext.
/// </summary>
/// <param name="controllerContext">Controller context.</param>
protected override void Initialize (System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize (controllerContext);
wfmgr = new WorkFlowManager ();
}
/// <summary>
/// Catalog this instance.
/// </summary>
[AcceptVerbs ("GET")]
public Catalog Catalog ()
{
Catalog c = CatalogManager.GetCatalog ();
return c;
}
/// <summary>
/// Gets the product categorie.
/// </summary>
/// <returns>The product categorie.</returns>
/// <param name="brandName">Brand name.</param>
/// <param name="prodCategorie">Prod categorie.</param>
[AcceptVerbs ("GET")]
public ProductCategory GetProductCategorie (string brandName, string prodCategorie)
{
return CatalogManager.GetCatalog ().GetBrand (brandName).GetProductCategory (prodCategorie);
}
/// <summary>
/// Gets the estimate.
/// </summary>
/// <returns>The estimate.</returns>
/// <param name="id">Estimate Id.</param>
[Authorize]
[HttpGet]
public Estimate GetEstimate (long id)
{
Estimate est = wfmgr.ContentProvider.Get (id);
string username = Membership.GetUser ().UserName;
if (est.Client != username)
if (!Roles.IsUserInRole("Admin"))
if (!Roles.IsUserInRole("FrontOffice"))
throw new AuthorizationDenied (
string.Format (
"Auth denied to eid {1} for:{2}",
id, username));
return est;
}
/// <summary>
/// Gets the estim tex.
/// </summary>
/// <returns>The estim tex.</returns>
/// <param name="id">Estimate id.</param>
[AcceptVerbs ("GET")]
public HttpResponseMessage EstimateToTex (long id)
{
string texest = estimateToTex (id);
if (texest == null)
throw new InvalidOperationException (
"Not an estimate");
HttpResponseMessage result = new HttpResponseMessage () {
Content = new ObjectContent (typeof(string),
texest,
new SimpleFormatter ("text/x-tex"))
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue ("attachment") {
FileName = "estimate-" + id.ToString () + ".tex"
};
return result;
}
private string estimateToTex (long estimid)
{
Yavsc.templates.Estim tmpe = new Yavsc.templates.Estim ();
Estimate e = wfmgr.GetEstimate (estimid);
tmpe.Session = new Dictionary<string,object> ();
tmpe.Session.Add ("estim", e);
Profile prpro = new Profile (ProfileBase.Create (e.Responsible));
if (!prpro.HasBankAccount)
throw new TemplateException ("NotBankable:" + e.Responsible);
if (!prpro.HasPostalAddress)
throw new TemplateException ("NoPostalAddress:" + e.Responsible);
Profile prcli = new Profile (ProfileBase.Create (e.Client));
if (!prcli.IsBillable)
throw new TemplateException ("NotBillable:" + e.Client);
tmpe.Session.Add ("from", prpro);
tmpe.Session.Add ("to", prcli);
tmpe.Session.Add ("efrom", Membership.GetUser (e.Responsible).Email);
tmpe.Session.Add ("eto", Membership.GetUser (e.Client).Email);
tmpe.Init ();
return tmpe.TransformText ();
}
/// <summary>
/// Gets the estimate in pdf format from tex generation.
/// </summary>
/// <returns>The to pdf.</returns>
/// <param name="id">Estimid.</param>
[AcceptVerbs("GET")]
public HttpResponseMessage EstimateToPdf (long id)
{
string texest = null;
try {
texest = estimateToTex (id);
} catch (TemplateException ex) {
return new HttpResponseMessage (HttpStatusCode.OK) { Content =
new ObjectContent (typeof(string),
ex.Message, new ErrorHtmlFormatter (HttpStatusCode.NotAcceptable,
LocalizedText.DocTemplateException
))
};
} catch (Exception ex) {
return new HttpResponseMessage (HttpStatusCode.OK) { Content =
new ObjectContent (typeof(string),
ex.Message, new ErrorHtmlFormatter (HttpStatusCode.InternalServerError,
LocalizedText.DocTemplateException))
};
}
if (texest == null)
return new HttpResponseMessage (HttpStatusCode.OK) { Content =
new ObjectContent (typeof(string), "Not an estimation id:" + id,
new ErrorHtmlFormatter (HttpStatusCode.NotFound,
LocalizedText.Estimate_not_found))
};
var memPdf = new MemoryStream ();
try {
new TexToPdfFormatter ().WriteToStream (
typeof(string), texest, memPdf,null);
}
catch (FormatterException ex) {
return new HttpResponseMessage (HttpStatusCode.OK) { Content =
new ObjectContent (typeof(string), ex.Message+"\n\n"+ex.Output+"\n\n"+ex.Error,
new ErrorHtmlFormatter (HttpStatusCode.InternalServerError,
LocalizedText.InternalServerError))
};
}
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memPdf.GetBuffer())
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue ("attachment") {
FileName = String.Format (
"Estimation-{0}.pdf",
id)
};
return result;
}
}
}

View file

@ -0,0 +1,33 @@
//
// GCMController.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.Web.Http;
namespace Yavsc.ApiControllers
{
public class GCMController : ApiController
{
public GCMController ()
{
}
}
}

View file

@ -0,0 +1,77 @@
//
// PaypalApiController.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.Web.Http;
using PayPal;
using System.Collections.Generic;
using PayPal.OpenIdConnect;
using PayPal.Manager;
using PayPal.PayPalAPIInterfaceService;
using PayPal.PayPalAPIInterfaceService.Model;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Paypal API controller.
/// </summary>
public class PaypalController: ApiController
{
PayPalAPIInterfaceServiceService service = null;
/// <summary>
/// Initialize the specified controllerContext.
/// </summary>
/// <param name="controllerContext">Controller context.</param>
protected override void Initialize (System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize (controllerContext);
// Get the config properties from PayPal.Api.ConfigManager
// Create the Classic SDK service instance to use.
service = new PayPalAPIInterfaceServiceService(ConfigManager.Instance.GetProperties());
}
/// <summary>
/// Search the specified str.
/// </summary>
/// <param name="str">str.</param>
public BMCreateButtonResponseType Create(string str)
{
BMCreateButtonRequestType btcrerqu = new BMCreateButtonRequestType ();
BMCreateButtonReq btcrerq = new BMCreateButtonReq ();
btcrerq.BMCreateButtonRequest = btcrerqu;
BMCreateButtonResponseType btcrere = service.BMCreateButton (btcrerq);
return btcrere;
}
/// <summary>
/// Search the specified str.
/// </summary>
/// <param name="str">String.</param>
public BMButtonSearchResponseType Search(string str)
{
BMButtonSearchReq req = new BMButtonSearchReq ();
req.BMButtonSearchRequest = new BMButtonSearchRequestType ();
return service.BMButtonSearch (req);
}
}
}

View file

@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Security;
using Yavsc;
using Yavsc.Model.WorkFlow;
using System.Web.Http;
using Yavsc.Model.RolesAndMembers;
using Yavsc.Helpers;
using Yavsc.Model;
using System.Web.Http.Controllers;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Work flow controller.
/// </summary>
public class WorkFlowController : ApiController
{
string adminRoleName="Admin";
/// <summary>
/// The wfmgr.
/// </summary>
protected WorkFlowManager wfmgr = null;
/// <summary>
/// Initialize the specified controllerContext.
/// </summary>
/// <param name="controllerContext">Controller context.</param>
protected override void Initialize (HttpControllerContext controllerContext)
{
// TODO move it in a module initialization
base.Initialize (controllerContext);
if (!Roles.RoleExists (adminRoleName)) {
Roles.CreateRole (adminRoleName);
}
wfmgr = new WorkFlowManager ();
}
/// <summary>
/// Creates the estimate.
/// </summary>
/// <returns>The estimate.</returns>
/// <param name="title">Title.</param>
/// <param name="client">Client.</param>
/// <param name="description">Description.</param>
[HttpGet]
[Authorize]
public Estimate CreateEstimate (string title,string client,string description)
{
return wfmgr.CreateEstimate (
Membership.GetUser().UserName,client,title,description);
}
/// <summary>
/// Register the specified userModel.
/// </summary>
/// <param name="userModel">User model.</param>
[HttpGet]
[ValidateAjax]
[Authorize(Roles="Admin,FrontOffice")]
public void Register([FromBody] RegisterModel userModel)
{
if (ModelState.IsValid) {
MembershipCreateStatus mcs;
var user = Membership.CreateUser (
userModel.UserName,
userModel.Password,
userModel.Email,
null,
null,
userModel.IsApprouved,
out mcs);
switch (mcs) {
case MembershipCreateStatus.DuplicateEmail:
ModelState.AddModelError ("Email",
string.Format(LocalizedText.DuplicateEmail,userModel.UserName) );
return ;
case MembershipCreateStatus.DuplicateUserName:
ModelState.AddModelError ("Author",
string.Format(LocalizedText.DuplicateUserName,userModel.Email));
return ;
case MembershipCreateStatus.Success:
if (!userModel.IsApprouved)
Url.SendActivationMessage (user);
return;
default:
throw new InvalidOperationException (string.Format("Unexpected user creation code :{0}",mcs));
}
}
}
/// <summary>
/// Drops the writting.
/// </summary>
/// <param name="wrid">Wrid.</param>
[HttpGet]
[Authorize]
public void DropWritting(long wrid)
{
wfmgr.DropWritting (wrid);
}
/// <summary>
/// Drops the estimate.
/// </summary>
/// <param name="estid">Estid.</param>
[HttpGet]
[Authorize]
public void DropEstimate(long estid)
{
string username = Membership.GetUser().UserName;
Estimate e = wfmgr.GetEstimate (estid);
if (e == null)
throw new InvalidOperationException("not an estimate id:"+estid);
if (username != e.Responsible
&& !Roles.IsUserInRole ("FrontOffice"))
throw new UnauthorizedAccessException ("You're not allowed to drop this estimate");
wfmgr.DropEstimate (estid);
}
/// <summary>
/// Index this instance.
/// </summary>
[HttpGet]
[Authorize]
public object Index()
{
// TODO inform user on its roles and alerts
string username = Membership.GetUser ().UserName;
return new { test=string.Format("Hello {0}!",username) };
}
/// <summary>
/// Updates the writting.
/// </summary>
/// <returns>The writting.</returns>
/// <param name="wr">Wr.</param>
[Authorize]
[AcceptVerbs("POST")]
[ValidateAjax]
public HttpResponseMessage UpdateWritting([FromBody] Writting wr)
{
wfmgr.UpdateWritting (wr);
return Request.CreateResponse<string> (System.Net.HttpStatusCode.OK,"WrittingUpdated:"+wr.Id);
}
/// <summary>
/// Adds the specified imputation to the given estimation by estimation id.
/// </summary>
/// <param name="estid">Estimation identifier</param>
/// <param name="wr">Imputation to add</param>
[AcceptVerbs("POST")]
[Authorize]
[ValidateAjax]
public HttpResponseMessage Write ([FromUri] long estid, [FromBody] Writting wr) {
if (estid <= 0) {
ModelState.AddModelError ("EstimationId", "Spécifier un identifiant d'estimation valide");
return Request.CreateResponse (System.Net.HttpStatusCode.BadRequest,
ValidateAjaxAttribute.GetErrorModelObject (ModelState));
}
try {
return Request.CreateResponse(System.Net.HttpStatusCode.OK,
wfmgr.Write(estid, wr.Description,
wr.UnitaryCost, wr.Count, wr.ProductReference));
}
catch (Exception ex) {
return Request.CreateResponse (
System.Net.HttpStatusCode.InternalServerError,
"Internal server error:" + ex.Message + "\n" + ex.StackTrace);
}
}
}
}

View file

@ -0,0 +1,71 @@
//
// YavscApiController.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.Web.Http;
using System.Net.Http;
using System.Web.Profile;
namespace Yavsc.ApiControllers
{
/// <summary>
/// Yavsc controller.
/// </summary>
public class YavscController : ApiController
{
/// <summary>
/// Initializes a new instance of the <see cref="Yavsc.ApiControllers.YavscController"/> class.
/// </summary>
public YavscController ()
{
}
/// <summary>
/// Auth.
/// </summary>
public class Auth {
public string Id { get; set; }
}
/// <summary>
/// Allows the cookies.
/// </summary>
/// <param name="model">Model.</param>
public void AllowCookies (Auth model)
{
// TODO check Auth when existing
if (model.Id != null) {
ProfileBase pr = ProfileBase.Create (model.Id);
pr.SetPropertyValue ("allowcookies", true);
pr.Save ();
}
}
/// <summary>
/// Defaults the response.
/// </summary>
/// <returns>The response.</returns>
protected HttpResponseMessage DefaultResponse()
{
return ModelState.IsValid ?
Request.CreateResponse (System.Net.HttpStatusCode.OK) :
Request.CreateResponse (System.Net.HttpStatusCode.BadRequest,
ValidateAjaxAttribute.GetErrorModelObject (ModelState));
}
}
}