コード例 #1
0
    public IEnumerator JumpToConnection(PlatformConnection endConnection)
    {
        Vector2 jumpDifference = endConnection.transform.position - feetPos.position;

        SetEffect(Effect.NoControl, connectionJumpTime, false);
        isAffectedByGravity         = false;
        collisionCollider.isTrigger = true;
        float timer = connectionJumpTime / slowEffectScale;

        pJumpCDRemaining = pathFindingJumpCooldown;

        while (timer > 0 && !Is(Effect.Stun) && !Is(Effect.NoGravity))
        {
            rb.velocity = jumpDifference / connectionJumpTime * slowEffectScale * Time.deltaTime * 50;

            yield return(new WaitForEndOfFrame());

            timer -= Time.deltaTime;
        }

        if (timer <= 0)
        {
            transform.position = endConnection.transform.position - feetPos.localPosition;
            Propel(Vector2.zero, true, true);
            SetEffect(Effect.NoControl, 0.2f, false);
        }
        else
        {
            SetEffect(Effect.NoControl, 0, false);
        }

        collisionCollider.isTrigger = false;
        isAffectedByGravity         = true;
    }
コード例 #2
0
 public async Task TriggerDataFetch(string userId, PlatformConnection platformConnection,
                                    PlatformIntegrationType platformIntegrationType, IBus bus)
 {
     platformConnection.MarkAsDataFetchStarted();
     var fetchDataMessage = new FetchDataForPlatformConnectionMessage(userId,
                                                                      platformConnection.PlatformId, platformIntegrationType);
     await bus.Send(fetchDataMessage);
 }
コード例 #3
0
 private void onFriendConnected(Friend friend, PlatformConnection conn)
 {
     if (!allowFriends)
     {
         return;
     }
     Log.trace("onFriendConnected " + friend.displayName + " " + conn);
     if (modeInit != null && Multiplayer.mode == Mode.Host)
     {
         pendingConns.Add(conn);
     }
 }
コード例 #4
0
 private static bool IsPlatformConnectionRipeForUpdate(PlatformConnection pc, DateTimeOffset now)
 {
     return(!pc.ConnectionInfo.IsDeleted &&
            pc.DataPullIntervalInSeconds.HasValue &&
            (!pc.LastDataFetchAttemptStart.HasValue ||
             (pc.LastDataFetchAttemptCompleted.HasValue &&                           //we did complete the last update attempt and it was more then data pull interval ago
              now.Subtract(pc.LastDataFetchAttemptCompleted.Value).TotalSeconds >=
              pc.DataPullIntervalInSeconds.Value) ||
             (!pc.LastDataFetchAttemptCompleted.HasValue &&                          //we did not complete the last update attempt and the attempt was started more then data pull interval ago
              now.Subtract(pc.LastDataFetchAttemptStart.Value).TotalSeconds >=
              pc.DataPullIntervalInSeconds.Value)));
 }
コード例 #5
0
        public override void draw(SpriteBatch b)
        {
            if (!didModeSelect)
            {
                int x = xPositionOnScreen + width / 4;
                int y = yPositionOnScreen + (int)(height / 5 * 0.5);
                int w = width / 2;
                int h = height / 5;

                buttonX = x;
                buttonH = h;
                buttonW = w;

                buttonY1 = y;
                IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), x, y, w, h, new Rectangle(x, y, w, h).Contains(Game1.getOldMouseX(), Game1.getOldMouseY()) ? Color.Wheat : Color.White, (float)Game1.pixelZoom, true);
                SpriteText.drawString(b, "Singleplayer", x + w / 2 - SpriteText.getWidthOfString("Singleplayer") / 2, y + h / 2 - SpriteText.getHeightOfString("Singleplayer") / 2);
                y += (int)(h * 1.25);

                buttonY2 = y;
                IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), x, y, w, h, new Rectangle(x, y, w, h).Contains(Game1.getOldMouseX(), Game1.getOldMouseY()) ? Color.Wheat : Color.White, (float)Game1.pixelZoom, true);
                SpriteText.drawString(b, "Host", x + w / 2 - SpriteText.getWidthOfString("Host") / 2, y + h / 2 - SpriteText.getHeightOfString("Host") / 2);
                y += (int)(h * 1.25);

                buttonY3 = y;
                IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), x, y, w, h, new Rectangle(x, y, w, h).Contains(Game1.getOldMouseX(), Game1.getOldMouseY()) ? Color.Wheat : Color.White, (float)Game1.pixelZoom, true);
                SpriteText.drawString(b, "Client", x + w / 2 - SpriteText.getWidthOfString("Client") / 2, y + h / 2 - SpriteText.getHeightOfString("Client") / 2);
            }
            else if (modeInit == null)
            {
                int    x = buttonX, y = buttonY3 + buttonH, w = buttonW, h = buttonH;
                String str = (Multiplayer.mode == Mode.Host ? "Listen" : "Connect");

                if (Multiplayer.mode == Mode.Client)
                {
                    /*
                     * SpriteText.drawString(b, "Network", Game1.viewport.Width / 2 - SpriteText.getWidthOfString("Network") - 50, 20,
                     *  999999, -1, 999999, 1, 0.88f, false, -1, "", showingFriends ? -1 : 5);
                     * SpriteText.drawString(b, "Friends", Game1.viewport.Width / 2 + 50, 20,
                     *  999999, -1, 999999, 1, 0.88f, false, -1, "", friends == null ? 0 : (showingFriends ? 5 : -1));*/

                    b.DrawString(Game1.dialogueFont, "Network", new Vector2(Game1.viewport.Width / 4 + 0, 20 + 2), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "Network", new Vector2(Game1.viewport.Width / 4 + 2, 20 + 0), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "Network", new Vector2(Game1.viewport.Width / 4 + 0, 20 - 2), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "Network", new Vector2(Game1.viewport.Width / 4 - 2, 20 - 0), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "Network", new Vector2(Game1.viewport.Width / 4, 20), (!showingFriends && !showingLan ? Color.OrangeRed : Color.SaddleBrown));
                    b.DrawString(Game1.dialogueFont, "Friends", new Vector2(Game1.viewport.Width / 2 - 50 + 0, 20 + 2), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "Friends", new Vector2(Game1.viewport.Width / 2 - 50 + 2, 20 + 0), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "Friends", new Vector2(Game1.viewport.Width / 2 - 50 + 0, 20 - 2), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "Friends", new Vector2(Game1.viewport.Width / 2 - 50 - 2, 20 - 0), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "Friends", new Vector2(Game1.viewport.Width / 2 - 50, 20), friends == null ? Color.Black : (showingFriends ? Color.OrangeRed : Color.SaddleBrown));
                    b.DrawString(Game1.dialogueFont, "LAN", new Vector2(Game1.viewport.Width / 4 * 3 - 100 + 0, 20 + 2), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "LAN", new Vector2(Game1.viewport.Width / 4 * 3 - 100 + 2, 20 + 0), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "LAN", new Vector2(Game1.viewport.Width / 4 * 3 - 100 + 0, 20 - 2), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "LAN", new Vector2(Game1.viewport.Width / 4 * 3 - 100 - 2, 20 - 0), (Color.Black) * 0.25f);
                    b.DrawString(Game1.dialogueFont, "LAN", new Vector2(Game1.viewport.Width / 4 * 3 - 100, 20), showingLan ? Color.OrangeRed : Color.SaddleBrown);
                }
                else if (Multiplayer.mode == Mode.Host)
                {
                    Color gray   = new Color(127, 127, 127);
                    Color text   = new Color(86, 22, 12);
                    Color hover1 = Color.Wheat * 0.8f;
                    Color hover2 = Color.DarkGoldenrod * 0.8f;
                    hover1.A = hover2.A = 0xFF;

                    String    checkStr = "Allow direct friend connections";
                    Rectangle r        = new Rectangle(x, buttonY1 + 48, 64, 64);
                    Vector2   pos      = new Vector2(r.X + r.Width + 30, r.Y + (r.Height - Game1.dialogueFont.MeasureString(checkStr).Y) / 2);
                    drawTextureBox(b, r.X, r.Y, r.Width, r.Height, r.Contains(Game1.getMousePosition()) ? hover1 : Color.White);
                    if (allowFriends)
                    {
                        drawTextureBox(b, Game1.menuTexture, new Rectangle(0, 256, 60, 60), r.X + r.Width / 5, r.Y + r.Height / 5, r.Width / 8 * 5, r.Height / 8 * 5, r.Contains(Game1.getMousePosition()) ? hover2 : Color.DarkGoldenrod, 1, false);
                    }
                    b.DrawString(Game1.dialogueFont, checkStr, pos + new Vector2(0, 2), gray * 0.25f);
                    b.DrawString(Game1.dialogueFont, checkStr, pos + new Vector2(2, 0), gray * 0.25f);
                    b.DrawString(Game1.dialogueFont, checkStr, pos + new Vector2(0, -2), gray * 0.25f);
                    b.DrawString(Game1.dialogueFont, checkStr, pos + new Vector2(-2, 0), gray * 0.25f);
                    b.DrawString(Game1.dialogueFont, checkStr, pos, text);

                    checkStr = "Allow LAN discovery";
                    r.Y     += 80;
                    pos.Y   += 80;
                    drawTextureBox(b, r.X, r.Y, r.Width, r.Height, r.Contains(Game1.getMousePosition()) ? hover1 : Color.White);
                    if (allowLan)
                    {
                        drawTextureBox(b, Game1.menuTexture, new Rectangle(0, 256, 60, 60), r.X + r.Width / 5, r.Y + r.Height / 5, r.Width / 8 * 5, r.Height / 8 * 5, r.Contains(Game1.getMousePosition()) ? hover2 : Color.DarkGoldenrod, 1, false);
                    }
                    b.DrawString(Game1.dialogueFont, checkStr, pos + new Vector2(0, 2), gray * 0.25f);
                    b.DrawString(Game1.dialogueFont, checkStr, pos + new Vector2(2, 0), gray * 0.25f);
                    b.DrawString(Game1.dialogueFont, checkStr, pos + new Vector2(0, -2), gray * 0.25f);
                    b.DrawString(Game1.dialogueFont, checkStr, pos + new Vector2(-2, 0), gray * 0.25f);
                    b.DrawString(Game1.dialogueFont, checkStr, pos, text);
                }

                if (showingFriends)
                {
                    if (pendingClient == null)
                    {
                        if (pendingConns.Count > 0)
                        {
                            PlatformConnection conn   = (PlatformConnection)pendingConns[0];
                            Friend             friend = conn.friend;

                            int ix = xPositionOnScreen + width / 5;
                            int iw = width / 5 * 3;
                            int ih = 80 * 2 + 64;
                            int iy = (Game1.viewport.Height - ih) / 2;

                            IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), ix, iy, iw, ih, Color.White, (float)Game1.pixelZoom, true);
                            ix += 32;
                            iy += 32;
                            b.Draw(friend.avatar, new Rectangle(ix, iy, 64, 64), Color.White);
                            SpriteText.drawString(b, friend.displayName, ix + 88, iy + 8);
                            SpriteText.drawString(b, "Connecting...", ix + 32, iy + 96);
                        }
                        else
                        {
                            friends.draw(b);
                        }
                    }
                }
                else if (showingLan)
                {
                    lan.draw(b);
                }
                else
                {
                    Color gray = new Color(127, 127, 127);
                    Color text = new Color(86, 22, 12);
                    if (ipBox != null)
                    {
                        b.DrawString(Game1.dialogueFont, "IP Address:", new Vector2(ipBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20 + 0, ipBox.Y + 2), gray * 0.25f);
                        b.DrawString(Game1.dialogueFont, "IP Address:", new Vector2(ipBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20 + 2, ipBox.Y + 0), gray * 0.25f);
                        b.DrawString(Game1.dialogueFont, "IP Address:", new Vector2(ipBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20 + 0, ipBox.Y - 2), gray * 0.25f);
                        b.DrawString(Game1.dialogueFont, "IP Address:", new Vector2(ipBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20 - 2, ipBox.Y - 0), gray * 0.25f);
                        b.DrawString(Game1.dialogueFont, "IP Address:", new Vector2(ipBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20, ipBox.Y), text);

                        ipBox.Draw(b);
                    }
                    if (portBox != null)
                    {
                        b.DrawString(Game1.dialogueFont, "Port:", new Vector2(portBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20 + 0, portBox.Y + 2), gray * 0.25f);
                        b.DrawString(Game1.dialogueFont, "Port:", new Vector2(portBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20 + 2, portBox.Y + 0), gray * 0.25f);
                        b.DrawString(Game1.dialogueFont, "Port:", new Vector2(portBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20 + 0, portBox.Y - 2), gray * 0.25f);
                        b.DrawString(Game1.dialogueFont, "Port:", new Vector2(portBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20 - 2, portBox.Y - 0), gray * 0.25f);
                        b.DrawString(Game1.dialogueFont, "Port:", new Vector2(portBox.X - Game1.dialogueFont.MeasureString("IP Address:").X - 20, portBox.Y), text);

                        portBox.Draw(b);
                    }

                    IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), x, y, w, h, new Rectangle(x, y, w, h).Contains(Game1.getOldMouseX(), Game1.getOldMouseY()) ? Color.Wheat : Color.White, (float)Game1.pixelZoom, true);
                    SpriteText.drawString(b, str, x + w / 2 - SpriteText.getWidthOfString(str) / 2, y + h / 2 - SpriteText.getHeightOfString(str) / 2);
                }
            }
            else if (Multiplayer.problemStarting)
            {
                int    x = buttonX, y = buttonY1, w = buttonW, h = buttonH;
                String str = "Error";
                SpriteText.drawString(b, str, x + w / 2 - SpriteText.getWidthOfString(str) / 2, y + h / 2 - SpriteText.getHeightOfString(str) / 2);

                y = buttonY2;
                //

                y   = buttonY3;
                str = "Back";
                IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), x, y, w, h, new Rectangle(x, y, w, h).Contains(Game1.getOldMouseX(), Game1.getOldMouseY()) ? Color.Wheat : Color.White, (float)Game1.pixelZoom, true);
                SpriteText.drawString(b, str, x + w / 2 - SpriteText.getWidthOfString(str) / 2, y + h / 2 - SpriteText.getHeightOfString(str) / 2);
            }
            else if (Multiplayer.server != null)
            {
                if (pendingConns.Count > 0)
                {
                    PlatformConnection conn   = (PlatformConnection)pendingConns[0];
                    Friend             friend = conn.friend;

                    int ix = xPositionOnScreen + width / 5;
                    int iw = width / 5 * 3;
                    int ih = 80 * 2 + 64;
                    int iy = (Game1.viewport.Height - ih) / 2;

                    IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), ix, iy, iw, ih, Color.White, (float)Game1.pixelZoom, true);
                    ix += 32;
                    iy += 32;
                    b.Draw(friend.avatar, new Rectangle(ix, iy, 64, 64), Color.White);
                    SpriteText.drawString(b, friend.displayName, ix + 88, iy + 8);

                    ix += 40;
                    iy += ih - 32 * 2 - 80;
                    iw  = iw / 2 - 96;
                    ih  = 80;

                    IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), ix, iy, iw, ih, new Rectangle(ix, iy, iw, ih).Contains(Game1.getOldMouseX(), Game1.getOldMouseY()) ? Color.Wheat : Color.White, (float)Game1.pixelZoom, true);
                    SpriteText.drawString(b, "Accept", ix + iw / 2 - SpriteText.getWidthOfString("Accept") / 2, iy + ih / 2 - SpriteText.getHeightOfString("Accept") / 2);
                    if (justClicked && new Rectangle(ix, iy, iw, ih).Contains(Game1.getMouseX(), Game1.getMouseY()))
                    {
                        Log.trace("Accepted " + ((PlatformConnection)pendingConns[0]).friend.displayName);
                        Task.Run(() =>
                        {
                            var platConn = pendingConns[0] as PlatformConnection;
                            platConn.accept();
                            pendingConns.Remove(platConn);
                            Multiplayer.server.addClient(platConn, true);
                        });
                    }

                    ix += iw + 40;

                    IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), ix, iy, iw, ih, new Rectangle(ix, iy, iw, ih).Contains(Game1.getOldMouseX(), Game1.getOldMouseY()) ? Color.Wheat : Color.White, (float)Game1.pixelZoom, true);
                    SpriteText.drawString(b, "Decline", ix + iw / 2 - SpriteText.getWidthOfString("Decline") / 2, iy + ih / 2 - SpriteText.getHeightOfString("Decline") / 2);
                    if (justClicked && new Rectangle(ix, iy, iw, ih).Contains(Game1.getMouseX(), Game1.getMouseY()))
                    {
                        Log.trace("Declined " + ((PlatformConnection)pendingConns[0]).friend.displayName);
                        pendingConns.Remove(pendingConns[0]);
                    }
                }
                else
                {
                    int    x = buttonX, y = buttonY1, w = buttonW, h = buttonH;
                    String str = "Start";

                    Util.drawStr("Local IP: ", x, buttonY1, Color.White);
                    Util.drawStr("External IP: ", x, buttonY1 + 35, Color.White);
                    Util.drawStr("Port: ", x, buttonY1 + 70, Color.White);
                    Util.drawStr(localIp, x + 200, buttonY1, Color.White);
                    Util.drawStr(externalIp, x + 200, buttonY1 + 35, Color.White);
                    Util.drawStr(Multiplayer.portStr, x + 200, buttonY1 + 70, Color.White);

                    /*Util.drawStr("Other players: ", x, buttonY1, Color.White);
                     * foreach ( Server.Client client in Multiplayer.server.clients )
                     * {
                     *  String str_ = "<Client " + ( int )( client.id ) + ">";
                     *  if ( client.farmer != null )
                     *      str_ = client.farmer.name;
                     *
                     *  y += 30;
                     *  Util.drawStr(str_, x + 25, y, Color.White);
                     * }*/

                    y = buttonY3;
                    IClickableMenu.drawTextureBox(b, Game1.mouseCursors, new Rectangle(384, 373, 18, 18), x, y, w, h, new Rectangle(x, y, w, h).Contains(Game1.getOldMouseX(), Game1.getOldMouseY()) ? Color.Wheat : Color.White, (float)Game1.pixelZoom, true);
                    SpriteText.drawString(b, str, x + w / 2 - SpriteText.getWidthOfString(str) / 2, y + h / 2 - SpriteText.getHeightOfString(str) / 2);
                }
            }
            else if (Multiplayer.client != null)
            {
                int x = buttonX, y = buttonY1, w = buttonW, h = buttonH;

                /*Util.drawStr("Other players: ", x, buttonY1, Color.White);
                 * foreach (KeyValuePair< byte, SFarmer > other in Multiplayer.client.others)
                 * {
                 *  String str_ = "<Client " + (int)(other.Key) + ">";
                 *  if (other.Value != null)
                 *      str_ = other.Value.name;
                 *
                 *  y += 30;
                 *  Util.drawStr(str_, x + 25, y, Color.White);
                 * }*/
            }

            base.draw(b);

            ChatMenu.drawChat(false);

            justClicked = false;
        }
コード例 #6
0
 public Task <TConnectionInfo> StartDataFetch(string userId, string platformId, TConnectionInfo connectionInfo,
                                              PlatformConnection platformConnection, DataSyncLog syncLog, CancellationToken cancellationToken = default)
 {
     throw new NotImplementedException();
 }
コード例 #7
0
    /// <summary>
    /// Change the value of targetConnection and targetConnectedConnection.
    /// Return the distance between the connected connection and the next connection in negative, if positive it's the distance between the player and the connected connection
    /// </summary>
    /// <param name="platform"></param>
    /// <param name="target"></param>
    /// <param name="originConnectionPos"></param>
    /// <param name="linkedConnection"></param>
    /// <returns></returns>
    private float FindNextConnection(PlatformHandler platform, GameObject target, Vector2 originConnectionPos)
    {
        //Debug.Log("Testing player presence on " + platform.gameObject.name);

        if (GameData.playerMovement.currentPlayerPlatform == null && platform.IsUnder(target))
        {
            GameData.playerMovement.currentPlayerPlatform = platform;
        }

        if (platform == GameData.playerMovement.currentPlayerPlatform)
        {
            //Debug.Log("Player found on " + platform.gameObject.name + " !");

            float distanceToPlayer = Vector2.Distance(originConnectionPos, target.transform.position);
            return(distanceToPlayer);
        }
        else
        {
            //Debug.Log("No player found. Now testing connections on " + platform.gameObject.name);

            float minDistanceBetweenConnection = -1;

            foreach (PlatformConnection connection in platform.connections)
            {
                //Debug.Log("Testing " + connection.gameObject.name);
                if (connection.connectedConnections.Count > 0)
                {
                    //Debug.Log(connection.gameObject.name + " has at least 1 connected connection");

                    float minDistanceBetweenConnected = -1;
                    float distanceToConnection        = Vector2.Distance(originConnectionPos, connection.transform.position) + pathfindingJumpWeight;
                    PlatformConnection tempCC         = null;

                    for (int i = 0; i < connection.connectedConnections.Count; i++)
                    {
                        //Debug.Log("Testing connected " + connection.connectedConnections[i].gameObject.name);
                        if (!testedPlatform.Contains(connection.connectedConnections[i].attachedPlatformHandler))
                        {
                            testedPlatform.Add(connection.connectedConnections[i].attachedPlatformHandler);

                            float distanceFromEnd = FindNextConnection(connection.connectedConnections[i].attachedPlatformHandler, target, connection.connectedConnections[i].transform.position);

                            if (distanceFromEnd > 0)
                            {
                                testedPlatform.Remove(connection.connectedConnections[i].attachedPlatformHandler);
                                //Debug.Log("Player found at " + distanceFromEnd + " passing by " + connection.connectedConnections[i].gameObject.name + " linked with " + connection.gameObject.name);
                                if (distanceFromEnd < minDistanceBetweenConnected || minDistanceBetweenConnected == -1)
                                {
                                    //Debug.Log("Better CC found with " + distanceFromEnd + " instead of " + minDistanceBetweenConnected);
                                    minDistanceBetweenConnected = distanceFromEnd;
                                    tempCC = connection.connectedConnections[i];
                                }
                            }
                        }
                        else
                        {
                            //Debug.Log(connection.connectedConnections[i].attachedPlatformHandler.gameObject.name + " has already been tested");
                        }
                    }

                    if (minDistanceBetweenConnected != -1)
                    {
                        if ((minDistanceBetweenConnected + distanceToConnection) < minDistanceBetweenConnection || minDistanceBetweenConnection == -1)
                        {
                            //Debug.Log("Better connection found with " + minDistanceBetweenConnected + distanceToConnection + " instead of " + minDistanceBetweenConnection);
                            minDistanceBetweenConnection = minDistanceBetweenConnected + distanceToConnection;

                            if (platform == currentPlatform)
                            {
                                //Debug.Log("Target Connection found ! + \"" + connection.gameObject.name + " is the chosen one ! Linked to " + tempCC.gameObject.name);
                                targetConnection          = connection;
                                targetConnectedConnection = tempCC;
                            }
                        }
                    }
                    else
                    {
                        //Debug.Log("No CC linked to " + connection.gameObject.name + " lead to the player");
                    }
                }
                else
                {
                    //Debug.Log("Connection " + connection.gameObject.name + " has no connected connection");
                }
            }

            if (minDistanceBetweenConnection != -1)
            {
                return(minDistanceBetweenConnection);
            }
            else
            {
                //Debug.Log(platform.gameObject.name + " has no connection leading to the player");
            }
        }
        return(0);
    }
コード例 #8
0
        public new async Task <OAuthPlatformConnectionInfo> StartDataFetch(string userId, string platformId,
                                                                           OAuthPlatformConnectionInfo connectionInfo, PlatformConnection platformConnection, DataSyncLog syncLog,
                                                                           CancellationToken cancellationToken = default)
        {
            using var _ = Logger.BeginPropertyScope((LoggerPropertyNames.DataSyncLogId, syncLog.ExternalId));

            Logger.LogTrace($"Will start data fetch from Freelancer for user with id {userId}");
            if (connectionInfo.Token.HasExpired())
            {
                Logger.LogInformation($"Token has expired, will try to refresh it");
                try
                {
                    var newToken = await _freelancerAuthenticator.RefreshToken(new OAuthAccessToken
                    {
                        AccessToken  = connectionInfo.Token.AccessToken,
                        RefreshToken = connectionInfo.Token.RefreshToken,
                        ExpiresIn    = connectionInfo.Token.ExpiresInSeconds
                    });

                    connectionInfo.Token = new Token(newToken);
                }
                catch (UnauthorizedAccessException)
                {
                    Logger.LogInformation(
                        "The consent to access Freelancer seems to have been revoked. Will act accordingly");
                    return(await HandleUnauthorized(userId, platformId, syncLog.Id));
                }
            }

            _apiClient.SetAccessToken(connectionInfo.Token.AccessToken);
            string          rawReviews;
            ReviewApiResult freelancerReviews;
            string          rawUserProfile;

            UserInfoApiResult userProfile;

            try
            {
                (userProfile, rawUserProfile) = await _apiClient.GetUserProfile();

                (freelancerReviews, rawReviews) = await _apiClient.GetReviews(userProfile.Result.Id);
            }
            catch (UnauthorizedAccessException)
            {
                Logger.LogInformation(
                    "The consent to access Freelancer seems to have been revoked. Will act accordingly");
                return(await HandleUnauthorized(userId, platformId, syncLog.Id));
            }

            var(ratings, reviews) = GetRatingsAndReviews(freelancerReviews);

            var raw = $"{{data: [{rawUserProfile}, {rawReviews}]}}";

            var numberOfCompletedJobs = userProfile.Result.Reputation.EntireHistory.Complete;
            var averageRating         = numberOfCompletedJobs == 0
                ? null
                : new RatingDataFetchResult(userProfile.Result.Reputation.EntireHistory.Overall);

            //achievements
            var achievements = new List <AchievementFetchResult>();

            var qualifications = userProfile.Result.Qualifications;

            if (qualifications != null)
            {
                foreach (var qualification in qualifications)
                {
                    var score = new AchievementScoreFetchResult(
                        qualification.ScorePercentage.ToString(CultureInfo.InvariantCulture), "percent");

                    var achievement = new AchievementFetchResult($"freelancer_qualification_{qualification.Id}",
                                                                 qualification.Name,
                                                                 "qualification", PlatformAchievementType.QualificationAssessment, qualification.Description,
                                                                 $"https://www.freelancer.com{qualification.IconUrl}",
                                                                 score);

                    achievements.Add(achievement);
                }
            }

            var badges = userProfile.Result.Badges;

            if (badges != null)
            {
                foreach (var badge in badges)
                {
                    var achievement = new AchievementFetchResult($"freelancer_badge_{badge.Id}", badge.Name, "badge",
                                                                 PlatformAchievementType.Badge, badge.Description, $"https://www.freelancer.com{badge.IconUrl}",
                                                                 null);

                    achievements.Add(achievement);
                }
            }

            var registrationDate = DateTimeOffset.FromUnixTimeSeconds(userProfile.Result.RegistrationDate);

            var result = new PlatformDataFetchResult(numberOfCompletedJobs,
                                                     registrationDate, DateTimeOffset.UtcNow, averageRating, ratings, reviews, achievements, raw);

            await CompleteDataFetch(userId, platformId, result, syncLog.Id);


            Logger.LogTrace($"Freelancer data fetch completed for user with id {userId}");
            return(connectionInfo);
        }
コード例 #9
0
        public new async Task <OAuthOrEmailPlatformConnectionInfo> StartDataFetch(string userId, string platformId,
                                                                                  OAuthOrEmailPlatformConnectionInfo connectionInfo, PlatformConnection platformConnection, DataSyncLog syncLog,
                                                                                  CancellationToken cancellationToken = default)
        {
            using var _ = Logger.BeginPropertyScope((LoggerPropertyNames.UserId, userId),
                                                    (LoggerPropertyNames.PlatformId, platformId), (LoggerPropertyNames.PlatformName, platformConnection.PlatformName),
                                                    (LoggerPropertyNames.DataSyncLogId, syncLog.ExternalId));

            Logger.LogInformation("Will start data fetch from a Gig platform integrated platform for user.");

            if (connectionInfo.IsOAuthAuthentication)
            {
                Logger.LogError("Oauth connection not yet supported in Gig Platform API. Will throw.");
                throw new UnsupportedPlatformConnectionAuthenticationTypeException("Oauth connection not yet supported in Gig Platform API");
            }

            try
            {
                var result = await _apiClient.RequestLatest(platformConnection.ExternalPlatformId, connectionInfo.Email, cancellationToken);

                using var __ = Logger.BeginPropertyScope((LoggerPropertyNames.GigPlatformApiRequestId, result.RequestId));
                await _intermittentDataManager.RegisterRequestData(result.RequestId, userId, platformId, syncLog.Id);
            }
            catch (ExternalServiceErrorException ex)
            {
                //Error that can occur here is that we get either a 500, which means there is something wrong with platform api server. Or we get a 404, which means that the
                //platform we asked the api to fetch data from does not exist on the api side of things. Both these cases should result in a retry. So we throw here.
                var logMessage = "Got error when regestering data fetch. Will throw.";
                Logger.LogError(ex, logMessage);
                syncLog.Steps.Add(new DataSyncStep(DataSyncStepType.PlatformDataFetch, DataSyncStepState.Failed, logMessage: logMessage));
                throw new GigDataPlatformApiInitiateDataFetchException();
            }

            syncLog.Steps.Add(new DataSyncStep(DataSyncStepType.PlatformDataFetch, DataSyncStepState.Started));
            Logger.LogInformation("Data fetch successfully started.");
            return(connectionInfo);
        }
コード例 #10
0
        public async Task Handle(PlatformConnectionRemovedMessage message)
        {
            using var _ = _logger.BeginPropertyScope((LoggerPropertyNames.PlatformId, message.PlatformId),
                                                     (LoggerPropertyNames.UserId, message.UserId),
                                                     ("DeleteReason", message.DeleteReason));
            _logger.LogInformation("Will remove platform connection");

            using var session = _documentStore.OpenAsyncSession();

            DataSyncLog syncLog = null;

            if (!string.IsNullOrEmpty(message.SyncLogId))
            {
                syncLog = await session.LoadAsync <DataSyncLog>(message.SyncLogId);
            }

            using var __ = _logger.BeginPropertyScope((LoggerPropertyNames.DataSyncLogId, syncLog?.ExternalId));

            //remove connection
            var user = await session.LoadAsync <User>(message.UserId);

            var index         = 0;
            var indexToRemove = -1;
            PlatformConnection platformConnectionToRemove = null;

            foreach (var userPlatformConnection in user.PlatformConnections)
            {
                if (userPlatformConnection.PlatformId == message.PlatformId)
                {
                    indexToRemove = index;
                    platformConnectionToRemove = userPlatformConnection;
                    break;
                }

                index++;
            }

            if (indexToRemove == -1 || platformConnectionToRemove == null)
            {
                _logger.LogWarning("Platform connection with platform id {PlatformId} was not found for user with id {UserId}",
                                   message.PlatformId, message.UserId);
                syncLog?.Steps.Add(new DataSyncStep(DataSyncStepType.RemovePlatformConnection, DataSyncStepState.Failed,
                                                    $"Platform connection with platform id {message.PlatformId} was not found for user with id {message.UserId}"));
                await session.SaveChangesAsync();

                return;
            }

            if (message.DeleteReason != Common.PlatformConnectionDeleteReason.Undefined) //if we have a delete reason, do soft delete
            {
                _logger.LogInformation("Delete reason was {DeleteReason}. Will do soft delete", message.DeleteReason);
                platformConnectionToRemove.ConnectionInfo.DeleteReason = message.DeleteReason;
                platformConnectionToRemove.ConnectionInfo.IsDeleted    = true;
            }
            else //no reason given, do hard delete
            {
                _logger.LogInformation("No delete reason was given. Will do hard delete");
                user.PlatformConnections.RemoveAt(indexToRemove);
            }

            syncLog?.Steps.Add(new DataSyncStep(DataSyncStepType.RemovePlatformConnection, DataSyncStepState.Succeeded));

            await session.SaveChangesAsync();

            await _appNotificationManager.NotifyPlatformConnectionRemoved(message.UserId,
                                                                          platformConnectionToRemove.ConnectionInfo.NotificationInfos.Select(ni => ni.AppId).ToList(),
                                                                          platformConnectionToRemove.PlatformId, session);
        }