//Returns the path to the tools used by MOTRd static public string GetExecuteToolPath(string sTool) { string sToolVersion = GetCurrentToolVersion(sTool); if (sToolVersion.Length == 0) { return(""); } string baseFolder = MOTR_Settings.GetGlobalApplicationPath("tools"); try { string[] aExeFiles = Directory.GetFiles(baseFolder + sTool + @"\" + sToolVersion, "*.exe", SearchOption.TopDirectoryOnly); if (aExeFiles.Length > 0) { return(aExeFiles[0]); } else { return(""); } } catch (Exception ex) { Console.WriteLine("Error getting execute tool path, with error: " + ex.Message.ToString()); return(""); } }
//Get movieinformation from database public MovieInformation GetMovieInformation(string sSession, int nFileID) { string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); //Get the path for the FileID string sPath = this.GetTemporaryVariable(sSession, "DrivePosition"); string sFile = this.GetPathByID(sSession, nFileID); //No length, no go... if (sPath.Length == 0 || sFile.Length == 0) { return(null); } //Include full filename sPath += sFile; lock (_lockDbObjectMovies) { LiteDatabase m_db = new LiteDatabase(sGlobalPath + @"\MovieInformation.db"); LiteCollection <MovieInformation> aDBValues = m_db.GetCollection <MovieInformation>("movieinfo"); MovieInformation results = aDBValues.FindOne(x => x.Path == sPath); m_db.Dispose(); if (results != null) { return(results); } else { return(null); } } }
public MOTR_Dirs() { string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); m_db = new LiteDatabase(sGlobalPath + @"\Directories.db"); aUNCConnections = new ArrayList(); ReadDirs(); }
public MOTR_Users() { //Opening the database string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); m_db = new LiteDatabase(sGlobalPath + @"\Userdata.db"); sUserSalt = "Also users needs salt :)"; }
public static string GetCurrentToolVersion(string sTool) { string baseFolder = MOTR_Settings.GetGlobalApplicationPath("tools"); if (Directory.Exists(baseFolder)) { if (File.Exists(baseFolder + sTool + ".txt")) { return(File.ReadAllText(baseFolder + sTool + ".txt")); } } return(""); }
public static bool UpdateTool(string sTool, string sVersion) { WebClient m_WebClient = new WebClient(); string baseFolder = MOTR_Settings.GetGlobalApplicationPath("tools"); //Create directory if it does not exists try { if (!Directory.Exists(baseFolder)) { Directory.CreateDirectory(baseFolder); } if (!Directory.Exists(baseFolder + sTool)) { Directory.CreateDirectory(baseFolder + sTool); } //Now create a directory with current version string sToolDirectory = baseFolder + sTool + @"\"; if (!Directory.Exists(sToolDirectory + sVersion)) { Directory.CreateDirectory(sToolDirectory + sVersion); } //Now download the file from the webserver m_WebClient.DownloadFile("http://moviesonthe.run/tools/" + sTool + "/" + sVersion + "/" + sTool + ".zip", sToolDirectory + sVersion + @"\" + sTool + ".zip"); //Extract the file, ready to use //ZipFile.ExtractToDirectory(sToolDirectory + sVersion + @"\" + sTool + ".zip", sToolDirectory + sVersion); ZipArchive archive = ZipFile.OpenRead(sToolDirectory + sVersion + @"\" + sTool + ".zip"); foreach (ZipArchiveEntry file in archive.Entries) { if (file.Name.Length > 0) { file.ExtractToFile(sToolDirectory + sVersion + @"\" + file.FullName, true); } } //Create a file with the current version File.WriteAllText(baseFolder + sTool + ".txt", sVersion); return(true); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(false); } }
//Function that fires away a convert with handbreak private bool ExecuteQueue(long nQueueID) { int nItem = ItemByQueueID(nQueueID); if (nItem == -1) { return(false); } QueueStruct aStruct = (QueueStruct)aQueue[nItem]; //We don't run twice... if (aStruct.nStatus == QueueStatus.RUNNING) { return(false); } //Setting the parameters string baseFolder = MOTR_Settings.GetGlobalApplicationPath("tools"); string sExec = MOTR_Settings.GetExecuteToolPath("handbreak"); string sParams = "--optimize --preset \"" + aStruct.sHandbrakeProfile + "\" --input \"" + aStruct.sPath + aStruct.sSource + "\" --output \"" + aStruct.sPath + aStruct.sDestination + "\""; aStruct.dateRunning = DateTime.Now; aStruct.nStatus = QueueStatus.RUNNING; //extension = extension.Substring(extension.Length - 4); string sExtension = aStruct.sSource.Substring(aStruct.sSource.Length - 4); if (sExtension.ToUpper() == ".RAR") { sExec = MOTR_Settings.GetExecuteToolPath("unrar"); sParams = "x -y -p- " + aStruct.sPath + aStruct.sSource; } //Console.WriteLine("Exec: " + sExec + " " + sParams); //Now start the background process, if it fails change status of the queue if (!StartBackgroundProcess(sExec, sParams, aStruct.sPath, aStruct.nQueueID)) { aStruct.nStatus = QueueStatus.FINISHEDANDFAIL; aStruct.sETA = "Background could not be executed, please update tools"; } //Update the current item aQueue.RemoveAt(nItem); aQueue.Insert(nItem, aStruct); return(true); }
//Store movieinformation in a database public bool StoreMovieInformation(string sSession, int nFileID, MovieInformation movieInformation) { string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); //Get the path for the FileID string sPath = this.GetTemporaryVariable(sSession, "DrivePosition"); string sFile = this.GetPathByID(sSession, nFileID); //No length, no go... if (sPath.Length == 0 || sFile.Length == 0) { return(false); } //Include full filename sPath += sFile; //Store it in the class movieInformation.Path = sPath; lock (_lockDbObjectMovies) { LiteDatabase m_db = new LiteDatabase(sGlobalPath + @"\MovieInformation.db"); LiteCollection <MovieInformation> aDBValues = m_db.GetCollection <MovieInformation>("movieinfo"); // Use Linq to query documents var results = aDBValues.FindOne(x => x.Path == sPath); if (results != null) { int ResultID = results._id; results = movieInformation; results._id = ResultID; aDBValues.Update(results); } else //Add new { aDBValues.EnsureIndex(x => x.Path); aDBValues.Insert(movieInformation); } m_db.Dispose(); } return(true); }
//Download function to get file private void DownloadImage(string sImage) { //No file, just return if (sImage == null) { return; } if (sImage.Length == 0) { return; } //Get the path for files string desktopPath = MOTR_Settings.GetGlobalApplicationPath("MovieImages"); if (!Directory.Exists(desktopPath)) { Directory.CreateDirectory(desktopPath); } //No need to download again if (File.Exists(desktopPath + sImage)) { return; } // This will download a large image from the web, you can change the value string urlstart = "https://image.tmdb.org/t/p/original/"; string url = urlstart + sImage; //Using sync method using (var client = new WebClient()) { client.DownloadFile(url, desktopPath + "/" + sImage); } /* * //Async method for downloading * using (WebClient wc = new WebClient()) * { * //wc.DownloadProgressChanged += wc_DownloadProgressChanged; * wc.DownloadFileCompleted += wc_DownloadFileCompleted; * wc.DownloadFileAsync(new Uri(url), desktopPath + "/" + sImage); * }*/ }
private bool ReadAdminPassword() { string baseFolder = MOTR_Settings.GetGlobalApplicationPath("config"); if (File.Exists(baseFolder + "admin.ini") == false) { SetErrorString(@"Critical error! No adminpassword is set, please check the %programdata%\MOTRd\ for a admin.ini file\nAlternative delete all files in %programdata%\MOTRd\ to run inital setup again"); return(false); } using (var file = File.OpenRead(baseFolder + "admin.ini")) { var reader = new BinaryFormatter(); m_AdminPassword = (EncryptedData)reader.Deserialize(file); // Reads the entire list. file.Close(); } return(true); }
public void CreateAdminPassword(string sPassword) { string baseFolder = MOTR_Settings.GetGlobalApplicationPath("config"); //We do not overwrite... if (File.Exists(baseFolder + "admin.ini")) { SetErrorString("Adminpassword already exists, cannot overwrite"); return; } //Get the structed filled m_AdminPassword = GetCipher(sPassword); using (var file = File.OpenWrite(baseFolder + "admin.ini")) { var writer = new BinaryFormatter(); writer.Serialize(file, m_AdminPassword); // Writes the struct file.Close(); } }
public MOTR_Downloads(MOTR_Dirs _Dirs) { m_Dirs = _Dirs; //Array for what??? - old school remove after dbconvert aDownloads = new ArrayList(); string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); m_dbdownload = new LiteDatabase(sGlobalPath + @"\Downloads.db"); // this.AddMobileDownload(16, 6, "Mainstream\\super.troopers.2.2018.1080p.bluray.x264-drones.mkv"); //sDownloadsFilename = "downloads.ini"; //WindowsService.LogEventInformation("Starting to read sessions..."); //ReadSession(); //Console.WriteLine("There is {0} sessions", aSessions.Count); // for(int i=0;i<aSessions.Count;i++) // Console.WriteLine("Random {0} chars", GetRandomString(RANDOM_LENGTH, RANDOM_CHARACTERSUSED.ToCharArray())); }
//Sessionless storage public string GetSessionLessVariable(string sSession, int nFileID, string sCommand) { string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); //Get the path for the FileID string sDrive = this.GetTemporaryVariable(sSession, "Drive"); string sPath = this.GetTemporaryVariable(sSession, "DrivePosition"); string sFile = this.GetPathByID(sSession, nFileID); int DirID = Convert.ToInt32(GetTemporaryVariable(sSession, "DriveID")); int UserID = Convert.ToInt32(GetTemporaryVariable(sSession, "UserID")); //No length, no go... if (sPath.Length == 0 || sFile.Length == 0) { return(""); } //Include full filename, minus the drive length sPath += sFile; sPath = sPath.Substring(sDrive.Length); lock (_lockDbObject) { LiteDatabase m_db = new LiteDatabase(sGlobalPath + @"\SessionLessStorage.db"); LiteCollection <SessionlessStorage> aDBValues = m_db.GetCollection <SessionlessStorage>("sessionlessstorage"); var results = aDBValues.FindOne(x => x.UserID == UserID && x.DirID == DirID && x.Path == sPath && x.Command == sCommand); m_db.Dispose(); if (results != null) { return(results.Value); } else { return(""); } } }
public MOTR_Sessions(MOTR_Users Users) { //Storing the users variable, used to check the ID etc.. m_Users = Users; aTemporarySessions = new ArrayList(); //WindowsService.LogEventInformation("Starting to read sessions..."); //Opening the database string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); m_db = new LiteDatabase(sGlobalPath + @"\Sessions.db"); //Check for expired sessions LiteCollection <SessionStruct> aDBValues = m_db.GetCollection <SessionStruct>("session"); foreach (SessionStruct item in aDBValues.FindAll()) { if (SessionExpired(item.sLastUsed)) { RemoveSession(item.sID); } } }
//Writes into a log-file instead private void WriteToLogFile(string message) { string baseFolder = MOTR_Settings.GetGlobalApplicationPath(); System.IO.File.AppendAllText(baseFolder + @"\console.log", message + Environment.NewLine); }
/* * private LoginReturn LoginValid(string sHeader) * { * //Hent ut info fra svaret * int iLength = GetContentLength(sHeader); * int nEndPos = sHeader.IndexOf("\r\n\r\n"); * if (nEndPos+4 > (sHeader.Length - iLength)) * { * Console.WriteLine("No userdata ffs: " + sHeader); * return LoginReturn.NO_CONTENT; * } * string sPostData = sHeader.Substring(sHeader.Length - iLength); * _logger.Information(typeof(MOTR_WebserverFactory), "Header in POST: " + sHeader); * _logger.Information(typeof(MOTR_WebserverFactory), "PostData: " + sPostData); * * //Data needs to be at least u=x&p=x * if (sPostData.Length < 7) * return LoginReturn.NOT_LOGGED_IN; * * //Split the chars * char[] delimiterChars = { '=', '&'}; * string[] verbs= sPostData.Split(delimiterChars); * * //Fill username and password * string sUsername=""; * string sPassword=""; * for(int i=0;i<verbs.Count();i++) * { * //Find username * if (verbs[i].ToUpper() == "U") * if(verbs.Count() > i+1) * sUsername = verbs[i + 1]; * if (verbs[i].ToUpper() == "P") * if (verbs.Count() > i + 1) * sPassword = verbs[i + 1]; * } * * //Console.WriteLine("Username: "******"Password: "******"/directory") { MOTR_DirectoryWebsocket pWS = new MOTR_DirectoryWebsocket(connectionDetails.Stream, connectionDetails.TcpClient, connectionDetails.Header, _logger, m_Sessions, m_Dirs, m_Queue, m_Users, m_Downloads); pWS.OnQueueUpdate += m_WebServer.HandleEvent; return(pWS); } if (connectionDetails.Path == "/admin") { MOTR_AdminWebsocket pWS = new MOTR_AdminWebsocket(connectionDetails.Stream, connectionDetails.TcpClient, connectionDetails.Header, _logger, m_Sessions, m_Dirs, m_Users, m_Admin); pWS.OnRestartWebserver += this.OnRestartWebserver; return(pWS); } break; case ConnectionType.Http: // this path actually refers to the reletive location of some html file or image string extension = connectionDetails.Path; //_logger.Information(this.GetType(), "Header: {0}", connectionDetails.Header); //_logger.Information(this.GetType(), "Path: {0}", connectionDetails.Path); if (extension.Length > 4) { extension = extension.Substring(extension.Length - 4); extension = extension.ToUpper(); string sIP = connectionDetails.TcpClient.Client.RemoteEndPoint.ToString(); //_logger.Information(this.GetType(), "IP adress: {0}", sIP); } //Special extension for our file if (extension == "MOTR" || extension == "LOAD") { //_logger.Information(this.GetType(), "Handling MOTR or LOAD: " + extension); //Sjekk at brukeren er logget inn (SessionID = gullgutten), TempID er for å sette gullgutten ;) string sSessionID = GetCookie(connectionDetails.Header, "SessionID"); if (sSessionID.Length > 0) { if (!m_Sessions.SessionLoggedIn(sSessionID, "[WEBBASEDAUTH, NOT USER]")) { return(new HttpRedirectService(connectionDetails.Stream, "/", connectionDetails.Path, "[DELETE]", _logger)); } else if (GetCookie(connectionDetails.Header, "TempID").Length > 0) { return(new HttpRedirectService(connectionDetails.Stream, connectionDetails.Path, connectionDetails.Path, sSessionID, _logger)); } } else //Just forward when we don't have any session { string sTempID = GetCookie(connectionDetails.Header, "TempID"); if (sTempID.Length == 0) { return(new HttpRedirectService(connectionDetails.Stream, "/", connectionDetails.Path, "", _logger)); } else { //Get the session, if it is real, set the session to login sSessionID = m_Sessions.GetSessionByTempID(sTempID); if (sSessionID.Length == 0) { return(new HttpRedirectService(connectionDetails.Stream, "/", connectionDetails.Path, "", _logger)); } else { return(new HttpRedirectService(connectionDetails.Stream, connectionDetails.Path, connectionDetails.Path, sSessionID, _logger)); } } } //Sjekk om det er utlogging som skal foregå bool bRemoveCookies = false; if (connectionDetails.Path.ToUpper().Contains("LOGOFF.MOTR")) { //Slett sesjonen fra listen, la parseren håndtere resten m_Sessions.RemoveSession(sSessionID); bRemoveCookies = true; } //Her skal vi parse fila før vi sender avgårde html'n... if (extension == "MOTR") //Ignore if we are going to remove cookies, normally logging out { MOTR_Parser m_Parser = new MOTR_Parser(_logger, sSessionID, m_Sessions); return(new HttpTextService(connectionDetails.Stream, m_Parser.ParseFile(_webRoot + connectionDetails.Path), _logger, bRemoveCookies)); } else //Handling "DOWN.LOAD" { string[] aTemp = connectionDetails.Path.Split('/'); if (aTemp.Count() > 0) { string nID = aTemp[1]; string sPath = m_Sessions.GetTemporaryVariable(sSessionID, "DrivePosition"); string sFile = m_Sessions.GetPathByID(sSessionID, Convert.ToInt32(nID)); string sOneHour = DateTime.Now.AddHours(1).ToString(); string sDownloadID = m_Downloads.AddDownload(sSessionID, sPath + sFile, false, sOneHour); return(new HttpRedirectService(connectionDetails.Stream, "/MOTR-download/" + sDownloadID + "/" + sFile, "", "", _logger)); } else { return(new HttpTextService(connectionDetails.Stream, "Did not provide correct nID for file", _logger)); } } } //Here we handle the tag "/motr-download/" to ensure we download the file binary if (connectionDetails.Path.Contains("/MOTR-download/")) { //Check if we have a session (This blocks several clients, temp disabled) //string sSessionID = GetCookie(connectionDetails.Header, "SessionID"); //if(sSessionID.Length == 0) // return new HttpTextService(connectionDetails.Stream, "Session is no longer valid, unable to download", _logger); string[] aDownloads = connectionDetails.Path.Split('/'); string sDownloadID = ""; if (aDownloads.Count() > 2) { sDownloadID = aDownloads[2]; } if (sDownloadID.Length > 0) { //Get the filename //string sFileName = connectionDetails.Path.Substring(connectionDetails.Path.LastIndexOf('/') + 1); string sFileName = m_Downloads.GetDownload(sDownloadID); //No filename, no love... if (sFileName.Length == 0) { _logger.Warning(typeof(MOTR_WebserverFactory), "Download is no longer valid..."); return(new BadRequestService(connectionDetails.Stream, connectionDetails.Header, _logger)); } sFileName = Uri.UnescapeDataString(sFileName); if (connectionDetails != null) { if (connectionDetails.Header != null) { _logger.Debug(typeof(MOTR_WebserverFactory), "MOTR-download: " + WebUtility.HtmlDecode(connectionDetails.Header)); } } //This is where the file actually is //string sBasePath = m_Sessions.GetTemporaryVariable(sSessionID, "DrivePosition"); //return new HttpBinaryService(connectionDetails.Stream, sBasePath + sFileName, _logger); return(new HttpBinaryService(connectionDetails.Stream, sFileName, _webRoot, connectionDetails.Header, _logger)); } } //END: /MOTR-download else if (connectionDetails.Path.Contains("/kodi/")) //Kodi directory is special { extension = extension.ToUpper(); if (extension == ".ZIP") { return(new HttpBinaryService(connectionDetails.Stream, _webRoot + connectionDetails.Path, _webRoot, connectionDetails.Header, _logger)); } } else if (connectionDetails.Path.Contains("/MovieInfo/")) //Kodi directory is special { int nSlashPos = connectionDetails.Path.LastIndexOf('/'); string sImageName = connectionDetails.Path.Substring(nSlashPos, connectionDetails.Path.Length - (nSlashPos)); sImageName = sImageName.Substring(1, sImageName.Length - 1); sImageName = sImageName.Replace("..", ""); sImageName = sImageName.Replace("%", ""); string movieInfoPath = MOTR_Settings.GetGlobalApplicationPath("MovieImages"); return(new HttpBinaryService(connectionDetails.Stream, movieInfoPath + sImageName, _webRoot, connectionDetails.Header, _logger)); } //Redirect to front page on initalsetup if (connectionDetails.Path.Contains("/initalsetup/")) { return(new HttpRedirectService(connectionDetails.Stream, "/", connectionDetails.Path, "", _logger)); } //Everything else is served here (but limited to the mimelist...) return(new HttpService(connectionDetails.Stream, connectionDetails.Path, _webRoot, _logger)); case ConnectionType.Head: //Only handle MOTR-download on head requests //_logger.Information(typeof(MOTR_WebserverFactory), "HEAD: " + connectionDetails.Header); if (connectionDetails.Path.Contains("/MOTR-download/")) { string[] aDownloads = connectionDetails.Path.Split('/'); string sDownloadID = ""; if (aDownloads.Count() > 2) { sDownloadID = aDownloads[2]; } if (sDownloadID.Length > 0) { string sFileName = m_Downloads.GetDownload(sDownloadID, true); return(new HttpBinaryService(connectionDetails.Stream, sFileName, _webRoot, connectionDetails.Header, _logger, true)); //True is head only! } } else if (connectionDetails.Path.Contains("/kodi/")) //Kodi directory is special { return(new HttpBinaryService(connectionDetails.Stream, _webRoot + connectionDetails.Path, _webRoot, connectionDetails.Header, _logger, true)); //True is head only! } else if (connectionDetails.Path.Contains("/MovieInfo/")) //Kodi directory is special { int nSlashPos = connectionDetails.Path.LastIndexOf('/'); string sImageName = connectionDetails.Path.Substring(nSlashPos, connectionDetails.Path.Length - (nSlashPos)); sImageName = sImageName.Substring(1, sImageName.Length - 1); sImageName = sImageName.Replace("..", ""); sImageName = sImageName.Replace("%", ""); string movieInfoPath = MOTR_Settings.GetGlobalApplicationPath("MovieImages"); return(new HttpBinaryService(connectionDetails.Stream, movieInfoPath + sImageName, _webRoot, connectionDetails.Header, _logger, true)); //True is head only! } //Redirect to front page on initalsetup _logger.Warning(typeof(MOTR_WebserverFactory), "Head requested, not supported for all paths: " + connectionDetails.Header); return(new BadRequestService(connectionDetails.Stream, connectionDetails.Header, _logger)); //return new HttpTextService(connectionDetails.Stream, "HEAD is not supported", _logger); } return(new BadRequestService(connectionDetails.Stream, connectionDetails.Header, _logger)); }
/// <summary> /// The Main Thread: This is where your Service is Run. /// </summary> static void Main(string[] args) { //Check if the global application path exists, if not create it string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); if (!Directory.Exists(sGlobalPath)) { Directory.CreateDirectory(sGlobalPath); } //Static service variable to handle the service m_TheService = new WindowsService(); //Default values before startup iHTTP = MOTR_Settings.GetNumber("http"); if (iHTTP == 0) { iHTTP = 80; MOTR_Settings.SetNumber("http", iHTTP); } iHTTPS = MOTR_Settings.GetNumber("https"); //If iHTTPS = 0 then the https will not open //This is function is before Mutex, so it will be runned each time! //If one of the parameters is to generate a cert, then we are creating in the same path for (int i = 0; i < args.Length; i++) { string sArg = args[i].ToUpper(); if (sArg == "-CERT") { string name = "MOTRd"; string domain = ""; if (args.Length > i + 1) { domain = "*." + args[i + 1]; name = domain; } CertGenerator m_Generator = new CertGenerator(); if (m_Generator.GenerateAndSave(name, domain)) { LogEventInformation("MOTR certificate generated success"); } else { LogEventError("MOTR certification generation error"); } return; } //Wait 5 seconds if (sArg == "-WAIT") { Thread.Sleep(3000); return; } //Port override with parameters if (sArg.Contains("HTTPS")) { string[] aString = sArg.Split('='); if (aString.Length > 1) { iHTTPS = Convert.ToInt32(aString[1]); } } else if (sArg.Contains("HTTP")) { string[] aString = sArg.Split('='); if (aString.Length > 1) { iHTTP = Convert.ToInt32(aString[1]); } } //Check for tool update if (sArg == "-TOOLUPDATE") { Console.WriteLine("Update tools..."); ArrayList aTools = new ArrayList(); aTools.Add("handbreak"); aTools.Add("unrar"); //Update all the tools used for (int o = 0; o < aTools.Count; o++) { string sLocalVersion = MOTR_Settings.GetCurrentToolVersion(aTools[o].ToString()); string sWebVersion = MOTR_Settings.GetWebsiteToolVersion(aTools[o].ToString()); //Updates if (sLocalVersion != sWebVersion) { Console.Write("Updating " + aTools[o].ToString() + " to v" + sWebVersion + "... "); bool bRet = MOTR_Settings.UpdateTool(aTools[o].ToString(), sWebVersion); if (bRet) { Console.WriteLine("success"); } else { Console.WriteLine("failed"); } } else { Console.WriteLine(aTools[o].ToString() + " already in latest version"); } } return; } } //====================================================== //Create the global mutex and set its security bool bFirstInstance = false; Mutex mutex = null; try { //Create a mutex with security globally oMutexSecurity = new MutexSecurity(); oMutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), MutexRights.FullControl, AccessControlType.Allow)); mutex = new Mutex(true, "Global\\MOTRD Mutex for single instances", out bFirstInstance); mutex.SetAccessControl(oMutexSecurity); } catch (Exception ex) { LogEventError("Only one instance of MOTRd is allowed, please check if service is running or taskmanager for motrd.exe. Only one instance is allowed!"); Console.WriteLine("Error: " + ex.Message.ToString()); m_TheService.Stop(); return; } //Check if we are going to run as service or not :) bool bRunAsService = true; if (Environment.UserInteractive) { bRunAsService = false; } if (bRunAsService) { //Check if there are other instances if (mutex.WaitOne(TimeSpan.Zero, true)) { ServiceBase.Run(m_TheService); } else { LogEventError("Only one instance of MOTRd is allowed, please stop service or check taskmanager for motrd.exe"); m_TheService.Stop(); return; } } else { //Check if there are other instances if (mutex.WaitOne(TimeSpan.Zero, true)) { Console.ForegroundColor = ConsoleColor.DarkBlue; Console.WriteLine("Starting in console..."); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Press Q to quit"); Console.Write("Args: "); for (int i = 0; i < args.Length; i++) { Console.Write(args[i] + ", "); } Console.WriteLine(""); Console.ResetColor(); MOTR_Settings.ShowAllSettings(); //test //Lager en "fake" service og starter den lik en normal service vil kjøre m_TheService.StartServiceAsConsole(args); while (true) { char cKey = Console.ReadKey().KeyChar; if (cKey == 'Q' || cKey == 'q') { break; } } m_TheService.StopServiceAsConsole(); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR: MOTRd is already running."); Console.ResetColor(); Console.WriteLine("Could be running as service, also check taskmanager for motrd.exe"); Console.WriteLine("Press any key to quit"); Console.ReadKey(); } } }
public bool StoreSessionLessVariable(string sSession, int nFileID, string sCommand, string sValue) { string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath(); //Store the username int DirID = Convert.ToInt32(GetTemporaryVariable(sSession, "DriveID")); int UserID = Convert.ToInt32(GetTemporaryVariable(sSession, "UserID")); //Get the path for the FileID string sDrive = this.GetTemporaryVariable(sSession, "Drive"); string sPath = this.GetTemporaryVariable(sSession, "DrivePosition"); string sFile = this.GetPathByID(sSession, nFileID); //No length, no go... if (sPath.Length == 0 || sFile.Length == 0) { return(false); } //Include full filename sPath += sFile; sPath = sPath.Substring(sDrive.Length); SessionlessStorage aSessionlessStorage = new SessionlessStorage { DirID = DirID, UserID = UserID, Path = sPath, Command = sCommand, Value = sValue, Added = DateTime.Now }; lock (_lockDbObject) { LiteDatabase m_db = new LiteDatabase(sGlobalPath + @"\SessionLessStorage.db"); LiteCollection <SessionlessStorage> aDBValues = m_db.GetCollection <SessionlessStorage>("sessionlessstorage"); // Use Linq to query documents var results = aDBValues.FindOne(x => x.UserID == UserID && x.DirID == DirID && x.Path == sPath && x.Command == sCommand); if (results != null) { if (sValue.Length > 0) { results.Value = sValue; aDBValues.Update(results); } else { aDBValues.Delete(results.Id); //Remove by id } } else //Add new { aDBValues.EnsureIndex(x => x.UserID); aDBValues.Insert(aSessionlessStorage); } m_db.Dispose(); } return(true); }