Merge branch 'develop' of git://github.com/Vocaluxe/Vocaluxe into develop

This commit is contained in:
Flamefire committed 2014-08-08 17:33:21 +02:00
commit faee5fa107
44 files changed
+209 -2049

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Timers;
namespace ServerLib
{
public delegate void OnServerDiscovered(string ipAddress, string hostname);
public class CDiscover
{
public const string Timeout = "Timeout";
public const string Finished = "Finished";
private readonly string _Keyword;
private readonly string _BroadcastAddress;
private readonly int _Port;
private Thread _DiscoverThread;
private bool _DiscoverRunning;
private OnServerDiscovered _OnDiscovered;
private readonly System.Timers.Timer _BroadcastTimer;
public CDiscover(int port, string keyword, string broadcastAddress = "255.255.255.255")
{
_BroadcastAddress = broadcastAddress;
_Port = port;
_Keyword = keyword;
_DiscoverRunning = false;
_BroadcastTimer = new System.Timers.Timer();
_BroadcastTimer.Elapsed += _OnBroadcastEvent;
_BroadcastTimer.Interval = 2500;
}
public void StartBroadcasting()
{
_BroadcastTimer.Start();
}
public void Stop()
{
_BroadcastTimer.Stop();
_DiscoverRunning = false;
}
public void Discover(OnServerDiscovered onDiscovered, int timeout = 5000)
{
if (_DiscoverRunning)
return;
_DiscoverRunning = true;
_DiscoverThread = new Thread(() => _Discover(timeout)) {Name = "Client discover"};
_OnDiscovered = onDiscovered;
_DiscoverThread.Start();
}
private void _OnBroadcastEvent(object source, ElapsedEventArgs e)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) {EnableBroadcast = true};
IPAddress broadcast = IPAddress.Parse(_BroadcastAddress);
byte[] sendbuf = Encoding.UTF8.GetBytes(_Keyword);
IPEndPoint ep = new IPEndPoint(broadcast, _Port);
s.SendTo(sendbuf, ep);
s.Close();
}
private void _Discover(int timeout)
{
UdpClient listener = null;
Stopwatch timer = new Stopwatch();
List<string> knownServer = new List<string>();
bool foundSomething = false;
timer.Start();
while (_DiscoverRunning && timer.ElapsedMilliseconds < timeout * 2)
{
try
{
listener = new UdpClient(_Port);
IPEndPoint groupEp = new IPEndPoint(IPAddress.Any, _Port);
listener.Client.ReceiveTimeout = timeout;
byte[] bytes = listener.Receive(ref groupEp);
string message = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
foundSomething = true;
if (!knownServer.Contains(groupEp.Address.ToString()))
{
knownServer.Add(groupEp.Address.ToString());
if (_OnDiscovered != null)
{
IPHostEntry e = Dns.GetHostEntry(groupEp.Address);
string hostname = e.HostName;
_OnDiscovered(groupEp.Address.ToString(), hostname);
}
}
listener.Close();
}
catch (Exception)
{
if (listener != null)
listener.Close();
}
}
_DiscoverRunning = false;
if (_OnDiscovered != null)
_OnDiscovered(!foundSomething ? Timeout : Finished, String.Empty);
}
}
}
+213
View File
@@ -0,0 +1,213 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Net;
using System.Windows.Forms;
namespace ServerLib
{
public class CServer
{
private ServiceHost _Host;
private Uri _BaseAddress;
private bool _Encrypted;
public static SendKeyEventDelegate SendKeyEvent { internal get; set; }
#region profile
public static GetProfileDataDelegate GetProfileData { internal get; set; }
public static SendProfileDataDelegate SendProfileData { internal get; set; }
public static GetProfileListDelegate GetProfileList { internal get; set; }
#endregion
#region photo
public static SendPhotoDelegate SendPhoto { get; set; }
#endregion
#region website
public static GetSiteFileDelegate GetSiteFile { internal get; set; }
public static GetDelayedImageDelegate GetDelayedImage { internal get; set; }
#endregion
#region songs
public static GetSongDelegate GetSong { internal get; set; }
public static GetAllSongsDelegate GetAllSongs { internal get; set; }
public static GetCurrentSongIdDelegate GetCurrentSongId { internal get; set; }
#endregion
#region playlist
public static GetPlaylistsDelegate GetPlaylists { internal get; set; }
public static GetPlaylistDelegate GetPlaylist { internal get; set; }
public static AddSongToPlaylistDelegate AddSongToPlaylist { internal get; set; }
public static RemoveSongFromPlaylistDelegate RemoveSongFromPlaylist { internal get; set; }
public static MoveSongInPlaylistDelegate MoveSongInPlaylist { internal get; set; }
public static PlaylistContainsSongDelegate PlaylistContainsSong { internal get; set; }
public static GetPlaylistSongsDelegate GetPlaylistSongs { internal get; set; }
public static RemovePlaylistDelegate RemovePlaylist { internal get; set; }
public static AddPlaylistDelegate AddPlaylist { internal get; set; }
#endregion
#region user management
public static ValidatePasswordDelegate ValidatePassword { internal get; set; }
public static GetUserRoleDelegate GetUserRole { internal get; set; }
public static SetUserRoleDelegate SetUserRole { internal get; set; }
public static GetUserIdFromUsernameDelegate GetUserIdFromUsername { internal get; set; }
#endregion
public CServer(int port, bool encrypted)
{
_Init(port, encrypted);
}
public string GetBaseAddress()
{
return _BaseAddress.AbsoluteUri;
/*IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in ips)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
return "";*/
}
public bool IsRunning()
{
return _Host.State == CommunicationState.Opened;
}
#region server control
private void _Init(int port, bool encrypted)
{
string hostname = Dns.GetHostName();
string protocol = (encrypted) ? "https" : "http";
_BaseAddress = new Uri(protocol + "://" + hostname + ":" + port + "/");
_Encrypted = encrypted;
_Host = new WebServiceHost(typeof(CWebservice), _BaseAddress);
WebHttpBinding wb = new WebHttpBinding
{
MaxReceivedMessageSize = 10485760,
MaxBufferSize = 10485760,
MaxBufferPoolSize = 10485760,
ReaderQuotas = {MaxStringContentLength = 10485760, MaxArrayLength = 10485760, MaxBytesPerRead = 10485760}
};
if (encrypted)
{
wb.Security.Mode = WebHttpSecurityMode.Transport;
wb.Security.Transport = new HttpTransportSecurity {ClientCredentialType = HttpClientCredentialType.None};
}
_Host.AddServiceEndpoint(typeof(ICWebservice), wb, "");
}
public void Start()
{
try
{
/*ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);*/
_RegisterUrlAndCert(_BaseAddress.Port, false);
_Host.Open();
}
catch (CommunicationException e)
{
if (e is AddressAccessDeniedException || e is AddressAlreadyInUseException)
{
_RegisterUrlAndCert(_BaseAddress.Port, true);
try
{
_Host.Abort();
_Init(_BaseAddress.Port, _Encrypted);
_Host.Open();
}
catch (CommunicationException)
{
_Host.Abort();
MessageBox.Show("Problem while initialization of webserver. You may use a different port (Change in config.xml)");
}
}
else
_Host.Abort();
}
}
public void Stop()
{
try
{
_Host.Close();
}
catch (CommunicationException)
{
_Host.Abort();
}
}
private void _RegisterUrlAndCert(int port, bool reserve)
{
#if WIN
ProcessStartInfo info = new ProcessStartInfo
{
FileName = "VocaluxeServerConfig.exe",
WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory,
Arguments = port + " " + (_Encrypted ? "true" : "false") + (reserve ? " reserve" : ""),
UseShellExecute = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
try
{
using (Process p = Process.Start(info))
{
p.WaitForExit();
p.Close();
}
}
catch (Exception) {}
#else
//Required?
#endif
}
#endregion
}
}
+407
View File
@@ -0,0 +1,407 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.IO;
using System.ServiceModel.Channels;
namespace ServerLib
{
class CWebservice : ICWebservice
{
private static Guid _GetSession()
{
Guid sessionKey = Guid.Empty;
string sessionHeader =
((HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties["httpRequest"]).Headers["session"];
if (string.IsNullOrEmpty(sessionHeader))
return sessionKey;
try
{
sessionKey = Guid.Parse(sessionHeader);
}
catch (Exception) {}
return sessionKey;
}
public void SendKeyEvent(string key)
{
if (!_CheckRight(EUserRights.UseKeyboard))
return;
if (CServer.SendKeyEvent == null)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Not found";
}
}
else
CServer.SendKeyEvent(key);
}
#region profile
public int GetOwnProfileId()
{
Guid sessionKey = _GetSession();
if (sessionKey == Guid.Empty)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "No session";
}
return -1;
}
int profileId = CSessionControl.GetUserIdFromSession(sessionKey);
if (profileId < 0)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "No session";
}
return -1;
}
return profileId;
}
public void SendProfile(SProfileData profile)
{
Guid sessionKey = _GetSession();
if (profile.ProfileId != -1) //-1 is the id for a new profile
{
if (CSessionControl.GetUserIdFromSession(sessionKey) != profile.ProfileId
&& !(_CheckRight(EUserRights.EditAllProfiles)))
return;
}
if (CServer.SendProfileData == null)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Not found";
}
return;
}
CServer.SendProfileData(profile);
}
public SProfileData GetProfile(int profileId)
{
Guid sessionKey = _GetSession();
if (_CheckRight(EUserRights.ViewOtherProfiles) || CSessionControl.GetUserIdFromSession(sessionKey) == profileId)
{
if (CServer.GetProfileData == null)
return new SProfileData();
bool isReadonly = (!CSessionControl.RequestRight(sessionKey, EUserRights.EditAllProfiles) &&
CSessionControl.GetUserIdFromSession(sessionKey) != profileId);
return CServer.GetProfileData(profileId, isReadonly);
}
else
return new SProfileData();
}
public SProfileData[] GetProfileList()
{
if (CServer.GetProfileList == null)
return new SProfileData[] {};
return CServer.GetProfileList();
}
#endregion
#region photo
public void SendPhoto(SPhotoData photo)
{
if (_CheckRight(EUserRights.UploadPhotos))
CServer.SendPhoto(photo);
}
#endregion
#region website
public Guid Login(string username, string password)
{
Guid sessionId = CSessionControl.OpenSession(username, password);
if (sessionId == Guid.Empty)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Wrong username or password";
}
}
return sessionId;
}
public Stream Index()
{
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return new MemoryStream(CServer.GetSiteFile("index.html"));
}
public Stream GetJsFile(string filename)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "text/javascript";
WebOperationContext.Current.OutgoingResponse.LastModified = DateTime.UtcNow;
WebOperationContext.Current.OutgoingResponse.Headers.Add(
HttpResponseHeader.Expires,
DateTime.UtcNow.AddHours(4).ToString("r"));
}
byte[] data = CServer.GetSiteFile("js/" + filename);
if (data != null)
return new MemoryStream(data);
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
return null;
}
public Stream GetCssFile(string filename)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "text/css";
WebOperationContext.Current.OutgoingResponse.LastModified = DateTime.UtcNow;
WebOperationContext.Current.OutgoingResponse.Headers.Add(
HttpResponseHeader.Expires,
DateTime.UtcNow.AddHours(4).ToString("r"));
}
byte[] data = CServer.GetSiteFile("css/" + filename);
if (data != null)
return new MemoryStream(data);
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
return null;
}
public Stream GetCssImageFile(string filename)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
WebOperationContext.Current.OutgoingResponse.LastModified = DateTime.UtcNow;
WebOperationContext.Current.OutgoingResponse.Headers.Add(
HttpResponseHeader.Expires,
DateTime.UtcNow.AddYears(1).ToString("r"));
}
byte[] data = CServer.GetSiteFile("css\\images\\" + filename);
if (data != null)
return new MemoryStream(data);
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
return null;
}
public Stream GetImgFile(string filename)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
WebOperationContext.Current.OutgoingResponse.LastModified = DateTime.UtcNow;
WebOperationContext.Current.OutgoingResponse.Headers.Add(
HttpResponseHeader.Expires,
DateTime.UtcNow.AddYears(1).ToString("r"));
}
byte[] data = CServer.GetSiteFile("img/" + filename);
if (data != null)
return new MemoryStream(data);
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
return null;
}
public Stream GetLocaleFile(string filename)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "text/javascript";
WebOperationContext.Current.OutgoingResponse.LastModified = DateTime.UtcNow;
WebOperationContext.Current.OutgoingResponse.Headers.Add(
HttpResponseHeader.Expires,
DateTime.UtcNow.AddHours(4).ToString("r"));
}
byte[] data = CServer.GetSiteFile("locales/" + filename);
if (data != null)
return new MemoryStream(data);
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
return null;
}
public CBase64Image GetDelayedImage(string id)
{
return CServer.GetDelayedImage(id);
}
public bool IsServerOnline()
{
return true;
}
#endregion
#region songs
public SSongInfo GetSong(int songId)
{
return CServer.GetSong(songId);
}
public int GetCurrentSongId()
{
return CServer.GetCurrentSongId();
}
public SSongInfo[] GetAllSongs()
{
return CServer.GetAllSongs();
}
#endregion
#region playlist
public SPlaylistInfo[] GetPlaylists()
{
return CServer.GetPlaylists();
}
public SPlaylistInfo GetPlaylist(int playlistId)
{
return CServer.GetPlaylist(playlistId);
}
public void AddSongToPlaylist(int songId, int playlistId, bool allowDuplicates)
{
if (_CheckRight(EUserRights.AddSongToPlaylist))
CServer.AddSongToPlaylist(songId, playlistId, allowDuplicates);
}
public void RemoveSongFromPlaylist(int position, int playlistId, int songId)
{
if (_CheckRight(EUserRights.RemoveSongsFromPlaylists))
CServer.RemoveSongFromPlaylist(position, playlistId, songId);
}
public void MoveSongInPlaylist(int newPosition, int playlistId, int songId)
{
if (_CheckRight(EUserRights.ReorderPlaylists))
CServer.MoveSongInPlaylist(newPosition, playlistId, songId);
}
public bool PlaylistContainsSong(int songId, int playlistId)
{
return CServer.PlaylistContainsSong(songId, playlistId);
}
public SPlaylistSongInfo[] GetPlaylistSongs(int playlistId)
{
return CServer.GetPlaylistSongs(playlistId);
}
public void RemovePlaylist(int playlistId)
{
if (_CheckRight(EUserRights.DeletePlaylists))
CServer.RemovePlaylist(playlistId);
}
public int AddPlaylist(string playlistName)
{
if (_CheckRight(EUserRights.CreatePlaylists))
return CServer.AddPlaylist(playlistName);
return -1;
}
#endregion
#region user management
public int GetUserRole(int profileId)
{
return CServer.GetUserRole(profileId);
}
public void SetUserRole(int profileId, int userRole)
{
if (_CheckRight(EUserRights.EditAllProfiles))
CServer.SetUserRole(profileId, userRole);
}
public bool HasUserRight(int right)
{
return _CheckRightWithNoErrorMessage((EUserRights)right);
}
private static bool _CheckRight(EUserRights requestedRight)
{
Guid sessionKey = _GetSession();
if (sessionKey == Guid.Empty)
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "No session";
}
return false;
}
if (!CSessionControl.RequestRight(sessionKey, requestedRight))
{
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Not allowed";
}
return false;
}
return true;
}
private static bool _CheckRightWithNoErrorMessage(EUserRights requestedRight)
{
Guid sessionKey = _GetSession();
if (sessionKey == Guid.Empty)
return false;
if (!CSessionControl.RequestRight(sessionKey, requestedRight))
return false;
return true;
}
#endregion
}
}
+179
View File
@@ -0,0 +1,179 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
namespace ServerLib
{
public delegate bool SendKeyEventDelegate(string key);
#region profile
public delegate SProfileData GetProfileDataDelegate(int profileId, bool isReadonly);
public delegate bool SendProfileDataDelegate(SProfileData profile);
public delegate SProfileData[] GetProfileListDelegate();
[DataContract]
public struct SProfileData
{
[DataMember] public CBase64Image Avatar;
[DataMember] public string PlayerName;
[DataMember] public int Type;
[DataMember] public int Difficulty;
[DataMember] public int ProfileId;
[DataMember] public bool IsEditable;
[DataMember] public string Password;
}
#endregion
#region photo
public delegate bool SendPhotoDelegate(SPhotoData photo);
[DataContract]
public struct SPhotoData
{
[DataMember] public CBase64Image Photo;
//Add infomation about the user who took this image??
}
#endregion
#region website
public delegate byte[] GetSiteFileDelegate(string filename);
public delegate CBase64Image GetDelayedImageDelegate(string hashedFilename);
#endregion
[DataContract]
public class CBase64Image
{
[DataMember] private string base64Data = "";
[DataMember] private string imageId = "";
public CBase64Image(Image img, ImageFormat format)
{
MemoryStream ms = new MemoryStream();
img.Save(ms, format);
string formatString = ImageCodecInfo.GetImageEncoders().FirstOrDefault(x => x.FormatID == format.Guid).FilenameExtension.Replace("*.", "").ToLower();
base64Data = "data:image/" + formatString + ";base64," + Convert.ToBase64String(ms.ToArray());
}
public CBase64Image(string imageId)
{
this.imageId = imageId;
}
public Image GetImage()
{
string onlyBase64Data = base64Data.Substring(base64Data.IndexOf(";base64,") + (";base64,").Length);
byte[] imageData = Convert.FromBase64String(onlyBase64Data);
MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length);
ms.Write(imageData, 0, imageData.Length);
Image image = Image.FromStream(ms, true);
return image;
}
public string GetImageType()
{
Match match = Regex.Match(base64Data, "(?<=data:image/)[a-zA-Z]+(?=;base64)");
return match.Success ? match.Groups[0].Value : "";
}
}
#region songs
public delegate SSongInfo GetSongDelegate(int songId);
public delegate SSongInfo[] GetAllSongsDelegate();
public delegate int GetCurrentSongIdDelegate();
[DataContract]
public struct SSongInfo
{
[DataMember] public string Title;
[DataMember] public string Artist;
[DataMember] public CBase64Image Cover;
[DataMember]
public string Genre { get; set; }
[DataMember]
public string Language { get; set; }
[DataMember]
public string Year { get; set; }
[DataMember]
public bool IsDuet { get; set; }
[DataMember]
public int SongId { get; set; }
}
#endregion
#region playlists
public delegate SPlaylistInfo[] GetPlaylistsDelegate();
public delegate SPlaylistInfo GetPlaylistDelegate(int playlistId);
public delegate void AddSongToPlaylistDelegate(int songId, int playlistId, bool allowDuplicates);
public delegate void RemoveSongFromPlaylistDelegate(int position, int playlistId, int songId);
public delegate void MoveSongInPlaylistDelegate(int newPosition, int playlistId, int songId);
public delegate bool PlaylistContainsSongDelegate(int songId, int playlistId);
public delegate SPlaylistSongInfo[] GetPlaylistSongsDelegate(int playlistId);
public delegate void RemovePlaylistDelegate(int playlistId);
public delegate int AddPlaylistDelegate(string playlistName);
[DataContract]
public struct SPlaylistSongInfo
{
[DataMember] public SSongInfo Song;
[DataMember] public int PlaylistId;
[DataMember] public int PlaylistPosition;
[DataMember] public int GameMode;
}
[DataContract]
public struct SPlaylistInfo
{
[DataMember] public int PlaylistId;
[DataMember] public string PlaylistName;
[DataMember] public int SongCount;
[DataMember] public string LastChanged;
}
#endregion
#region user management
public delegate void SetPasswordDelegate(int profileId, string newPassword);
public delegate bool ValidatePasswordDelegate(int profileId, string password);
public delegate int GetUserRoleDelegate(int profileId);
public delegate void SetUserRoleDelegate(int profileId, int userRole);
public delegate int GetUserIdFromUsernameDelegate(string username);
#endregion
}
+191
View File
@@ -0,0 +1,191 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace ServerLib
{
[ServiceContract]
public interface ICWebservice
{
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/sendKeyEvent?key={key}")]
void SendKeyEvent(string key);
#region profile
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getOwnProfileId")]
int GetOwnProfileId();
[OperationContract, WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/sendProfile")]
void SendProfile(SProfileData profile);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getProfile?profileId={profileId}")]
SProfileData GetProfile(int profileId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getProfileList")]
SProfileData[] GetProfileList();
#endregion
#region photo
[OperationContract, WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/sendPhoto")]
void SendPhoto(SPhotoData photo);
#endregion
#region website
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/login?username={username}&password={password}")]
Guid Login(string username, string password);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "")]
Stream Index();
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/js/{filename}")]
Stream GetJsFile(String filename);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/css/{filename}")]
Stream GetCssFile(String filename);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/css/images/{filename}")]
Stream GetCssImageFile(String filename);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/img/{filename}")]
Stream GetImgFile(String filename);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/locales/{filename}")]
Stream GetLocaleFile(String filename);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/delayedImage?id={id}")]
CBase64Image GetDelayedImage(String id);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/isServerOnline")]
bool IsServerOnline();
#endregion
#region songs
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getSong?songId={songId}")]
SSongInfo GetSong(int songId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getCurrentSongId")]
int GetCurrentSongId();
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getAllSongs")]
SSongInfo[] GetAllSongs();
#endregion
#region playlist
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getPlaylists")]
SPlaylistInfo[] GetPlaylists();
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getPlaylist?id={playlistId}")]
SPlaylistInfo GetPlaylist(int playlistId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/addSongToPlaylist?songId={songId}&playlistId={playlistId}&duplicates={allowDuplicates}")]
void AddSongToPlaylist(int songId, int playlistId, bool allowDuplicates);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/removeSongFromPlaylist?position={position}&playlistId={playlistId}&songId={songId}")]
void RemoveSongFromPlaylist(int position, int playlistId, int songId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/moveSongInPlaylist?newPosition={newPosition}&playlistId={playlistId}&songId={songId}")]
void MoveSongInPlaylist(int newPosition, int playlistId, int songId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/playlistContainsSong?songId={songId}&playlistId={playlistId}")]
bool PlaylistContainsSong(int songId, int playlistId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getPlaylistSongs?playlistId={playlistId}")]
SPlaylistSongInfo[] GetPlaylistSongs(int playlistId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/removePlaylist?playlistId={playlistId}")]
void RemovePlaylist(int playlistId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/addPlaylist?playlistName={playlistName}")]
int AddPlaylist(string playlistName);
#endregion
#region user management
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getUserRole?profileId={profileId}")]
int GetUserRole(int profileId);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/setUserRole?profileId={profileId}&userRole={userRole}")]
void SetUserRole(int profileId, int userRole);
[OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/hasUserRight?right={right}")]
bool HasUserRight(int right);
#endregion
}
}
+56
View File
@@ -0,0 +1,56 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("ClientServerLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ClientServerLib")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("53f89645-1948-420f-b64a-7dc705ca8820")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+89
View File
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{EC5167E4-CCFB-4CEE-987C-CF816F1062A3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ServerLib</RootNamespace>
<AssemblyName>ClientServerLib</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugWin|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\..\Output\</OutputPath>
<DefineConstants>TRACE;DEBUG;WIN;</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugLinux|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\..\Output\</OutputPath>
<DefineConstants>TRACE;DEBUG;LINUX;</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseWin|AnyCPU'">
<OutputPath>..\..\Output\</OutputPath>
<DefineConstants>TRACE;WIN;</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseLinux|AnyCPU'">
<OutputPath>..\..\Output\</OutputPath>
<DefineConstants>TRACE;LINUX;</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Web.Services" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CDiscover.cs" />
<Compile Include="CServer.cs" />
<Compile Include="CWebservice.cs" />
<Compile Include="DataStructs.cs" />
<Compile Include="ICWebservice.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Session.cs" />
<Compile Include="SessionControl.cs" />
<Compile Include="UserRights.cs" />
<Compile Include="UserRoleControl.cs" />
<Compile Include="UserRoles.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
+49
View File
@@ -0,0 +1,49 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
namespace ServerLib
{
class CSession
{
private readonly Guid _ID;
public Guid Id
{
get { return _ID; }
}
private readonly int _ProfileId;
public int ProfileId
{
get { return _ProfileId; }
}
private readonly EUserRoles _Roles;
internal EUserRoles Roles
{
get { return _Roles; }
}
public CSession(Guid id, int profileId, EUserRoles roles)
{
_ID = id;
_ProfileId = profileId;
_Roles = roles;
}
}
}
+79
View File
@@ -0,0 +1,79 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
namespace ServerLib
{
static class CSessionControl
{
private static readonly Dictionary<Guid, CSession> _ActiveSessions = new Dictionary<Guid, CSession>();
public static Guid OpenSession(string userName, string password)
{
if (!_ValidateUserAndPassword(userName, password))
return Guid.Empty;
Guid newId = Guid.NewGuid();
int id = _GetProfileIdFormUsername(userName);
EUserRoles roles = _GetUserRoles(id);
CSession session = new CSession(newId, id, roles);
InvalidateSessions(id);
_ActiveSessions.Add(newId, session);
return newId;
}
private static bool _ValidateUserAndPassword(string userName, string password)
{
return CServer.ValidatePassword(_GetProfileIdFormUsername(userName), password);
}
private static int _GetProfileIdFormUsername(string username)
{
return CServer.GetUserIdFromUsername(username);
}
private static EUserRoles _GetUserRoles(int profileId)
{
return (EUserRoles)CServer.GetUserRole(profileId);
}
internal static void InvalidateSessions(int profileId)
{
foreach (KeyValuePair<Guid, CSession> s in (from kv in _ActiveSessions
where kv.Value.ProfileId == profileId
select kv).ToList())
_ActiveSessions.Remove(s.Key);
}
internal static bool RequestRight(Guid sessionId, EUserRights requestedRight)
{
return ((CUserRoleControl.GetUserRightsFromUserRole(_ActiveSessions[sessionId].Roles)
.HasFlag(requestedRight)));
}
internal static int GetUserIdFromSession(Guid sessionId)
{
if (!_ActiveSessions.ContainsKey(sessionId))
return -1;
return _ActiveSessions[sessionId].ProfileId;
}
}
}
+36
View File
@@ -0,0 +1,36 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
namespace ServerLib
{
[Flags]
enum EUserRights
{
None = 0,
EditAllProfiles = 1,
UploadPhotos = 2,
ViewOtherProfiles = 4,
UseKeyboard = 8,
ReorderPlaylists = 16,
AddSongToPlaylist = 32,
CreatePlaylists = 64,
DeletePlaylists = 128,
RemoveSongsFromPlaylists = 256
}
}
+77
View File
@@ -0,0 +1,77 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Collections.Generic;
using System.Linq;
namespace ServerLib
{
static class CUserRoleControl
{
private static readonly Dictionary<EUserRoles, EUserRights> _RoleRightsMapping = new Dictionary<EUserRoles, EUserRights>
{
{
EUserRoles.TR_USERROLE_ADMIN,
(EUserRights.EditAllProfiles |
EUserRights.UploadPhotos |
EUserRights.ViewOtherProfiles |
EUserRights.UseKeyboard |
EUserRights.AddSongToPlaylist |
EUserRights.ReorderPlaylists |
EUserRights.CreatePlaylists |
EUserRights.DeletePlaylists |
EUserRights.RemoveSongsFromPlaylists)
},
{
EUserRoles.TR_USERROLE_GUEST,
EUserRights.None
},
{
EUserRoles.TR_USERROLE_NORMAL,
(EUserRights.UploadPhotos |
EUserRights.ViewOtherProfiles)
},
{
EUserRoles.TR_USERROLE_KEYBOARDUSER,
EUserRights.UseKeyboard
},
{
EUserRoles.TR_USERROLE_ADDSONGSUSER,
EUserRights.AddSongToPlaylist
},
{
EUserRoles.TR_USERROLE_PLAYLISTEDITOR,
(EUserRights.AddSongToPlaylist |
EUserRights.ReorderPlaylists |
EUserRights.CreatePlaylists |
EUserRights.DeletePlaylists |
EUserRights.RemoveSongsFromPlaylists)
},
{
EUserRoles.TR_USERROLE_PROFILEEDITOR,
EUserRights.EditAllProfiles
}
};
internal static EUserRights GetUserRightsFromUserRole(EUserRoles userRole)
{
return _RoleRightsMapping.Where(role => userRole.HasFlag(role.Key))
.Select(role => role.Value)
.Aggregate(EUserRights.None, (current, r) => current | r);
}
}
}
+33
View File
@@ -0,0 +1,33 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
namespace ServerLib
{
[Flags]
enum EUserRoles
{
TR_USERROLE_GUEST = 0,
TR_USERROLE_NORMAL = 1,
TR_USERROLE_ADMIN = 2,
TR_USERROLE_KEYBOARDUSER = 4,
TR_USERROLE_ADDSONGSUSER = 8,
TR_USERROLE_PLAYLISTEDITOR = 16,
TR_USERROLE_PROFILEEDITOR = 32
}
}
Binary file not shown.