Skip to content
This repository was archived by the owner on Apr 3, 2025. It is now read-only.

Commit 672f73f

Browse files
authored
fix: generate uuid for request (#228)
1 parent 0b196a9 commit 672f73f

File tree

2 files changed

+220
-336
lines changed

2 files changed

+220
-336
lines changed

scripts/blog.yaml

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
apiVersion: batch/v1
2+
kind: CronJob
3+
metadata:
4+
name: strapi-update-cronjob
5+
spec:
6+
schedule: "0 0 * * *" # Run daily at midnight
7+
jobTemplate:
8+
spec:
9+
template:
10+
spec:
11+
containers:
12+
- name: strapi-update-container
13+
image: python:3.9 # Use a Python Docker image
14+
command: ["/bin/sh", "/scripts/entrypoint.sh"]
15+
volumeMounts:
16+
- name: script-volume
17+
mountPath: /scripts
18+
restartPolicy: OnFailure
19+
volumes:
20+
- name: script-volume
21+
configMap:
22+
name: strapi-update-script
23+
---
24+
apiVersion: v1
25+
kind: ConfigMap
26+
metadata:
27+
name: strapi-update-script
28+
data:
29+
entrypoint.sh: |
30+
#!/bin/sh
31+
set -e
32+
33+
# Install the required Python packages
34+
pip install requests python-dateutil Pillow
35+
36+
# Run the Python script
37+
python /scripts/strapi_update_script.py
38+
strapi_update_script.py: |
39+
import requests
40+
import json
41+
from datetime import datetime
42+
import os
43+
import re
44+
import uuid
45+
46+
# Strapi API URL and API key
47+
strapi_blog_url = ""
48+
strapi_upload_url = ""
49+
API_KEY = ""
50+
51+
# Function to generate a unique UUID code
52+
def generate_code():
53+
new_code = str(uuid.uuid4())
54+
return new_code
55+
56+
# Function to fetch blogs from Strapi
57+
def fetch_strapi_blogs():
58+
response = requests.get(f"{strapi_blog_url}?_limit=100", headers={"Authorization": f"Bearer {API_KEY}"})
59+
if response.status_code == 200:
60+
return response.json()['results']
61+
else:
62+
print(f"Failed to fetch blogs from Strapi: {response.text}")
63+
return []
64+
65+
# Function to create entries in Strapi
66+
def create_entries(data_array):
67+
for data in data_array:
68+
response = requests.post(
69+
strapi_blog_url,
70+
json=data,
71+
headers={"Content-Type": "application/json", "Authorization": f"bearer {API_KEY}",},
72+
)
73+
if response.status_code == 200:
74+
print(f"Entry created successfully: {data}")
75+
else:
76+
print(f"Failed to create entry: {data}")
77+
print(f"Response: {response.text}")
78+
79+
# Function to create a slug from a title
80+
def create_slug(title):
81+
slug = title.lower().replace(" ", "-")
82+
slug = re.sub(r'[^A-Za-z0-9-_.~]', '', slug)
83+
return slug
84+
85+
# Helper function to download an image
86+
def download_image(url, filename):
87+
response = requests.get(url)
88+
if response.status_code == 200:
89+
with open(filename, 'wb') as file:
90+
file.write(response.content)
91+
print(f"Downloaded image: {filename}")
92+
else:
93+
print(f"Failed to download image: {url}")
94+
95+
# Function to upload an image to Strapi
96+
def upload_image_to_strapi(image_path):
97+
files = {'files': open(image_path, 'rb')}
98+
headers = {'Authorization': f'Bearer {API_KEY}'}
99+
response = requests.post(strapi_upload_url, headers=headers, files=files)
100+
if response.status_code == 200:
101+
print(f"Uploaded image: {response.json()[0]['id']}")
102+
return response.json()[0]['id']
103+
else:
104+
print(f"Failed to upload image to Strapi: {response.content}")
105+
return None
106+
107+
# Generate the code for anonymousUserId
108+
anonymous_user_id = generate_code()
109+
110+
# Define the URL and headers for the request
111+
url = "https://taiko.mirror.xyz/api/graphql"
112+
headers = {
113+
'accept': '*/*',
114+
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
115+
'content-type': 'application/json',
116+
'cookie': f'anonymousUserId={anonymous_user_id};',
117+
'origin': 'https://taiko.mirror.xyz',
118+
'priority': 'u=1, i',
119+
'referer': 'https://taiko.mirror.xyz/',
120+
'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
121+
'sec-ch-ua-mobile': '?0',
122+
'sec-ch-ua-platform': '"macOS"',
123+
'sec-fetch-dest': 'empty',
124+
'sec-fetch-mode': 'cors',
125+
'sec-fetch-site': 'same-origin',
126+
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
127+
}
128+
129+
# Define the payload for the request
130+
payload = {
131+
"operationName": "ProjectPage",
132+
"variables": {
133+
"projectAddress": "taiko.mirror.xyz",
134+
"limit": 10
135+
},
136+
"query": """
137+
query ProjectPage($projectAddress: String!, $limit: Int, $cursor: Int) {
138+
projectFeed(projectAddress: $projectAddress, limit: $limit, cursor: $cursor) {
139+
...projectPage
140+
}
141+
}
142+
fragment projectPage on ProjectType {
143+
posts {
144+
... on entry {
145+
_id
146+
id
147+
digest
148+
title
149+
publishedAtTimestamp
150+
featuredImage {
151+
url
152+
}
153+
}
154+
}
155+
}
156+
"""
157+
}
158+
159+
# Fetch existing blogs from Strapi
160+
strapi_blogs = fetch_strapi_blogs()
161+
strapi_link = [blog['link'] for blog in strapi_blogs]
162+
163+
# Make the request to taiko.mirror.xyz
164+
response = requests.post(url, headers=headers, json=payload)
165+
data = response.json()
166+
transformed_data_list = []
167+
168+
# Process each post
169+
for post in data['data']['projectFeed']['posts']:
170+
post_id = post['_id']
171+
link = f"https://taiko.mirror.xyz/{post_id}"
172+
title = post.get('title', 'N/A')
173+
published_at = post.get('publishedAtTimestamp', 'N/A')
174+
featured_image_url = post.get('featuredImage', {}).get('url', 'N/A')
175+
formatted_date = datetime.fromtimestamp(published_at).strftime('%Y-%m-%d') if published_at != 'N/A' else 'N/A'
176+
slug = create_slug(title)
177+
if link not in strapi_link:
178+
print("Unpublished blog: "+ title)
179+
# Download featured image
180+
imgid = "placeholder_imgid"
181+
if featured_image_url != 'N/A':
182+
img_filename = os.path.basename(featured_image_url.split('?')[0]) # Remove query parameters from URL
183+
download_image(featured_image_url, img_filename)
184+
imgid = upload_image_to_strapi(img_filename)
185+
186+
# Transform the data into the desired format
187+
transformed_data = {
188+
"category": {
189+
"disconnect": [],
190+
"connect": [{"id": 1, "position": {"end": True}}]
191+
},
192+
"slug": slug,
193+
"link": f"https://taiko.mirror.xyz/{post_id}",
194+
"date": formatted_date,
195+
"content": [
196+
{
197+
"type": "paragraph",
198+
"children": [
199+
{"type": "text", "text": title}
200+
]
201+
}
202+
],
203+
"howToApply": [
204+
{
205+
"type": "paragraph",
206+
"children": [
207+
{"type": "text", "text": "Visit our github"}
208+
]
209+
}
210+
],
211+
"title": title,
212+
"timeToRead": "6 min",
213+
"image": imgid,
214+
}
215+
216+
# Add to the list
217+
transformed_data_list.append(transformed_data)
218+
219+
# Create new entries in Strapi
220+
create_entries(transformed_data_list)

0 commit comments

Comments
 (0)