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); } }
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(); return View(_torrent); } }
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="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="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); } }
// // 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"); } }