Esempio n. 1
0
        //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("");
            }
        }
Esempio n. 2
0
        //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);
                }
            }
        }
Esempio n. 3
0
        //Parseren må vite hvilken session som gjelder, slik at man får lov til å utføre handling

        public string ParseFile(string sFile)
        {
            FileInfo fi = new FileInfo(sFile);

            if (fi.Exists)
            {
                string ext = fi.Extension.ToLower();

                string[] sFileText = File.ReadAllLines(fi.FullName);
                //RespondSuccess(contentType, bytes.Length);

                //Set default values if not exists
                int iHTTP  = MOTR_Settings.GetNumber("http");
                int iHTTPS = MOTR_Settings.GetNumber("https");
                if (iHTTP == 0)
                {
                    iHTTP = 80;
                    MOTR_Settings.SetNumber("http", iHTTP);
                }

                string sReturn = "";
                //int i = 1;
                foreach (string s in sFileText)
                {
                    if (s.Contains("</@DISPLAYNAME@>"))
                    {
                        sReturn += s.Replace("</@DISPLAYNAME@>", m_Sessions.GetDisplayName(sSessionID)) + Environment.NewLine;
                    }
                    else if (s.Contains("</@HANDBREAKVERSION@>"))
                    {
                        sReturn += s.Replace("</@HANDBREAKVERSION@>", MOTR_Settings.GetCurrentToolVersion("handbreak")) + Environment.NewLine;
                    }
                    else if (s.Contains("</@UNRARVERSION@>"))
                    {
                        sReturn += s.Replace("</@UNRARVERSION@>", MOTR_Settings.GetCurrentToolVersion("unrar")) + Environment.NewLine;
                    }
                    else if (s.Contains("</@HTTPPORT@>"))
                    {
                        sReturn += s.Replace("</@HTTPPORT@>", iHTTP.ToString()) + Environment.NewLine;
                    }
                    else if (s.Contains("</@HTTPSPORT@>"))
                    {
                        sReturn += s.Replace("</@HTTPSPORT@>", iHTTPS.ToString()) + Environment.NewLine;
                    }
                    else
                    {
                        sReturn += s + Environment.NewLine;
                    }
                    //sReturn += i.ToString() + ": " + s + Environment.NewLine;
                    //i += 1;
                }

                return(sReturn);
            }

            return("No file exists with that name: " + DateTime.Now.ToString());
        }
Esempio n. 4
0
        public MOTR_Dirs()
        {
            string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath();

            m_db = new LiteDatabase(sGlobalPath + @"\Directories.db");

            aUNCConnections = new ArrayList();
            ReadDirs();
        }
Esempio n. 5
0
        public MOTR_Users()
        {
            //Opening the database
            string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath();

            m_db = new LiteDatabase(sGlobalPath + @"\Userdata.db");

            sUserSalt = "Also users needs salt :)";
        }
Esempio n. 6
0
        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("");
        }
Esempio n. 7
0
        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);
            }
        }
Esempio n. 8
0
        //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);
        }
Esempio n. 9
0
        //Here we actually restart the server
        public void RestartServer()
        {
            MOTR_WebserverObject m_WebObject;

            for (int i = aWebservers.Count - 1; i > -1; i--)
            {
                //Dispose the last server created
                if (aWebservers[i].server != null)
                {
                    aWebservers[i].server.Dispose();
                    aWebservers[i].server = null;
                }
                if (aWebservers[i].serviceFactory != null)
                {
                    aWebservers[i].serviceFactory.Dispose();
                    aWebservers[i].serviceFactory = null;
                }
                if (aWebservers[i].initalServiceFactory != null)
                {
                    aWebservers[i].initalServiceFactory = null;
                }

                //Get the object and remove it from the list
                m_WebObject = aWebservers[i];
                aWebservers.RemoveAt(i);

                //Retrive the port, if option not set retrive it from the last object
                int port = MOTR_Settings.GetNumber("http");
                if (port == 0)
                {
                    port = m_WebObject.LastPortNumber;
                }
                if (m_WebObject.LastSSL)
                {
                    port = MOTR_Settings.GetNumber("https");
                }
                if (port == 0)
                {
                    port = m_WebObject.LastPortNumber;
                }

                //Now create the new webserver with current options
                CreateWebServer(port, m_WebObject.LastPath, m_WebObject.LastSSL, m_WebObject.LastCert, m_WebObject.LastCertPassword);
                m_WebObject = null;
            }
        }
Esempio n. 10
0
        //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);
             * }*/
        }
Esempio n. 11
0
        //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);
        }
Esempio n. 12
0
        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);
        }
Esempio n. 13
0
        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();
            }
        }
Esempio n. 14
0
        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()));
        }
Esempio n. 15
0
        //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("");
                }
            }
        }
Esempio n. 16
0
        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);
                }
            }
        }
Esempio n. 17
0
        //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);
        }
Esempio n. 18
0
/*
 *      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));
        }
Esempio n. 19
0
        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);
        }
Esempio n. 20
0
        protected override void OnTextFrame(string text)
        {
            string jsonText = null;

            //             WebsocketSendClass WSTest2 = new WebsocketSendClass();
            //             WSTest2.command = "Do this thing";
            //             WSTest2.aArray = m_Dirs.GetArray();
            //             WSTest2.count = WSTest2.aArray.Count;
            //             jsonText = fastJSON.JSON.ToJSON(WSTest2);

            //Just for debugging purposes
            //Console.WriteLine("Received: " + text);

            //Every object is linked to this
            //WebSocketCommandClass WSCommand = (WebSocketCommandClass)fastJSON.JSON.ToObject(text);

            //Every object is linked to this
            WebSocketCommandClass WSCommand = new WebSocketCommandClass();

            //Try & catch on the parsing
            try
            {
                dynamic WSTemp = fastJSON.JSON.ToDynamic(text);
                WSCommand.command   = WSTemp.command;
                WSCommand.parameter = WSTemp.parameter;
                //WSCommand.sessionid = WSTemp.sessionid;
            }
            catch (Exception ex)
            {
                _logger.Error(typeof(MOTR_AdminWebsocket), "Admin->Error parsing JSON: " + text + " - Returnstring: " + ex.ToString());
                return;
            }

            //Check if the user is logged in
//            if (!m_Sessions.SessionLoggedIn(WSCommand.sessionid))
//                return;

            //Just temp info
//            _logger.Information(typeof(MOTR_AdminWebsocket), "session: " + WSCommand.sessionid);
            _logger.Information(typeof(MOTR_AdminWebsocket), "command: " + WSCommand.command);

            //This object is used to send info
            WebsocketSendClass WSSend = new WebsocketSendClass();

            //Return the state of the user trying to log in
            if (WSCommand.command == "ISLOGGEDIN")
            {
                //Store the session for later
                sSession = WSCommand.parameter;

                WSSend.command = "LOGGEDIN";
                WSSend.aArray  = new ArrayList();
                WSSend.aArray.Add(m_Admin.IsSessionLoggedIn(sSession));
                WSSend.count = WSSend.aArray.Count;
                jsonText     = fastJSON.JSON.ToJSON(WSSend);
                base.Send(jsonText);
                return;
            }

            //Return a ISLOGGEDIN if seesoin it not set
            if (sSession.Length == 0)
            {
                WSSend.command = "ISLOGGEDIN";
                WSSend.aArray  = new ArrayList();
                WSSend.aArray.Add("You need to sens ISLOGGEDIN first");
                WSSend.count = WSSend.aArray.Count;
                jsonText     = fastJSON.JSON.ToJSON(WSSend);
                base.Send(jsonText);
                return;
            }
            _logger.Information(typeof(MOTR_AdminWebsocket), "Session trying to admin: " + sSession);

            //Check password
            if (WSCommand.command == "LOGIN")
            {
                WSSend.command = "LOGIN";
                WSSend.aArray  = new ArrayList();
                WSSend.aArray.Add(m_Admin.CheckAdminPassword(WSCommand.parameter, sSession));
                WSSend.count = WSSend.aArray.Count;
                jsonText     = fastJSON.JSON.ToJSON(WSSend);
                base.Send(jsonText);
                return;
            }

            //=========================================================================
            //Everything below here is not available if not logged in
            if (!m_Admin.IsSessionLoggedIn(sSession))
            {
                return;
            }

            //Return an array of users
            if (WSCommand.command == "ADDUSER")
            {
                //Add the user
                string[] aInfo     = WSCommand.parameter.Split(',');
                string   sUsername = aInfo[0];
                string   sPassword = aInfo[1];
                bool     bRet      = m_Users.AddUserName(sUsername, sPassword);
                if (!bRet)
                {
                    m_Admin.SetErrorString("Username exists or wrong parameters");
                }

                //Send the userlist
                WSCommand.command = "USERLIST";
            }
            if (WSCommand.command == "CHANGEUSER")
            {
                //Add the user
                string[] aInfo     = WSCommand.parameter.Split(',');
                string   sID       = aInfo[0];
                string   sPassword = aInfo[1];
                int      nID       = Convert.ToInt32(sID);

                WSSend.command = "CHANGEUSER";
                WSSend.aArray  = new ArrayList();
                WSSend.aArray.Add(m_Users.ChangePassword(nID, sPassword));
                WSSend.count = WSSend.aArray.Count;
                jsonText     = fastJSON.JSON.ToJSON(WSSend);
            }
            //Return an array of users
            if (WSCommand.command == "DELETEUSER")
            {
                //Delete the user
                int nID = Convert.ToInt32(WSCommand.parameter);
                m_Users.RemoveUser(nID);

                //Send the userlist back
                WSCommand.command = "USERLIST";
            }

            //Sends the userlist, just names
            if (WSCommand.command == "USERLIST")
            {
                //Send new userlist
                WSSend.command = "USERLIST";
                WSSend.aArray  = m_Users.GetUserArray();
                WSSend.count   = WSSend.aArray.Count;
                jsonText       = fastJSON.JSON.ToJSON(WSSend);
            }

            //Adds a directory to the pathslist
            if (WSCommand.command == "ADMINADDIRECTORY")
            {
                string   sDisplayName, sPath, sUncUser, sUncPass;
                string[] sTmp = WSCommand.parameter.Split(',');

                //Only add if the parameters are correct
                if (sTmp.Length > 2)
                {
                    sDisplayName = sTmp[0];
                    sPath        = sTmp[1];
                    sUncUser     = sTmp[2];
                    sUncPass     = sTmp[3];

                    //Now add the directory
                    m_Dirs.AddDirectory(sDisplayName, sPath, sUncUser, sUncPass);
                }

                //Send directories available
                WSCommand.command = "DIRLIST";
            }

            //Removes a directory and return new dirlist
            if (WSCommand.command == "ADMINREMOVEDIRECTORY")
            {
                //Delete the user
                int nID = Convert.ToInt32(WSCommand.parameter);
                m_Dirs.RemoveDirectory(nID);

                //Send the userlist back
                WSCommand.command = "DIRLIST";
            }

            //Sends paths list
            if (WSCommand.command == "DIRLIST")
            {
                //Send new userlist
                WSSend.command = "DIRLIST";
                WSSend.aArray  = m_Dirs.GetDirsArray();
                WSSend.count   = WSSend.aArray.Count;
                jsonText       = fastJSON.JSON.ToJSON(WSSend);
                //Console.WriteLine("DIRLIST: " + jsonText);
            }

            //Sends drives and network list to the browser
            if (WSCommand.command == "ADMINDRIVES")
            {
                //Send new userlist
                WSSend.command = "ADMINDRIVES";
                WSSend.aArray  = m_Admin.GetDrivesAndNetwork();
                WSSend.count   = WSSend.aArray.Count;
                jsonText       = fastJSON.JSON.ToJSON(WSSend);
                //Console.WriteLine("ADMINDRIVES: " + jsonText);
            }

            //Set the drive we are going to browse
            if (WSCommand.command == "ADMINSETDRIVE")
            {
                m_Admin.SetBasePath(WSCommand.parameter);
                WSCommand.command = "ADMINFILELIST";
            }

            //Set the drive we are going to browse
            if (WSCommand.command == "ADMINSETPATH")
            {
                m_Admin.SetCurrentPath(WSCommand.parameter);
                WSCommand.command = "ADMINFILELIST";
            }

            //Return the filelist based on the current path
            if (WSCommand.command == "ADMINFILELIST")
            {
                //Send new userlist
                WSSend.command = "ADMINFILELIST";
                WSSend.aArray  = m_Admin.GetDirectoryList();
                WSSend.count   = WSSend.aArray.Count;
                jsonText       = fastJSON.JSON.ToJSON(WSSend);
                //Console.WriteLine("ADMINFILELIST: " + jsonText);
            }

            //Set the drive we are going to browse
            if (WSCommand.command == "ADMINCHECKFORTOOLUPDATE")
            {
                //Create return message
                WSSend.command = "ADMINCHECKFORTOOLUPDATE";
                WSSend.aArray  = new ArrayList();

                //Check if the tool is updated
                string sTool         = WSCommand.parameter;
                string sLocalVersion = MOTR_Settings.GetCurrentToolVersion(sTool);
                string sWebVersion   = MOTR_Settings.GetWebsiteToolVersion(sTool);
                if (sLocalVersion != sWebVersion)
                {
                    WSSend.aArray.Add("Updating " + sTool + " to v" + sWebVersion);
                    bool bRet = MOTR_Settings.UpdateTool(sTool, sWebVersion);
                    if (bRet)
                    {
                        WSSend.aArray.Add(sTool + " updated ok");
                    }
                    else
                    {
                        WSSend.aArray.Add(sTool + " failed to update");
                    }
                }
                else
                {
                    WSSend.aArray.Add("Newest version installed for " + sTool);
                }

                //Set the number of items added
                WSSend.count = WSSend.aArray.Count;
                jsonText     = fastJSON.JSON.ToJSON(WSSend);
            }

            //Restarts the server with given ports
            if (WSCommand.command == "ADMINRESTARTSERVER")
            {
                //Get ports available
                string[] ports  = WSCommand.parameter.Split(';');
                int      http   = MOTR_Settings.GetNumber("http");
                int      https  = MOTR_Settings.GetNumber("https");
                bool     bError = false;
                if (ports.Length > 1)
                {
                    //Temp store ports to check if changed
                    int httptemp  = http;
                    int httpstemp = https;
                    http  = Convert.ToInt32(ports[0]);
                    https = Convert.ToInt32(ports[1]);

                    //Check if the ports are available
                    if (httptemp != http)
                    {
                        if (WindowsService.IsPortOpen(http))
                        {
                            m_Admin.SetErrorString("http port is already taken, please choose another available port");
                            bError = true;
                        }
                    }
                    if (httpstemp != https)
                    {
                        if (WindowsService.IsPortOpen(https))
                        {
                            m_Admin.SetErrorString("https port is already taken, please choose another available port");
                            bError = true;
                        }
                    }
                }

                //No error, then we go fishing
                if (!bError)
                {
                    //Store the new ports
                    MOTR_Settings.SetNumber("http", http);
                    MOTR_Settings.SetNumber("https", https);

                    //Restart server
                    OnRestartWebserver(this, EventArgs.Empty);
                }

                //Send response back to server
                WSSend.command = "ADMINRESTARTSERVER";
                WSSend.aArray  = new ArrayList();
                WSSend.aArray.Add(bError);
                WSSend.aArray.Add(http);
                WSSend.aArray.Add(https);
                WSSend.count = WSSend.aArray.Count;
                jsonText     = fastJSON.JSON.ToJSON(WSSend);
            }


            //Send if the jsonText is set
            if (jsonText != null)
            {
                base.Send(jsonText);
            }
            else
            {
                _logger.Information(typeof(MOTR_AdminWebsocket), "Unknown admin command from websocket: " + WSCommand.command);
                WSSend.command = "UNKNOWN";
                WSSend.count   = 2;
                WSSend.aArray  = new ArrayList();
                WSSend.aArray.Add(WSCommand.command);
                WSSend.aArray.Add(WSCommand.parameter);
                jsonText = fastJSON.JSON.ToJSON(WSSend);
                base.Send(jsonText);
            }

            //Check if the admin has errors, send it if nessesary
            if (m_Admin.HasError)
            {
                WSSend.command = "ADMINERRORMESSAGE";
                WSSend.aArray  = new ArrayList();
                WSSend.aArray.Add(m_Admin.GetErrorString());
                WSSend.count = WSSend.count;
                jsonText     = fastJSON.JSON.ToJSON(WSSend);
                base.Send(jsonText);
            }
        }
Esempio n. 21
0
        /// <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();
                }
            }
        }