コード例 #1
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);
        }
    }
コード例 #2
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);
            }
        }
    }
コード例 #3
0
ファイル: DiscordUser.cs プロジェクト: Lachee/CISandbox
    /// <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);
            }
        }
    }
コード例 #4
0
ファイル: DiscordUser.cs プロジェクト: Lachee/CISandbox
    /// <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);
        }
    }
コード例 #5
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
            {
#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);
                }
            }
        }
    }