public ActionResult Index() { using (var context = new OpenTrackerDbContext()) { var _torrents = (from t in context.torrents join t2 in context.categories on t.categoryid equals t2.id join t3 in context.comments on t.id equals t3.torrentid into comment join t4 in context.peers on t.id equals t4.torrentid into peer join t5 in context.users on t.owner equals t5.id orderby t.id descending select new TorrentModel { TorrentId = t.id, InfoHash = t.info_hash, TorrentName = t.torrentname, Description = t.description, DescriptionSmall = t.description_small, Added = t.added, Size = (long)t.size, FileCount = t.numfiles, CategoryId = t2.id, CategoryImage = t2.image, CommentCount = comment.Count(), Seeders = peer.Count(count => count.left == 0), Leechers = peer.Count(count => count.left > 0), Uploader = t5.username }).ToList(); return(View(_torrents)); } }
/// <summary> /// /// </summary> public AccountInformation() { if (!HttpContext.Current.User.Identity.IsAuthenticated) { HttpContext.Current.Response.Redirect("/account/logout/"); return; } var id = ((FormsIdentity)HttpContext.Current.User.Identity).Ticket; this.UserId = Convert.ToInt32(id.UserData.Split(';')[1]); using (var context = new OpenTrackerDbContext()) { var retrieveUser = (from u in context.users where u.id == UserId select new { Class = u.@class, Uploaded = u.uploaded, Downloaded = u.downloaded }).Take(1).FirstOrDefault(); if (retrieveUser == null) { HttpContext.Current.Response.Redirect("/"); return; } this.Class = (int)retrieveUser.Class; this.Uploaded = (long)retrieveUser.Uploaded; this.Downloaded = (long)retrieveUser.Downloaded; } }
public string Imdb(string title) { title = title.Replace(@"C:\fakepath\", string.Empty); using (var client = new WebClient().OpenRead(string.Format("http://www.imdbapi.com/?i=&t={0}", title))) { if (client == null) { return(title); } using (var reader = new StreamReader(client)) { var result = reader.ReadToEnd(); var deserializedImdb = JsonConvert.DeserializeObject <ImdbJson>(result); using (var webClient = new WebClient()) { var tempImdbPath = Path.Combine( TrackerSettings.IMDB_DIRECTORY, string.Format("{0}.jpg", deserializedImdb.ID) ); if (deserializedImdb.Poster != "N/A") { using (var context = new OpenTrackerDbContext()) { var imdbExist = (from i in context.imdb where i.imdbid == deserializedImdb.ID select i).Take(1).FirstOrDefault(); if (imdbExist != null) { return(result.Replace(deserializedImdb.Poster, imdbExist.imgur)); } webClient.DownloadFile(deserializedImdb.Poster, tempImdbPath); var imgur = PostToImgur(tempImdbPath, TrackerSettings.IMGUR_API_KEY); var deserializedImgur = JObject.Parse(imgur); var imgurLink = (string)deserializedImgur.SelectToken("upload.links.original"); var _imdb = new imdb { imdbid = deserializedImdb.ID, imgur = imgurLink }; context.AddToimdb(_imdb); context.SaveChanges(); System.IO.File.Delete(tempImdbPath); return(result.Replace(deserializedImdb.Poster, imgurLink)); } } return(result.Replace(deserializedImdb.Poster, string.Empty)); } } } }
/// <summary> /// /// </summary> /// <param name="torrentid"></param> /// <returns></returns> public JsonResult RetrieveTorrentFiles(int torrentid) { using (var context = new OpenTrackerDbContext()) { var _files = (context.torrents_files .Where(f => f.torrentid == torrentid) .OrderBy(f => f.filename)) .Select(file => new { file.filename, file.filesize }) .ToList(); return(Json(new { files = _files }, JsonRequestBehavior.AllowGet)); } }
public void DownloadTorrent(int?torrentId) { using (var db = new OpenTrackerDbContext()) { var torrentExist = (from t in db.torrents where t.id == torrentId select t).Take(1).FirstOrDefault(); if (torrentExist == null) { Response.Write("Torrent not found."); return; } var file = string.Format("{0}.torrent", torrentExist.id); var finalTorrentPath = Path.Combine(TrackerSettings.TORRENT_DIRECTORY, file); var dictionary = (BEncodedDictionary)BEncodedValue.Decode(System.IO.File.ReadAllBytes(finalTorrentPath)); var userInformation = (from u in db.users where u.username == User.Identity.Name select u).Take(1).FirstOrDefault(); if (userInformation == null) { Response.Write("This shouldn't happen."); return; } var announceUrl = string.Format("{0}/announce/{1}", TrackerSettings.BASE_URL, userInformation.passkey); var editor = new TorrentEditor(dictionary) { Announce = announceUrl, Comment = "created by Open-Tracker.org" }; var privateTorrent = editor.ToDictionary().Encode(); var response = ControllerContext.HttpContext.Response; response.ClearHeaders(); response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}-{1}.torrent", TrackerSettings.TORRENT_NAME_PREFIX, Url.Encode(torrentExist.torrentname))); response.AddHeader("Content-Type", "application/x-bittorrent"); response.BinaryWrite(privateTorrent); response.End(); } }
/// <summary> /// /// </summary> /// <param name="username"></param> /// <param name="passhash"></param> /// <returns></returns> public int ValidateUser(string username, string passhash) { using (var context = new OpenTrackerDbContext()) { var retrieveTempUser = (from t in context.users where t.username == username && t.activated == 1 select t).Take(1).FirstOrDefault(); if (retrieveTempUser == null) { return(0); } if (BCrypt.CheckPassword(passhash, retrieveTempUser.passhash)) { return((int)retrieveTempUser.id); } } return(0); }
public ActionResult Details(int id) { using (var context = new OpenTrackerDbContext()) { var _torrent = (from t in context.torrents join t2 in context.categories on t.categoryid equals t2.id join t3 in context.users on t.owner equals t3.id join t4 in context.peers on t.id equals t4.torrentid into peer where t.id == id select new TorrentModel { TorrentId = t.id, InfoHash = t.info_hash, TorrentName = t.torrentname, Description = t.description, DescriptionSmall = t.description_small, Added = t.added, Size = (long)t.size, FileCount = t.numfiles, CategoryName = t2.name, Seeders = peer.Count(count => count.left == 0), Leechers = peer.Count(count => count.left > 0), Uploader = t3.username }).Take(1).FirstOrDefault(); var comments = (from c in context.comments join u in context.users on c.userid equals u.id where c.torrentid == id select new CommentModel { CommentId = c.id, CommentAuthor = u.username, CommentContent = c.comment }).ToList(); return(View(new BrowseModel { TorrentModel = _torrent, CommentModel = comments })); } }
public override void OnAuthorization(AuthorizationContext filterContext) { if (HttpContext.Current.User.Identity.IsAuthenticated) { using (var context = new OpenTrackerDbContext()) { var crntUser = new AccountInformation(); var retrieveTempUser = (from u in context.users where crntUser.Class >= (decimal)AccountValidation.Class.Uploader && u.id == crntUser.UserId select u).Take(1).FirstOrDefault(); if (retrieveTempUser != null) return; } } HttpContext.Current.Response.Redirect("/account/login?returnUrl=" + HttpContext.Current.Request.Path); return; }
public override void OnAuthorization(AuthorizationContext filterContext) { if (HttpContext.Current.User.Identity.IsAuthenticated) { using (var context = new OpenTrackerDbContext()) { var crntUser = new AccountInformation(); var retrieveTempUser = (from u in context.users where crntUser.Class >= (decimal)AccountValidation.Class.Uploader && u.id == crntUser.UserId select u).Take(1).FirstOrDefault(); if (retrieveTempUser != null) { return; } } } HttpContext.Current.Response.Redirect("/account/login?returnUrl=" + HttpContext.Current.Request.Path); return; }
/// <summary> /// /// </summary> /// <param name="q"></param> /// <param name="limit"></param> /// <param name="timespamp"></param> /// <returns></returns> public string AutoSuggest(string q, int?limit, long?timespamp) { using (var context = new OpenTrackerDbContext()) { var _torrents = (context.torrents .Where(f => f.torrentname.Contains(q)) .OrderBy(f => f.torrentname)) .Select(torrent => new { torrent.id, torrent.torrentname }) .ToList(); // return Json(new { torrents = _torrents }, JsonRequestBehavior.AllowGet); var bewlder = new StringBuilder(); foreach (var torrent in _torrents) { bewlder.Append(torrent.torrentname + Environment.NewLine); } return(bewlder.ToString()); } }
/// <summary> /// /// </summary> /// <param name="hash"></param> /// <returns></returns> public ActionResult Activate(string hash) { using (var context = new OpenTrackerDbContext()) { var checkActivation = (from u in context.users where u.activatesecret == hash select u).Take(1).FirstOrDefault(); if (checkActivation == null) { return(RedirectToAction("login", "account", new { message = "activationfail" })); } if (checkActivation.activated == 1) { return(RedirectToAction("login", "account", new { message = "activateexist" })); } checkActivation.activated = 1; checkActivation.@class = 4; checkActivation.uploaded = TrackerSettings.DEFAULT_UPLOADED_VALUE; context.SaveChanges(); return(RedirectToAction("login", "account", new { message = "activationsuccess" })); } }
/// <summary> /// /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="email"></param> /// <returns></returns> public AccountCreateStatus CreateUser(string userName, string password, string email) { if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password"); if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email"); using (var context = new OpenTrackerDbContext()) { var checkUsernameAlreadyExist = (from u in context.users where u.username == userName select u).Count(); if (checkUsernameAlreadyExist != 0) return AccountCreateStatus.DuplicateUserName; var checkEmailAlreadyExist = (from u in context.users where u.email == email select u).Count(); if (checkEmailAlreadyExist != 0) return AccountCreateStatus.DuplicateEmail; var activateSecret = AccountValidation.MD5(string.Format(password)); var newUser = new users { username = userName, passhash = password, email = email, passkey = AccountValidation.MD5(password), activatesecret = activateSecret }; context.AddTousers(newUser); context.SaveChanges(); var client = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("*****@*****.**", "lol123123"), EnableSsl = true }; using (var msg = new MailMessage()) { var BASE_URL = TrackerSettings.BASE_URL .Replace("http://", string.Empty) .Replace("https://", string.Empty); msg.From = new MailAddress("*****@*****.**"); msg.Subject = string.Format("{0} user registration confirmation", BASE_URL); var bewlder = new StringBuilder(); bewlder.AppendFormat( @" You have requested a new user account on {0} and you have specified this address ({1}) as user contact. If you did not do this, please ignore this email. The person who entered your email address had the IP address {2}. Please do not reply. To confirm your user registration, you have to follow this link: http://{0}/account/activate/{3}/ After you do this, you will be able to use your new account. If you fail to do this, you account will be deleted within a few days. We urge you to read the RULES and FAQ before you start using {0}. ", BASE_URL, email, HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], activateSecret ); msg.Body = bewlder.ToString(); msg.To.Add(new MailAddress(email)); client.Send(msg); return AccountCreateStatus.Success; } } }
/// <summary> /// /// </summary> /// <param name="username"></param> /// <param name="passhash"></param> /// <returns></returns> public int ValidateUser(string username, string passhash) { using (var context = new OpenTrackerDbContext()) { var retrieveTempUser = (from t in context.users where t.username == username && t.activated == 1 select t).Take(1).FirstOrDefault(); if (retrieveTempUser == null) return 0; if (BCrypt.CheckPassword(passhash, retrieveTempUser.passhash)) return (int) retrieveTempUser.id; } return 0; }
public ActionResult Index(UploadModel uploadModel) { if (!ModelState.IsValid) { /* * var errors = ModelState * .Where(x => x.Value.Errors.Count > 0) * .Select(x => new { x.Key, x.Value.Errors }) * .ToArray(); */ foreach (var _error in GetModelStateErrorsAsList(this.ModelState)) { ModelState.AddModelError("", _error.ErrorMessage); } return(View(uploadModel)); } Torrent t; try { t = Torrent.Load(uploadModel.TorrentFile.InputStream); } catch (Exception) { ModelState.AddModelError("", "Invalid .torrent file."); return(View(uploadModel)); } if (!t.IsPrivate) { ModelState.AddModelError("", "The torrent file needs to be marked as \"Private\" when you create the torrent."); return(View(uploadModel)); } var TORRENT_DIR = TrackerSettings.TORRENT_DIRECTORY; var NFO_DIR = TrackerSettings.NFO_DIRECTORY; using (var db = new OpenTrackerDbContext()) { // var _torrentFilename = uploadModel.TorrentFile.FileName; if (!string.IsNullOrEmpty(uploadModel.TorrentName)) { _torrentFilename = uploadModel.TorrentName; } var cleanTorentFilename = Regex.Replace(_torrentFilename, "[^A-Za-z0-9]", string.Empty); var finalTorrentFilename = string.Format("TEMP-{0}-{1}", DateTime.Now.Ticks, cleanTorentFilename); var _torrentPath = Path.Combine(TORRENT_DIR, string.Format("{0}.torrent", finalTorrentFilename)); var _nfoPath = Path.Combine(NFO_DIR, string.Format("{0}.nfo", finalTorrentFilename)); uploadModel.NFO.SaveAs(_nfoPath); uploadModel.TorrentFile.SaveAs(_torrentPath); var infoHash = t.InfoHash.ToString().Replace("-", string.Empty); var torrentSize = t.Files.Sum(file => file.Length); var numfiles = t.Files.Count(); var client = t.CreatedBy; var torrent = new torrents { categoryid = uploadModel.CategoryId, info_hash = infoHash, torrentname = _torrentFilename.Replace(".torrent", string.Empty), description = uploadModel.Description, description_small = uploadModel.SmallDescription, added = (int)Unix.ConvertToUnixTimestamp(DateTime.UtcNow), numfiles = numfiles, size = torrentSize, client_created_by = client, owner = new Core.Account.AccountInformation().UserId }; db.AddTotorrents(torrent); db.SaveChanges(); var _torrent = (from tor in db.torrents where tor.info_hash == infoHash select tor) .Select(tor => new { tor.info_hash, tor.id }) .Take(1) .FirstOrDefault(); if (_torrent == null) { // TODO: error logging etc. here } else { System.IO.File.Move(_torrentPath, Path.Combine(TORRENT_DIR, string.Format("{0}.torrent", _torrent.id))); System.IO.File.Move(_nfoPath, Path.Combine(NFO_DIR, string.Format("{0}.nfo", _torrent.id))); var files = t.Files; foreach (var tFile in files.Select(torrentFile => new torrents_files { torrentid = torrent.id, filename = torrentFile.FullPath, filesize = torrentFile.Length }).OrderBy(torrentFile => torrentFile.filename)) { db.AddTotorrents_files(tFile); } db.SaveChanges(); } return(RedirectToAction("Index", "Browse")); } }
// // GET: /Announce/Announce/ // GET: /announce/123af0c917876f6d4711654b2293895f public ActionResult Announce(AnnounceModel announceModel) { if (!announceModel.IsValidRequest()) { return(new BTErrorResult("Invalid request (see specification: http://bit.ly/bcYmSu)")); } if (!Regex.IsMatch(announceModel.Passkey, "[0-9a-fA-F]{32}")) { return(new BTErrorResult("Invalid passkey.")); } if (BLACKLIST_PORTS && IsPortBlackListed(Convert.ToInt32(announceModel.port))) { return(new BTErrorResult(string.Format("Port {0} is blacklisted", announceModel.port))); } try { using (var context = new OpenTrackerDbContext()) { var crntUser = (from u in context.users where u.passkey == announceModel.Passkey select u).Take(1).FirstOrDefault(); if (crntUser == null) { return(new BTErrorResult(string.Format("Unknown passkey. Please re-download the torrent from {0}.", TrackerSettings.BASE_URL))); } if (crntUser.activated == 0) { return(new BTErrorResult("Permission denied, you\'re not activated.")); } var seeder = false; if (announceModel.left == 0) { seeder = true; } // Entity Framework does not support BINARY keys var EncodedPeerId = Convert.ToBase64String(Encoding.ASCII.GetBytes(announceModel.peer_id)); var EncodedInfoHash = BEncoder.FormatUrlInfoHash(); var torrentExist = (from t in context.torrents where t.info_hash == EncodedInfoHash select t).Take(1).FirstOrDefault(); if (torrentExist == null) { return(new BTErrorResult("Torrent not registered with this tracker.")); } var peerAlreadyExist = (from t in context.peers where t.torrentid == torrentExist.id && t.peer_id == EncodedPeerId && t.passkey == announceModel.Passkey select t).Take(1); var existingPeerCount = peerAlreadyExist.Count(); peers p; if (existingPeerCount == 1) { p = peerAlreadyExist.First(); } else { var connectionLimit = (from t in context.peers where t.torrentid == torrentExist.id && t.passkey == announceModel.Passkey select t).Count(); if (connectionLimit >= 1 && !seeder) { return(new BTErrorResult("Connection limit exceeded! " + "You may only leech from one location at a time.")); } if (connectionLimit >= 3 && seeder) { return(new BTErrorResult("Connection limit exceeded.")); } if (announceModel.left > 0 && crntUser.@class < (decimal)AccountValidation.Class.Administrator) { var epoch = Unix.ConvertToUnixTimestamp(DateTime.UtcNow); var elapsed = Math.Floor((epoch - torrentExist.added) / 3600); var uploadedGigs = crntUser.uploaded / (1024 * 1024 * 1024); var ratio = ((crntUser.downloaded > 0) ? (crntUser.uploaded / crntUser.downloaded) : 1); int wait; if (ratio < (decimal)0.5 || uploadedGigs < 5) { wait = 48; } else if (ratio < (decimal)0.65 || uploadedGigs < (decimal)6.5) { wait = 24; } else if (ratio < (decimal)0.8 || uploadedGigs < 8) { wait = 12; } else if (ratio < (decimal)0.95 || uploadedGigs < (decimal)9.5) { wait = 6; } else { wait = 0; } if (elapsed < wait) { return(new BTErrorResult(string.Format("Not authorized (wait {0}h) - READ THE FAQ!", (wait - elapsed)))); } } p = new peers { torrentid = torrentExist.id, peer_id = EncodedPeerId, userid = crntUser.id, passkey = announceModel.Passkey, useragent = Request.UserAgent }; } var remoteHost = Request.ServerVariables["REMOTE_HOST"]; var ip = !string.IsNullOrEmpty(announceModel.ip) ? announceModel.ip : remoteHost; if (CHECK_CONNECTABLE) { p.connectable = IsConnectable(ip, Convert.ToInt32(announceModel.port)) ? 1 : 0; } if (announceModel.left != null) { p.left = (decimal)announceModel.left; } p.port = Convert.ToInt32(announceModel.port); p.ip = ip; p.seeding = seeder ? 1 : 0; if (existingPeerCount == 0) { context.AddTopeers(p); } else { if (crntUser.@class < (decimal)AccountValidation.Class.Administrator) { var nonUpdatedPeer = peerAlreadyExist.First(); var thisUploaded = (announceModel.uploaded - nonUpdatedPeer.uploaded); var thisDownloaded = (announceModel.downloaded - nonUpdatedPeer.downloaded); p.uploaded += (decimal)thisUploaded; p.downloaded += (decimal)thisDownloaded; if (thisUploaded > 0) { crntUser.uploaded = (crntUser.uploaded + Convert.ToInt64(thisUploaded)); } if (thisDownloaded > 0) { crntUser.downloaded = (crntUser.downloaded + Convert.ToInt64(thisDownloaded)); } } if (announceModel.Event == "completed") { torrentExist.snatches = torrentExist.snatches + 1; // torrentExist.snatches++; } } context.SaveChanges(); if (announceModel.Event == "stopped") { var removePeer = (from pr in context.peers where pr.torrentid == torrentExist.id && pr.peer_id == EncodedPeerId select pr).Take(1).FirstOrDefault(); context.peers.DeleteObject(removePeer); context.SaveChanges(); var announceResultStop = new AnnounceResult { Interval = ANNOUNCE_INTERVAL }; return(announceResultStop); } var announceResult = new AnnounceResult { Interval = ANNOUNCE_INTERVAL }; var existingPeers = (from t in context.peers where t.torrentid == torrentExist.id select t).ToList(); foreach (var peer in existingPeers) { announceResult.AddPeer(peer.peer_id, peer.ip, peer.port); } return(announceResult); } } catch (Exception) { return(new BTErrorResult("Database unavailable")); } }
/// <summary> /// /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="email"></param> /// <returns></returns> public AccountCreateStatus CreateUser(string userName, string password, string email) { if (String.IsNullOrEmpty(userName)) { throw new ArgumentException("Value cannot be null or empty.", "userName"); } if (String.IsNullOrEmpty(password)) { throw new ArgumentException("Value cannot be null or empty.", "password"); } if (String.IsNullOrEmpty(email)) { throw new ArgumentException("Value cannot be null or empty.", "email"); } using (var context = new OpenTrackerDbContext()) { var checkUsernameAlreadyExist = (from u in context.users where u.username == userName select u).Count(); if (checkUsernameAlreadyExist != 0) { return(AccountCreateStatus.DuplicateUserName); } var checkEmailAlreadyExist = (from u in context.users where u.email == email select u).Count(); if (checkEmailAlreadyExist != 0) { return(AccountCreateStatus.DuplicateEmail); } var activateSecret = AccountValidation.MD5(string.Format(password)); var newUser = new users { username = userName, passhash = password, email = email, passkey = AccountValidation.MD5(password), activatesecret = activateSecret }; context.AddTousers(newUser); context.SaveChanges(); var client = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("*****@*****.**", "lol123123"), EnableSsl = true }; using (var msg = new MailMessage()) { var BASE_URL = TrackerSettings.BASE_URL .Replace("http://", string.Empty) .Replace("https://", string.Empty); msg.From = new MailAddress("*****@*****.**"); msg.Subject = string.Format("{0} user registration confirmation", BASE_URL); var bewlder = new StringBuilder(); bewlder.AppendFormat( @" You have requested a new user account on {0} and you have specified this address ({1}) as user contact. If you did not do this, please ignore this email. The person who entered your email address had the IP address {2}. Please do not reply. To confirm your user registration, you have to follow this link: http://{0}/account/activate/{3}/ After you do this, you will be able to use your new account. If you fail to do this, you account will be deleted within a few days. We urge you to read the RULES and FAQ before you start using {0}. ", BASE_URL, email, HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], activateSecret ); msg.Body = bewlder.ToString(); msg.To.Add(new MailAddress(email)); client.Send(msg); return(AccountCreateStatus.Success); } } }