Beispiel #1
0
#pragma warning restore 0414
#endif

    public DiscordUser()
    {
        _username      = "******";
        _discriminator = 1;
        _snowflake     = 0;
        _avatarHash    = "";
        _avatar        = null;
        _cacheSize     = DiscordAvatarSize.x128;
        _cacheFormat   = DiscordUser.AvatarFormat;
        _cdnEndpoint   = "cdn.discordapp.com";
    }
Beispiel #2
0
    /// <summary>
    /// Gets the default avatar for the given user. Will check the cache first, and if none are available it will then download the default from discord.
    /// </summary>
    /// <param name="size">The size of the target avatar</param>
    /// <param name="callback">The callback that will be made when the picture finishes downloading.</param>
    /// <returns></returns>
    public IEnumerator GetDefaultAvatarCoroutine(DiscordAvatarSize size = DiscordAvatarSize.x128, AvatarDownloadCallback callback = null)
    {
        int discrim = discriminator % 5;

        string filename = string.Format("default-{0}{1}.png", discrim, size.ToString());
        string cache    = Path.Combine(Application.dataPath, CacheDirectory);
        string path     = Path.Combine(cache, filename);

        //The holder texture is null, so we should create new one
        Texture2D avatarTexture = new Texture2D((int)size, (int)size, TextureFormat.RGBA32, false);

        //Check if the file exists
        if (File.Exists(path))
        {
            //Load the image
            byte[] bytes = File.ReadAllBytes(path);
            avatarTexture.LoadImage(bytes);
        }
        else
        {
            string url = string.Format("https://{0}/embed/avatars/{1}.png?size={2}", _cdnEndpoint, discrim, (int)size);
            using (WWW www = new WWW(url))
            {
                //Download the texture
                yield return(www);

                //Update the holder
                www.LoadImageIntoTexture(avatarTexture);

                //Create the directory if it doesnt already exist
                if (!Directory.Exists(cache))
                {
                    Directory.CreateDirectory(cache);
                }

                byte[] bytes = avatarTexture.EncodeToPNG();
                File.WriteAllBytes(path, bytes);
            }
        }

        //Apply our avatar and update our cache
        _avatar      = avatarTexture;
        _cacheFormat = DiscordAvatarFormat.PNG;
        _cachePath   = path;
        _cacheSize   = size;

        //Execute the callback (if any)
        if (callback != null)
        {
            callback.Invoke(this, _avatar);
        }
    }
Beispiel #3
0
    private string GetAvatarURL(DiscordAvatarFormat format, DiscordAvatarSize size)
    {
        //Prepare the endpoint
        string endpoint = "/avatars/" + _snowflake + "/" + _avatarHash;

        //The user has no avatar, so we better replace it with the default
        if (string.IsNullOrEmpty(_avatarHash))
        {
            //Make sure we are only using PNG
            if (format != DiscordAvatarFormat.PNG)
            {
                throw new System.BadImageFormatException("The user has no avatar and the requested format " + format.ToString() + " is not supported. (Only supports PNG).");
            }

            //Get the endpoint
            int descrim = _discriminator % 5;
            endpoint = "/embed/avatars/" + descrim;
        }

        //Finish of the endpoint
        return(string.Format("https://{0}{1}.{2}?size={3}", this._cdnEndpoint, endpoint, format.ToString().ToLower(), (int)size));
    }
Beispiel #4
0
    /// <summary>
    /// Gets the default avatar for the given user. Will check the cache first, and if none are available it will then download the default from discord.
    /// <para>An alias of <see cref="DiscordUser.CacheDefaultAvatarCoroutine(DiscordAvatarSize, DiscordUser.AvatarDownloadCallback)"/> and will return the new <see cref="DiscordUser"/> instance in the callback.</para>
    /// </summary>
    /// <param name="size">The size of the target avatar</param>
    /// <param name="callback">The callback that will be made when the picture finishes downloading.</param>
    /// <returns></returns>
    public static IEnumerator GetDefaultAvatarCoroutine(this DiscordRPC.User user, DiscordAvatarSize size = DiscordAvatarSize.x128, DiscordUser.AvatarDownloadCallback callback = null)
    {
        var du = new DiscordUser(user);

        return(du.GetDefaultAvatarCoroutine(size, callback));
    }
Beispiel #5
0
    /// <summary>
    /// Gets the user avatar as a Texture2D and starts it with the supplied monobehaviour. It will first check the cache if the image exists, if it does it will return the image. Otherwise it will download the image from Discord and store it in the cache, calling the callback once done.
    /// <para>An alias of <see cref="DiscordUser.CacheAvatar(MonoBehaviour, DiscordAvatarSize, AvatarDownloadCallback)"/> and will return the new <see cref="DiscordUser"/> instance.</para>
    /// </summary>
    /// <param name="coroutineCaller">The target object that will start the coroutine</param>
    /// <param name="size">The target size of the avatar. Default is 128x128</param>
    /// <param name="callback">The callback for when the texture completes. Default is no-callback, but its highly recommended to use a callback</param>
    /// <returns>Returns the generated <see cref="DiscordUser"/> for this <see cref="DiscordRPC.User"/> object.</returns>
    public static DiscordUser GetAvatar(this DiscordRPC.User user, MonoBehaviour coroutineCaller, DiscordAvatarSize size = DiscordAvatarSize.x128, DiscordUser.AvatarDownloadCallback callback = null)
    {
        var du = new DiscordUser(user);

        du.GetAvatar(coroutineCaller, size, callback);
        return(du);
    }
Beispiel #6
0
 public IEnumerator CacheDefaultAvatarCoroutine(DiscordAvatarSize size = DiscordAvatarSize.x128, AvatarDownloadCallback callback = null)
 {
     return(GetDefaultAvatarCoroutine(size, callback));
 }
Beispiel #7
0
 public void CacheAvatar(MonoBehaviour coroutineCaller, DiscordAvatarSize size = DiscordAvatarSize.x128, AvatarDownloadCallback callback = null)
 {
     GetAvatar(coroutineCaller, size, callback);
 }
Beispiel #8
0
    /// <summary>
    /// Gets the user avatar as a Texture2D as a enumerator. It will first check the cache if the image exists, if it does it will return the image. Otherwise it will download the image from Discord and store it in the cache, calling the callback once done.
    /// </summary>
    /// <param name="size">The target size of the avatar. Default is 128x128</param>
    /// <param name="callback">The callback for when the texture completes. Default is no-callback, but its highly recommended to use a callback</param>
    /// <returns></returns>
    public IEnumerator GetAvatarCoroutine(DiscordAvatarSize size = DiscordAvatarSize.x128, AvatarDownloadCallback callback = null)
    {
        if (string.IsNullOrEmpty(_avatarHash))
        {
            yield return(GetDefaultAvatarCoroutine(size, callback));
        }
        else
        {
            //Generate the path name
            string filename = string.Format("{0}-{1}{2}.{3}", discriminator, avatarHash, size.ToString(), DiscordUser.AvatarFormat.ToString().ToLowerInvariant());

            string cache = Path.Combine(Application.dataPath, CacheDirectory);
            string path  = Path.Combine(cache, filename);

            //The holder texture is null, so we should create new one
            Texture2D avatarTexture = new Texture2D((int)size, (int)size, TextureFormat.RGBA32, false);

            //Check if the file exists
            if (File.Exists(path))
            {
                //Load the image
                var bytes = File.ReadAllBytes(path);
                avatarTexture.LoadImage(bytes);
            }
            else
            {
                using (WWW www = new WWW(GetAvatarURL(DiscordUser.AvatarFormat, size)))
                {
                    //Download the texture
                    yield return(www);

                    //Update the holder
                    www.LoadImageIntoTexture(avatarTexture);

                    //Create the directory if it doesnt already exist
                    if (!Directory.Exists(cache))
                    {
                        Directory.CreateDirectory(cache);
                    }

                    //Encode the image
                    byte[] bytes;
                    switch (DiscordUser.AvatarFormat)
                    {
                    default:
                    case DiscordAvatarFormat.PNG:
                        bytes = avatarTexture.EncodeToPNG();
                        break;

                    case DiscordAvatarFormat.JPEG:
                        bytes = avatarTexture.EncodeToJPG();
                        break;
                    }

                    //Save the image
                    File.WriteAllBytes(path, bytes);
                }
            }

            //Apply our avatar and update our cache
            _avatar      = avatarTexture;
            _cacheFormat = DiscordUser.AvatarFormat;
            _cachePath   = path;
            _cacheSize   = size;

            //Execute the callback (if any)
            if (callback != null)
            {
                callback.Invoke(this, avatarTexture);
            }
        }
    }
Beispiel #9
0
 /// <summary>
 /// Gets the user avatar as a Texture2D and starts it with the supplied monobehaviour. It will first check the cache if the image exists, if it does it will return the image. Otherwise it will download the image from Discord and store it in the cache, calling the callback once done.
 /// </summary>
 /// <param name="coroutineCaller">The target object that will start the coroutine</param>
 /// <param name="size">The target size of the avatar. Default is 128x128</param>
 /// <param name="callback">The callback for when the texture completes. Default is no-callback, but its highly recommended to use a callback</param>
 /// <returns></returns>
 public void GetAvatar(MonoBehaviour coroutineCaller, DiscordAvatarSize size = DiscordAvatarSize.x128, AvatarDownloadCallback callback = null)
 {
     coroutineCaller.StartCoroutine(GetAvatarCoroutine(size, callback));
 }
Beispiel #10
0
    /// <summary>
    /// Gets the default avatar for the given user. Will check the cache first, and if none are available it will then download the default from discord.
    /// <para>If <see cref="CacheLevel"/> has <see cref="CacheLevelFlag.Size"/> set, then the size will be ignored and <see cref="DiscordAvatarSize.x512"/> will be used instead.</para>
    /// <para>If <see cref="CacheLevel"/> is <see cref="CacheLevelFlag.None"/>, then no files will be written for cache.</para>
    /// </summary>
    /// <param name="size">The size of the target avatar</param>
    /// <param name="callback">The callback that will be made when the picture finishes downloading.</param>
    ///
    /// <returns></returns>
    public IEnumerator GetDefaultAvatarCoroutine(DiscordAvatarSize size = DiscordAvatarSize.x128, AvatarDownloadCallback callback = null)
    {
        //Calculate the discrim number and prepare the cache path
        int    discrim = discriminator % 5;
        string path    = null;

        //Update the default cache just incase its null
        if (CacheLevel != CacheLevelFlag.None)
        {
            //Setup the dir
            SetupDefaultCacheDirectory();

            //should we cache the size?
            bool cacheSize = (CacheLevel & CacheLevelFlag.Size) == CacheLevelFlag.Size;
            if (!cacheSize)
            {
                size = DiscordAvatarSize.x512;
            }

            string filename = string.Format("default-{0}{1}.png", discrim, cacheSize ? size.ToString() : "");
            path = Path.Combine(CacheDirectory, filename);
        }

        //The holder texture is null, so we should create new one
        Texture2D avatarTexture = new Texture2D((int)size, (int)size, TextureFormat.RGBA32, false);

        //Check if the file exists
        if (CacheLevel != CacheLevelFlag.None && File.Exists(path))
        {
            //Load the image
            byte[] bytes = File.ReadAllBytes(path);
            avatarTexture.LoadImage(bytes);
        }
        else
        {
            string url = string.Format("https://{0}/embed/avatars/{1}.png?size={2}", _cdnEndpoint, discrim, (int)size);
            using (WWW www = new WWW(url))
            {
                //Download the texture
                yield return(www);

                //Update the holder
                www.LoadImageIntoTexture(avatarTexture);

                //We have been told to cache, so do so.
                if (CacheLevel != CacheLevelFlag.None)
                {
                    //Create the directory if it doesnt already exist
                    if (!Directory.Exists(CacheDirectory))
                    {
                        Directory.CreateDirectory(CacheDirectory);
                    }

                    byte[] bytes = avatarTexture.EncodeToPNG();
                    File.WriteAllBytes(path, bytes);
                }
            }
        }

        //Apply our avatar and update our cache
        _avatar      = avatarTexture;
        _cacheFormat = DiscordAvatarFormat.PNG;
        _cacheSize   = size;

        //Execute the callback (if any)
        if (callback != null)
        {
            callback.Invoke(this, _avatar);
        }
    }
Beispiel #11
0
    /// <summary>
    /// Gets the user avatar as a Texture2D as a enumerator. It will first check the cache if the image exists, if it does it will return the image. Otherwise it will download the image from Discord and store it in the cache, calling the callback once done.
    /// <para>If <see cref="CacheLevel"/> has <see cref="CacheLevelFlag.Size"/> set, then the size will be ignored and <see cref="DiscordAvatarSize.x512"/> will be used instead.</para>
    /// <para>If <see cref="CacheLevel"/> is <see cref="CacheLevelFlag.None"/>, then no files will be written for cache.</para>
    /// </summary>
    /// <param name="size">The target size of the avatar. Default is 128x128</param>
    /// <param name="callback">The callback for when the texture completes. Default is no-callback, but its highly recommended to use a callback</param>
    /// <returns></returns>
    public IEnumerator GetAvatarCoroutine(DiscordAvatarSize size = DiscordAvatarSize.x128, AvatarDownloadCallback callback = null)
    {
        if (_avatar != null)
        {
            //Execute the callback (if any)
            if (callback != null)
            {
                callback.Invoke(this, _avatar);
            }

            //Stop here, we did all we need to do
            yield break;
        }

        if (string.IsNullOrEmpty(_avatarHash))
        {
            yield return(GetDefaultAvatarCoroutine(size, callback));
        }
        else
        {
            //Prepare the cache path
            string path = null;

            //Build the formatting
            if (CacheLevel != CacheLevelFlag.None)
            {
                //Update the default cache just incase its null
                SetupDefaultCacheDirectory();

                string format = "{0}";
                if ((CacheLevel & CacheLevelFlag.Hash) == CacheLevelFlag.Hash)
                {
                    format += "-{1}";
                }
                if ((CacheLevel & CacheLevelFlag.Size) == CacheLevelFlag.Size)
                {
                    format += "{2}";
                }
                else
                {
                    size = DiscordAvatarSize.x512;
                }

                //Generate the path name
                string filename = string.Format(format + ".{3}", ID, avatarHash, size.ToString(), DiscordUser.AvatarFormat.ToString().ToLowerInvariant());
                path = Path.Combine(CacheDirectory, filename);
                Debug.Log("<color=#FA0B0F>Cache:</color> " + path);
            }

            //The holder texture is null, so we should create new one
            Texture2D avatarTexture = new Texture2D((int)size, (int)size, TextureFormat.RGBA32, false);

            //Check if the file exists and we have caching enabled
            if (CacheLevel != CacheLevelFlag.None && File.Exists(path))
            {
                Debug.Log("<color=#FA0B0F>Read Cache:</color> " + path);

                //Load the image
                var bytes = File.ReadAllBytes(path);
                avatarTexture.LoadImage(bytes);
            }
            else
            {
                using (WWW www = new WWW(GetAvatarURL(DiscordUser.AvatarFormat, size)))
                {
                    //Download the texture
                    yield return(www);

                    //Update the holder
                    www.LoadImageIntoTexture(avatarTexture);

                    //Encode and cache the files
                    if (CacheLevel != CacheLevelFlag.None)
                    {
                        //Create the directory if it doesnt already exist
                        if (!Directory.Exists(CacheDirectory))
                        {
                            Directory.CreateDirectory(CacheDirectory);
                        }

                        Debug.Log("<color=#FA0B0F>Saving Cache:</color> " + path);

                        //Encode the image
                        byte[] bytes;
                        switch (DiscordUser.AvatarFormat)
                        {
                        default:
                        case DiscordAvatarFormat.PNG:
                            bytes = avatarTexture.EncodeToPNG();
                            break;

                        case DiscordAvatarFormat.JPEG:
                            bytes = avatarTexture.EncodeToJPG();
                            break;
                        }

                        //Save the image
                        File.WriteAllBytes(path, bytes);
                    }
                }
            }

            //Apply our avatar and update our cache
            _avatar      = avatarTexture;
            _cacheFormat = DiscordUser.AvatarFormat;
            _cacheSize   = size;

            //Execute the callback (if any)
            if (callback != null)
            {
                callback.Invoke(this, avatarTexture);
            }
        }
    }
    /// <summary>
    /// Gets the user avatar as a Texture2D as a enumerator. It will first check the cache if the image exists, if it does it will return the image. Otherwise it will download the image from Discord and store it in the cache, calling the callback once done.
    /// <para>If <see cref="CacheLevel"/> has <see cref="CacheLevelFlag.Size"/> set, then the size will be ignored and <see cref="DiscordAvatarSize.x512"/> will be used instead.</para>
    /// <para>If <see cref="CacheLevel"/> is <see cref="CacheLevelFlag.None"/>, then no files will be written for cache.</para>
    /// </summary>
    /// <param name="size">The target size of the avatar. Default is 128x128</param>
    /// <param name="callback">The callback for when the texture completes. Default is no-callback, but its highly recommended to use a callback</param>
    /// <returns></returns>
    public IEnumerator GetAvatarCoroutine(DiscordAvatarSize size = DiscordAvatarSize.x128, AvatarDownloadCallback callback = null)
    {
        if (_avatar != null)
        {
            //Execute the callback (if any)
            if (callback != null)
            {
                callback.Invoke(this, _avatar);
            }

            //Stop here, we did all we need to do
            yield break;
        }

        if (string.IsNullOrEmpty(_avatarHash))
        {
            yield return(GetDefaultAvatarCoroutine(size, callback));
        }
        else
        {
            //Prepare the cache path
            string path = null;

            //Build the formatting
            if (CacheLevel != CacheLevelFlag.None)
            {
                //Update the default cache just incase its null
                SetupDefaultCacheDirectory();

                string format = "{0}";
                if ((CacheLevel & CacheLevelFlag.Hash) == CacheLevelFlag.Hash)
                {
                    format += "-{1}";
                }
                if ((CacheLevel & CacheLevelFlag.Size) == CacheLevelFlag.Size)
                {
                    format += "{2}";
                }
                else
                {
                    size = DiscordAvatarSize.x512;
                }

                //Generate the path name
                string filename = string.Format(format + ".{3}", ID, avatarHash, size.ToString(), DiscordUser.AvatarFormat.ToString().ToLowerInvariant());
                path = Path.Combine(CacheDirectory, filename);
                Debug.Log("<color=#FA0B0F>Cache:</color> " + path);
            }

            //The holder texture is null, so we should create new one
            Texture2D avatarTexture = new Texture2D((int)size, (int)size, TextureFormat.RGBA32, false);

            //Check if the file exists and we have caching enabled
            if (CacheLevel != CacheLevelFlag.None && File.Exists(path))
            {
                Debug.Log("<color=#FA0B0F>Read Cache:</color> " + path);

                //Load the image
                var bytes = File.ReadAllBytes(path);
                avatarTexture.LoadImage(bytes);
            }
            else
            {
#if UNITY_2017_4_OR_NEWER
                using (UnityWebRequest req = UnityWebRequestTexture.GetTexture(GetAvatarURL(DiscordUser.AvatarFormat, size)))
                {
                    //Download the texture
                    yield return(req.SendWebRequest());

                    if (req.isNetworkError || req.isHttpError)
                    {
                        //Report errors
                        Debug.LogError("Failed to download user avatar: " + req.error);
                    }
                    else
                    {
                        //Update the avatar
                        avatarTexture = DownloadHandlerTexture.GetContent(req);
                    }
                }
#else
                using (WWW www = new WWW(GetAvatarURL(DiscordUser.AvatarFormat, size)))
                {
                    //Download the texture
                    yield return(www);

                    //Update the holder
                    www.LoadImageIntoTexture(avatarTexture);
                }
#endif
            }

            //Apply our avatar and update our cache
            if (avatarTexture != null)
            {
                CacheAvatarTexture(avatarTexture, path);
                _avatar      = avatarTexture;
                _cacheFormat = DiscordUser.AvatarFormat;
                _cacheSize   = size;

                //Execute the callback (if any)
                if (callback != null)
                {
                    callback.Invoke(this, avatarTexture);
                }
            }
        }
    }