import json
from math import ceil
from sys import exit
from time import sleep
import textwrap
import twitter
from PIL import Image, ImageDraw
from logger import Log
from util import ImageUtil, Utility
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Athena:
"""Fortnite Item Shop Generator."""
def main(self):
Log.Intro(self, "Fortnite Akademi Kozmetik Arama")
Log.Intro(self, "https://www.instagram.com/fortakademi/\n")
initialized = Athena.LoadConfiguration(self)
if initialized is True:
if self.delay > 0:
Log.Info(self, f"Delaying process start for {self.delay}s...")
sleep(self.delay)
ara = input("Aranacak Kozmetik : ")
itemShop = Utility.GET(self, f"https://fortnite-api.com/cosmetics/br/search/all?language=tr&searchLanguage=tr&matchMethod=contains&series={ara}")
if itemShop is not None:
itemShop = json.loads(itemShop)
with open('data.txt', 'w') as outfile:
json.dump(itemShop, outfile)
# Strip time from the timestamp, we only need the date
Log.Success(self, f"İçerik Yüklendi")
shopImage = Athena.GenerateImage(self, itemShop)
if shopImage is True:
if self.twitterEnabled is True:
Athena.Tweet(self, date)
def LoadConfiguration(self):
"""
Set the configuration values specified in configuration.json
Return True if configuration sucessfully loaded.
"""
configuration = json.loads(Utility.ReadFile(self, "configuration", "json"))
try:
self.delay = configuration["delayStart"]
self.supportACreator = configuration["supportACreator"]
self.twitterEnabled = configuration["twitter"]["enabled"]
self.twitterAPIKey = configuration["twitter"]["apiKey"]
self.twitterAPISecret = configuration["twitter"]["apiSecret"]
self.twitterAccessToken = configuration["twitter"]["accessToken"]
self.twitterAccessSecret = configuration["twitter"]["accessSecret"]
Log.Success(self, "Ayarlar Yüklendi")
return True
except Exception as e:
Log.Error(self, f"Failed to load configuration, {e}")
def GenerateImage(self, itemShop: dict):
"""
Generate the Item Shop image using the provided Item Shop.
Return True if image sucessfully saved.
"""
try:
sonuclar = itemShop["data"]
# Ensure both Featured and Daily have at least 1 item
if (len(sonuclar) <= 0):
raise Exception(f"Sonuç Sayısı: {len(sonuclar)}")
except Exception as e:
Log.Error(self, f"Failed to parse Item Shop Featured and Daily items, {e}")
return False
# Determine the max amount of rows required for the current
# Item Shop when there are 3 columns for both Featured and Daily.
# This allows us to determine the image height.
rows = (ceil(len(sonuclar) / 6))
shopImage = Image.new("RGBA", (1920, ((545 * rows) + 340)))
esyalar = sonuclar
# Track grid position
i = 0
for item in esyalar:
card = Athena.GenerateCard(self, item)
card.save( f"Sonuç: {i}.png")
if card is not None:
shopImage.paste(
card,
(
(47 + ((i % 6) * (card.width + 5))),
(45 + ((i // 6) * (card.height + 5))),
),
card,
)
i += 1
# Reset grid position
try:
shopImage.save("sonuc.png")
Log.Success(self, "PNG Sonuç Oluşturuldu.")
magazaImage = Image.new("RGB", (1500, 1500))
backgrounda = ImageUtil.Open(self, "akademibg4.png")
magazaImage.paste(
backgrounda, ImageUtil.CenterX(self, backgrounda.width, magazaImage.width)
)
shopImage = ImageUtil.RatioResize1(
self, shopImage, (magazaImage.width-35), (magazaImage.height-50)
)
magazaImage.paste(
shopImage, ImageUtil.CenterX(self, shopImage.width, magazaImage.width, 35), shopImage
)
magazaImage.save("sonuc1.png")
Log.Success(self, "Sayfa Gönderisi Oluşturuldu.")
return True
except Exception as e:
Log.Error(self, f"Failed to save Item Shop image, {e}")
def GenerateCard(self, item: dict):
"""Return the card image for the provided Fortnite Item Shop item."""
try:
name = item["name"]
rarity = item["rarity"]
aciklama = item["description"]
if rarity == "common":
rarity = "Yaygın"
elif rarity == "uncommon":
rarity = "Sıradışı"
elif rarity == "rare":
rarity = "Nadir"
elif rarity == "epic":
rarity = "Destansı"
elif rarity == "legendary":
rarity = "Efsanevi"
elif rarity == "marvel":
rarity = "Marvel"
elif rarity == "dark":
rarity = "Karanlık"
elif rarity == "DC":
rarity = "DC"
elif rarity == "shadow":
rarity = "Gölge"
category = item["shortDescription"]
if (category == "Kıyafet") or (category == "Wrap"):
if item["images"]["featured"] is not None:
Log.Success(self, "Featured resim var.")
icon = item["images"]["featured"]["url"]
Log.Success(self, "Featured resim seçildi.")
else:
icon = item["images"]["icon"]["url"]
Log.Success(self, "İkon resmi seçildi.")
if category == "Emoji":
icon = item["images"]["smallIcon"]["url"]
else:
icon = item["images"]["icon"]["url"]
Log.Success(self, "2İkon resmi seçildi.")
except Exception as e:
Log.Error(self, f"Failed to parse item {name}, {e}")
return
if rarity == "Yaygın":
blendColor = (190, 190, 190)
elif rarity == "Sıradışı":
blendColor = (96, 170, 58)
elif rarity == "Nadir":
blendColor = (73, 172, 242)
elif rarity == "Destansı":
blendColor = (177, 91, 226)
elif rarity == "Efsanevi":
blendColor = (211, 120, 65)
elif rarity == "Marvel":
blendColor = (197, 51, 52)
elif rarity == "Karanlık":
blendColor = (251, 34, 223)
elif rarity == "DC":
blendColor = (84, 117, 199)
else:
blendColor = (255, 255, 255)
card = Image.new("RGBA", (300, 545))
try:
layer = ImageUtil.Open(self, f"card_top_{rarity.lower()}.png")
except FileNotFoundError:
Log.Warn(
self,
f"Failed to open card_top_{rarity.lower()}.png, defaulted to Common",
)
layer = ImageUtil.Open(self, "card_top_yaygın.png")
card.paste(layer)
icon = ImageUtil.Download(self, icon)
icon = ImageUtil.RatioResize(self, icon, 285, 365)
card.paste(icon, ImageUtil.CenterX(self, icon.width, card.width), icon)
try:
layer = ImageUtil.Open(self, f"card_faceplate_{rarity.lower()}.png")
except FileNotFoundError:
Log.Warn(
self,
f"Failed to open card_faceplate_{rarity.lower()}.png, defaulted to Common",
)
layer = ImageUtil.Open(self, "card_faceplate_yaygın.png")
card.paste(layer, layer)
try:
layer = ImageUtil.Open(self, f"card_bottom_{rarity.lower()}.png")
except FileNotFoundError:
Log.Warn(
self,
f"Failed to open card_bottom_{rarity.lower()}.png, defaulted to Common",
)
layer = ImageUtil.Open(self, "card_bottom_yaygın.png")
card.paste(layer, layer)
canvas = ImageDraw.Draw(card)
font = ImageUtil.Font(self, 30)
textWidth, _ = font.getsize(f"{rarity} {category}")
canvas.text(
ImageUtil.CenterX(self, textWidth, card.width, 385),
f"{rarity} {category}",
blendColor,
font=font,
)
font = ImageUtil.Font(self, 50)
textWidth, _ = font.getsize(name)
if textWidth >= 270:
# Ensure that the item name does not overflow
font, textWidth = ImageUtil.FitTextX(self, name, 56, 265)
canvas.text(
ImageUtil.CenterX(self, textWidth, card.width, 425),
name,
(255, 255, 255),
font=font,
)
font = ImageUtil.Font(self, 22,)
textWidth, _ = font.getsize(aciklama)
if textWidth >= 270:
# Ensure that the item name does not overflow
font, textWidth = ImageUtil.FitTextX(self, aciklama, 56, 265)
canvas.text(
ImageUtil.CenterX(self, textWidth, card.width, 480),
textwrap.fill(aciklama, 55),
(255, 255, 255),
font=font,
)
Log.Intro(self, f"{name} - {aciklama}")
return card
def Tweet(self, date: str):
"""
Tweet the current `itemshop.png` local file to Twitter using the credentials provided
in `configuration.json`.
"""
try:
twitterAPI = twitter.Api(
consumer_key=self.twitterAPIKey,
consumer_secret=self.twitterAPISecret,
access_token_key=self.twitterAccessToken,
access_token_secret=self.twitterAccessSecret,
)
twitterAPI.VerifyCredentials()
except Exception as e:
Log.Error(self, f"Failed to authenticate with Twitter, {e}")
return
body = f"#Fortnite Item Shop for {date}"
if self.supportACreator is not None:
body = f"{body}\n\nSupport-a-Creator Code: {self.supportACreator}"
try:
with open("itemshop.png", "rb") as shopImage:
twitterAPI.PostUpdate(body, media=shopImage)
Log.Success(self, "Tweeted Item Shop")
except Exception as e:
Log.Error(self, f"Failed to Tweet Item Shop, {e}")
if __name__ == "__main__":
try:
Athena.main(Athena)
except KeyboardInterrupt:
Log.Info(Athena, "Exiting...")
exit()