コード例 #1
0
        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));
                    }
                }
            }
        }
コード例 #2
0
        /// <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" }));
            }
        }
コード例 #3
0
        //
        // 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"));
            }
        }
コード例 #4
0
        /// <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);
                }
            }
        }
コード例 #5
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"));
            }
        }
コード例 #6
0
        /// <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;
                }
            }
        }