Exemple #1
0
        public void Run(AuthObj auth, string twitterName) //Executes the task parsed by the ServerTask class
        {
            this.auth  = auth;
            webHandler = new WebHandler(auth);
            //Sets the limits such that we do not exceed the limits
            LimitHelper.Instance(auth).InitPropertises(new WebHandler(auth).TwitterGetRequest <Limit>(TwitterRequestBuilder.BuildStartupRequest()));
            User user = webHandler.TwitterGetRequest <User>(TwitterRequestBuilder.BuildRequest(RequestType.user, auth, "screen_name=" + twitterName)); //Used for getting the users political value

            //Analyse the tweets of the user and post the result to the database. Does not use linking because of this is the user we need to ananlyse
            TweetRetriever.Instance.GetTweetsFromUserAndAnalyse(user, auth, CheckIfResultExistOnDB, ClassifyTweet, PostResultToDB);
            //Finds the posted users recordId and assigns it to the global userRecordId variable to be used in the CheckIfResultExistOnDBAndLink and PostResultToDBAndLink
            if (!GetUsersRecordIdOnDb(user, ref userRecordId))
            {
                Log.Error("Could not find the posted user, something is wrong!");
                return;
            }

            //Gets the friends for the user
            var friends = FriendsRetriever.Instance.GetFriends(user, auth);

            Log.Debug("Following " + friends.Users.Count + " users");

            //Analyse the tweets of each friend and post the result to the database, then link the users result to the global userRecordId
            TweetRetriever.Instance.GetTweetsFromFriendsAndAnalyse(friends, auth, CheckIfResultExistOnDBAndLink, ClassifyTweet, PostResultToDBAndLink);

            //Finalizes the user by informing the database that the user has been proccessed.
            FinalizeUser();
            Log.Debug("Done task with id " + auth.RequestID + "!!!");
        }
        /// <summary>
        /// The method to retrieve tweets from a specific user.
        /// This method can retrieve as few tweets as 200 or as many as the constant TWEETS_TO_RETRIEVE (max.  3200)
        /// </summary>
        /// <param name="user">The user</param>
        /// <param name="auth">The auth object</param>
        /// <returns>A list of tweet posted by the user</returns>
        private List <Tweet> RetrieveTweets(User user, AuthObj auth)
        {
            List <Tweet> tweetList = new List <Tweet>();
            List <Tweet> tempList  = new List <Tweet>();

            if (!user.IsProtected)
            {
                long lastTweetID = 0;
                tempList.AddRange(new WebHandler(auth).TwitterGetRequest <List <Tweet> >(TwitterRequestBuilder.BuildRequest(RequestType.tweets, auth, "user_id=" + user.Id, "count=200")));
                if (tempList.Count != 0)
                {
                    lastTweetID = tempList.ElementAt(tempList.Count - 1).Id;
                    tweetList.AddRange(tempList.Where(x => !tweetList.Contains(x)));

                    while (tweetList.Count < Constants.TWEETS_TO_RETRIEVE)
                    {
                        tempList.AddRange(new WebHandler(auth).TwitterGetRequest <List <Tweet> >(TwitterRequestBuilder.BuildRequest(RequestType.tweets, auth, "user_id=" + user.Id, "count=200", "max_id=" + lastTweetID)));

                        if (tempList.Count == 0 || tempList.ElementAt(tempList.Count - 1).Id == lastTweetID)
                        {
                            break;
                        }

                        lastTweetID = tempList.ElementAt(tempList.Count - 1).Id;
                        tweetList.AddRange(tempList.Where(x => !tweetList.Contains(x)));
                    }
                }
            }

            tempList = null;

            return(tweetList);
        }
Exemple #3
0
 private void PassAuth()
 {
     if (access_token.Length > 0 || Login.Length == 0 || Password.Length == 0)
     {
         return;
     }
     access_token = "";
     try
     {
         Web w = new Web("https://o2.mail.ru/token");
         Dictionary <String, String> PA = new Dictionary <String, String>();
         PA.Add("client_id", "gamecenter.mail.ru");
         PA.Add("grant_type", "password");
         PA.Add("username", Login);
         PA.Add("password", Password);
         w.Post(PA);
         AuthObj obj = JsonConvert.DeserializeObject <AuthObj>(w.response);
         access_token = obj.access_token;
         if (access_token.Length > 0)
         {
             LTA.UpdateToken(obj.refresh_token, DateTime.Now.AddSeconds(Int32.Parse(obj.expires_in)).ToString(), DbId);
         }
     }
     catch { access_token = ""; }
     return;
 }
        public HttpResponseMessage Authenticate([FromBody] AuthObj obj)
        {
            bool isAuthenticated = BLPlayer.Authenticate(obj);

            if (!isAuthenticated)
            {
                return(Request.CreateResponse <bool>(HttpStatusCode.Forbidden, false));
            }
            else
            {
                IDatabase  db  = DalFactory.CreateDatabase();
                IPlayerDao dao = DalFactory.CreatePlayerDao(db);



                var player = dao.FindByNickname(obj.Nickname);

                var token = Authentication.getInstance().newAuthentication(obj.Nickname);

                ResponseObject r = new ResponseObject(token.Token, player);

                return(Request.CreateResponse <ResponseObject>(HttpStatusCode.Created, r));
                //return new HttpResponseMessage(HttpStatusCode.OK);
            }
        }
Exemple #5
0
        public async Task Authenticate(string nickname, string password)
        {
            HttpClient client = new HttpClient();
            AuthObj    obj    = new AuthObj(nickname, password);
            string     json   = JsonConvert.SerializeObject(obj);

            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(BASE_URL + "api/players/auth", httpContent);

            if (response.IsSuccessStatusCode)
            {
                string val = await response.Content.ReadAsStringAsync();

                token = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseObject>(val);
                if (token.Player.isAdmin)
                {
                    isAuthenticated = true;
                    GetPlayerData(nickname);
                }
                else
                {
                    isAuthenticated = false;
                }
                CheckIfLoggedIn(currentTab);
            }
            else
            {
                isAuthenticated = false;
            }
        }
Exemple #6
0
        /// <summary>
        /// Method used to update the words based on a set of pol users
        /// </summary>
        /// <param name="users">The pol users</param>
        /// <param name="auth">The auth object</param>
        public void UpdateWords(List <PolUserObj> users, AuthObj auth)
        {
            Dictionary <PolUserObj, List <Tweet> > usersAndTweets = GetTweets(users, auth);
            Dictionary <string, UncommonWordObj>   returnList     = DetermineWords(usersAndTweets);

            FileHelper.WriteObjectToFile("WordsTest", returnList.Values);
        }
Exemple #7
0
 private void btnUserData_Click(object sender, EventArgs e)
 {
     byte [] data = new byte[16];
     for (byte i = 0; i < 16; ++i)
     {
         data[i] = AuthObj.GetData(i);
     }
 }
Exemple #8
0
        public IActionResult Post([FromBody] AuthObj value)
        {
            var a = new JsonResult(new RedirectObj()
            {
                RedirectTo = $"http://localhost:4201/#/ready/{value.Account}"
            });

            return(a);
        }
        private void frmInit_Load(object sender, EventArgs e)
        {
            cboMode.Items.Add("Registr-code Mode");
            cboMode.Items.Add("Account Mode");
            cboMode.SelectedIndex = 0;

            frmMain.AuthObj = this.AuthObj;
            this.Text       = "VLM--" + AuthObj.GetVersion();
            AuthObj.Initialize("0F3C6EC9-7089-4BB2-B308-508E90A2995E");//product number
        }
Exemple #10
0
        private void btnProductData_Click(object sender, EventArgs e)
        {
            ushort size = AuthObj.GetProductDataSize();

            byte [] data = new byte[size];
            for (ushort i = 0; i < size; ++i)
            {
                data[i] = AuthObj.GetProductData(i);
            }
        }
Exemple #11
0
        /// <summary>
        /// Helper method for both GetTweetsFromFriendsAndAnalyse and GetTweetsFromFriends.
        /// </summary>
        /// <param name="friends">The friends of an user </param>
        /// <param name="auth">The auth object</param>
        /// <param name="retrieveMethod">Method to retrieve the tweets</param>
        /// <returns>A list of tweets from the friends</returns>
        private List <Tweet> GetTweetsFromFriendsHelper(Friends friends, AuthObj apiKey, Func <User, List <Tweet> > retrieveMethod)
        {
            List <Tweet> tweetList = new List <Tweet>();
            List <Task <List <Tweet> > >  runningTasks = new List <Task <List <Tweet> > >();
            List <Task <List <Tweet> > >  taskList     = new List <Task <List <Tweet> > >();
            Queue <Task <List <Tweet> > > taskQueue    = new Queue <Task <List <Tweet> > >();

            foreach (User user in friends.Users)
            {
                Task <List <Tweet> > task = new Task <List <Tweet> >(() => retrieveMethod(user));
                taskQueue.Enqueue(task);
            }

            friends = null;

            while (taskQueue.Count != 0)
            {
                //Startup process of starting 3 tasks
                if (taskList.Count < 3)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (taskQueue.Count != 0)
                        {
                            var task = taskQueue.Dequeue();
                            task.Start();
                            runningTasks.Add(task);
                            taskList.Add(task);
                        }
                    }
                }
                else //Just start a new task when one finishes
                {
                    int index = Task.WaitAny(runningTasks.ToArray(), -1);
                    runningTasks.RemoveAt(index);
                    var task = taskQueue.Dequeue();
                    task.Start();
                    runningTasks.Add(task);
                    taskList.Add(task);
                }
            }
            taskQueue = null;

            Task.WaitAll(taskList.ToArray());
            foreach (var item in taskList)
            {
                tweetList.AddRange(item.Result);
            }

            taskList     = null;
            runningTasks = null;

            return(tweetList);
        }
Exemple #12
0
        /// <summary>
        /// Helper method, that is used by both GetTweetsFromUser and GetTweetsFromUserAndAnalyse
        /// </summary>
        /// <param name="user">The user</param>
        /// <param name="auth">The auth object</param>
        /// <param name="retrieveMethod">Method to retrieve the tweets</param>
        /// <returns>A list of tweets a user has posted</returns>
        private List <Tweet> GetTweetsFromUserHelper(User user, AuthObj auth, Func <List <Tweet> > retrieveMethod)
        {
            List <Tweet>         tweetList = new List <Tweet>();
            Task <List <Tweet> > task      = new Task <List <Tweet> >(() => retrieveMethod());

            task.Start();
            task.Wait();
            tweetList.AddRange(task.Result);

            return(tweetList);
        }
Exemple #13
0
 /// <summary>
 /// Returns true if all the needed values for the auth obj is there
 /// Then it assigns the authobj the values
 /// So if this method returns true, the out has some value, else it is null
 /// </summary>
 /// <param name="auth">The auth object</param>
 /// <returns>True if the auth variable was assigned</returns>
 public bool GetAuthObj(out AuthObj auth)
 {
     if (string.IsNullOrWhiteSpace(Token) || string.IsNullOrWhiteSpace(Secret) || string.IsNullOrWhiteSpace(Name) || string.IsNullOrWhiteSpace(RequesterName))
     {
         auth = null;
         return(false);
     }
     else
     {
         auth = new AuthObj(Token, Secret, Name, RequestID, RequesterName);
         return(true);
     }
 }
        private void btnPay_Click(object sender, EventArgs e)
        {
            short days  = 0;
            short point = 0;

            if (0 == AuthObj.AddTime(txtCard.Text, txtUser.Text, txtSuper.Text, out days, out point))
            {
                lblRet3.Text = "Renewing Succeeded days:" + days.ToString() + "points:" + point.ToString();
            }
            else
            {
                lblRet3.Text = "Renewing Failed";
            }
        }
        private void btnTest_Click(object sender, EventArgs e)
        {
            int ret = AuthObj.Auth("0F3C6EC9-7089-4BB2-B308-508E90A2995E");

            if (0 == ret)
            {
                Hide();
                frmMain.ShowDialog();
                Close();
            }
            else
            {
                lblRet.Text = "The Test-card is disabled";
            }
        }
 /// <summary>
 /// Returns the user's friends by delegating the work to the private method with either the user's id or screen name
 /// depending upon which one is present in the user object.
 /// </summary>
 /// <param name="user">The user</param>
 /// <param name="auth">The auth object</param>
 /// <returns>A Friends object</returns>
 public Friends GetFriends(User user, AuthObj auth)
 {
     if (user.Id != 0)
     {
         return(GetFriends("user_id=" + user.Id, auth));
     }
     else if (string.IsNullOrWhiteSpace(user.Name))
     {
         return(GetFriends("screen_name=" + user.Name, auth));
     }
     else
     {
         return(new Friends());
     }
 }
        private void btnRegister_Click(object sender, EventArgs e)
        {
            Byte  type  = 0; //user type 0~15
            Byte  bind  = 0; //
            Byte  multi = 1; //channel amount, 1~200
            short point = 0; //point, 0~8000

            if (0 == AuthObj.UserRegister(txtName.Text, txtPassword.Text, type, bind, multi, point))
            {
                LblRet2.Text = "Register Succeeded";
            }
            else
            {
                LblRet2.Text = "Register Failed";
            }
        }
        /// <summary>
        /// Builds a request using the request type to determine which url to use.
        /// </summary>
        /// <param name="requestType">The request type</param>
        /// <param name="auth">The auth object</param>
        /// <param name="parameters">The parameters of the request</param>
        /// <returns>The request url object</returns>
        public static RequestUrlObject BuildRequest(RequestType requestType, AuthObj auth, params string[] parameters)
        {
            RequestUrlObject result = Build(requestType, parameters);

            //Checks if the worker is allowed to make the request
            if (CheckIfAllowedToMakeRequestOrSleep(requestType, ref result, auth, parameters))
            {
                /*Because we need to make sure after wakeup that we have a new request pool and thus we recursly call build.
                 * Then when we have the result, we can just return it, if we do not then the request would subtract 2 from the pool*/
                return(result);
            }

            //Subtracts one from the pool of request the worker is allowed to make.
            LimitHelper.Instance(auth).SubtractFrom(requestType);

            return(result);
        }
        private void btnAuth_Click(object sender, EventArgs e)
        {
            int ret = 0;

            if (0 == cboMode.SelectedIndex)
            {
                ret = AuthObj.Auth(txtAcc.Text);
            }
            else
            {
                ret = AuthObj.UserAuth(txtAcc.Text, txtPwd.Text);
            }

            switch (ret)
            {
            case 0:
                Hide();
                frmMain.ShowDialog();
                Close();
                break;

            case -1:
                lblRet.Text = "The Registr-code is Invalid";
                break;

            case -2:
                lblRet.Text = "The Registr-code is disabled";
                break;

            case -3:
                lblRet.Text = "Bind is over limit";
                break;

            case -4:
                lblRet.Text = "Channels is over limit";
                break;

            case -5:
                lblRet.Text = "Out of date";
                break;

            case -6:
                lblRet.Text = "Insufficient Balance";
                break;
            }
        }
Exemple #20
0
        public static bool Authenticate(AuthObj obj)
        {
            IDatabase  database = DalFactory.CreateDatabase();
            IPlayerDao dao      = DalFactory.CreatePlayerDao(database);

            string nickname = obj.Nickname;
            string password = obj.HashedPassword;

            Player p = dao.FindByNickname(nickname);

            if (p == null)
            {
                return(false);
            }

            return(BLAuthentication.Verify(password, p.Password));
        }
        /// <summary>
        /// Retrieves the user's friends using the parameter
        /// </summary>
        /// <param name="parameter">The parameter used to select the user</param>
        /// <param name="auth">The auth object</param>
        /// <returns></returns>
        private Friends GetFriends(string parameter, AuthObj auth)
        {
            List <User> tempList = new List <User>();
            long        cursor   = -1;

            while (cursor != 0)
            {
                var friends = new WebHandler(auth).TwitterGetRequest <Friends>(TwitterRequestBuilder.BuildRequest(RequestType.friendsObj, auth, parameter, "count=200", "cursor=" + cursor));
                tempList.AddRange(friends.Users);
                cursor  = friends.NextCursor;
                friends = null;
            }
            Friends result = new Friends();

            result.Users = tempList;
            tempList     = null;
            return(result);
        }
Exemple #22
0
 /// <summary>
 /// Returns the limit helper for the auth object.
 /// If none exist. creates one and returns it.
 /// </summary>
 /// <param name="auth">The auth object</param>
 /// <returns>A limit helper instance</returns>
 public static LimitHelper Instance(AuthObj auth)
 {
     if (limitsByAuth.ContainsKey(auth))
     {
         return(limitsByAuth[auth]);
     }
     else
     {
         lock (_lock)
         {
             if (!limitsByAuth.ContainsKey(auth))
             {
                 limitsByAuth.Add(auth, new LimitHelper());
             }
         }
         return(limitsByAuth[auth]);
     }
 }
Exemple #23
0
        private void FrmMain_Load(object sender, EventArgs e)
        {
            _ICurrencyAuthEvents_OnUpdateEventHandler OnUpdateHandler = new _ICurrencyAuthEvents_OnUpdateEventHandler(AuthObj_OnUpdate);

            AuthObj.OnUpdate += OnUpdateHandler;

            _ICurrencyAuthEvents_OnBulletinEventHandler OnBulletinHandler = new _ICurrencyAuthEvents_OnBulletinEventHandler(AuthObj_OnBulletin);

            AuthObj.OnBulletin += OnBulletinHandler;

            _ICurrencyAuthEvents_OnInvalidEventHandler OnInvalidHandler = new _ICurrencyAuthEvents_OnInvalidEventHandler(AuthObj_OnInvalid);

            AuthObj.OnInvalid += OnInvalidHandler;

            txtValidity.Text = AuthObj.GetValidity();
            txtCode.Text     = AuthObj.GetCode();
            txtBulletin.Text = AuthObj.GetBulletin();

            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }
Exemple #24
0
        /// <summary>
        /// The threaded tweet retrieve method which is used in the task
        /// </summary>
        /// <param name="user">The user</param>
        /// <param name="auth">The auth object</param>
        /// <param name="checkDB">The method to check the database for previous results</param>
        /// <param name="classifyMethod">The method to classify tweets</param>
        /// <param name="postToDB">The method to post the result to the database</param>
        /// <returns>A list of tweets </returns>
        private List <Tweet> TweetThreadMethod(User user, AuthObj auth, Func <User, bool> checkDB = null, Func <List <Tweet>, AnalysisResultObj> classifyMethod = null, Func <AnalysisResultObj, User, bool> postToDB = null)
        {
            bool alreadyExist            = false;
            AnalysisResultObj tempResult = new AnalysisResultObj();
            List <Tweet>      temp       = new List <Tweet>();

            if (checkDB != null)
            {
                alreadyExist = checkDB(user); //Uses the supplied method to find out if the result already exist on the database
                if (alreadyExist)
                {
                    Log.Debug(String.Format("{0,-30} {1,-20} {2,-11}", user.Name, user.Id, "Already exist in db"));
                }
            }

            if (!alreadyExist)
            {
                temp = RetrieveTweets(user, auth);
                if (user.IsProtected)
                {
                    Log.Debug(String.Format("{0,-30} {1,-20} {2,-11}", user.Name, user.Id, "Protected"));
                }
                else
                {
                    Log.Debug(String.Format("{0,-30} {1,-20} {2,-11}", user.Name, user.Id, temp.Count));
                }

                if (classifyMethod != null && postToDB != null)
                {
                    tempResult = classifyMethod(temp); //Use the supplied method to classify the list of tweets
                    postToDB(tempResult, user);        //Use the supplied method to post the result to the database
                    temp = new List <Tweet>();
                }
            }

            return(temp);
        }
Exemple #25
0
 /// <summary>
 /// Gets and analyses the tweets from each of the friends.
 /// In the same way that GetTweetsFromUserAndAnalyse does.
 /// </summary>
 /// <param name="friends">The friends of an user </param>
 /// <param name="auth">The auth object</param>
 /// <param name="checkDB">The method to check the database for previous results</param>
 /// <param name="classifyMethod">The method to classify tweets</param>
 /// <param name="postToDB">The method to post the result to the database</param>
 public void GetTweetsFromFriendsAndAnalyse(Friends friends, AuthObj auth, Func <User, bool> checkDB, Func <List <Tweet>, AnalysisResultObj> classifyMethod, Func <AnalysisResultObj, User, bool> postToDB)
 {
     GetTweetsFromFriendsHelper(friends, auth, ((x) => TweetThreadMethod(x, auth, checkDB, classifyMethod, postToDB)));
 }
Exemple #26
0
 /// <summary>
 /// Get the tweets a user has posted, but does nothing to them.
 /// Kept for legacy purposes
 /// </summary>
 /// <param name="user">The user</param>
 /// <param name="auth">The auth object</param>
 /// <returns>A list of tweets a user has posted</returns>
 public List <Tweet> GetTweetsFromUser(User user, AuthObj auth)
 {
     return(GetTweetsFromUserHelper(user, auth, (() => TweetThreadMethod(user, auth))));
 }
Exemple #27
0
 /// <summary>
 /// Get the tweets a user has posted, but does not return them,
 /// but only if the database does not contain a result.
 /// It analyses the tweets using both our approaches.
 /// Then uploads it to the database.
 /// </summary>
 /// <param name="user">The user</param>
 /// <param name="auth">The auth object</param>
 /// <param name="checkDB">The method to check the database for previous results</param>
 /// <param name="classifyMethod">The method to classify tweets</param>
 /// <param name="postToDB">The method to post the result to the database</param>
 public void GetTweetsFromUserAndAnalyse(User user, AuthObj auth, Func <User, bool> checkDB, Func <List <Tweet>, AnalysisResultObj> classifyMethod, Func <AnalysisResultObj, User, bool> postToDB)
 {
     GetTweetsFromUserHelper(user, auth, (() => TweetThreadMethod(user, auth, checkDB, classifyMethod, postToDB)));
 }
Exemple #28
0
 /// <summary>
 /// Gets the tweets from each of the friends.
 /// Kept for legacy purposes.
 /// </summary>
 /// <param name="friends">The friends of an user </param>
 /// <param name="auth">The auth object</param>
 /// <returns>A list of tweets from the friends</returns>
 public List <Tweet> GetTweetsFromFriends(Friends friends, AuthObj auth)
 {
     return(GetTweetsFromFriendsHelper(friends, auth, ((x) => TweetThreadMethod(x, auth))));
 }
Exemple #29
0
 public Worker(AuthObj auth, string twitterName)
 {
     Run(auth, twitterName);
 }
Exemple #30
0
 public WebHandler(AuthObj auth)
 {
     this.auth = auth;
     ServicePointManager.DefaultConnectionLimit = 4; //Because at normal operation at most 4 threads should be running
 }