Skip to content

Instantly share code, notes, and snippets.

@os11k
Last active October 26, 2024 13:30
Show Gist options
  • Save os11k/1f109155706ce2bef8b68ea61a324126 to your computer and use it in GitHub Desktop.
Save os11k/1f109155706ce2bef8b68ea61a324126 to your computer and use it in GitHub Desktop.
Check followers, visitors and refresh token
// Function to save the token to iCloud
async function saveAccessToken(token) {
let fileManager = FileManager.iCloud();
let filePath = fileManager.joinPath(fileManager.documentsDirectory(), "threads_token.txt");
// Save the token to iCloud
fileManager.writeString(filePath, token);
console.log("Access token saved to iCloud.");
}
// Function to refresh the access token
async function refreshAccessToken(currentToken) {
const refreshApiUrl = `https://graph.threads.net/refresh_access_token?grant_type=th_refresh_token&access_token=${currentToken}`;
try {
let request = new Request(refreshApiUrl);
let response = await request.loadJSON();
let newToken = response.access_token;
console.log("New token retrieved:", newToken);
// Save the new token to iCloud
await saveAccessToken(newToken);
return newToken;
} catch (error) {
console.error("Error refreshing token: " + error);
return null;
}
}
// Function to get the access token from iCloud
async function getAccessToken() {
let fileManager = FileManager.iCloud();
let filePath = fileManager.joinPath(fileManager.documentsDirectory(), "threads_token.txt");
// Check if the file exists
if (!fileManager.fileExists(filePath)) {
console.error("Token file does not exist. Please save the token in iCloud first.");
return null;
}
// Make sure the file is downloaded from iCloud if not already available
if (!fileManager.isFileDownloaded(filePath)) {
await fileManager.downloadFileFromiCloud(filePath);
}
// Read and return the token
let token = fileManager.readString(filePath);
console.log("Access token retrieved:", token);
return token;
}
// Function to fetch follower count
async function getFollowerCount() {
let accessToken = await getAccessToken(); // Get the token from iCloud
// Refresh the token every time the widget is refreshed
accessToken = await refreshAccessToken(accessToken); // Refresh token on each widget update
if (!accessToken) {
console.error("No access token found.");
return null;
}
// Define the API URL with the retrieved token
const apiUrl = `https://graph.threads.net/v1.0/me/threads_insights?metric=followers_count&access_token=${accessToken}`;
try {
// Make the API request
let request = new Request(apiUrl);
let response = await request.loadJSON();
// Extract followers count from the response
let followersCount = response.data[0].total_value.value;
// Return the followers count
return followersCount;
} catch (error) {
console.error("Error fetching followers data: " + error);
return null;
}
}
// Function to fetch today's and yesterday's visitors
async function getVisitorCount() {
let accessToken = await getAccessToken(); // Get the token from iCloud
if (!accessToken) {
console.error("No access token found.");
return null;
}
// Define the API URL with the retrieved token
const apiUrl = `https://graph.threads.net/v1.0/me/threads_insights?metric=views&access_token=${accessToken}`;
try {
// Make the API request
let request = new Request(apiUrl);
let response = await request.loadJSON();
// Extract visitors data for yesterday and today
let values = response.data[0].values;
let yesterdayCount = values[0].value;
let todayCount = values[1].value;
// Return the visitor counts for today and yesterday
return {
today: todayCount,
yesterday: yesterdayCount
};
} catch (error) {
console.error("Error fetching visitors data: " + error);
return null;
}
}
// Create the widget
async function createWidget() {
let widget = new ListWidget();
// Fetch the followers and visitors counts
let followersCount = await getFollowerCount();
let visitors = await getVisitorCount();
// Set up the widget display
if (followersCount !== null && visitors !== null) {
// Followers section
widget.addText("Followers");
let followersText = widget.addText(followersCount.toString());
followersText.font = Font.boldSystemFont(24);
// Spacer between sections
widget.addSpacer(8);
// Visitors section
widget.addText("Profile Visitors");
let todayText = widget.addText(`Today: ${visitors.today}`);
todayText.font = Font.boldSystemFont(17);
let yesterdayText = widget.addText(`Yesterday: ${visitors.yesterday}`);
yesterdayText.font = Font.boldSystemFont(17);
} else {
widget.addText("Error fetching data.");
}
widget.addSpacer();
widget.setPadding(16, 16, 16, 16);
// Set the widget to refresh every 15 minutes
let nextRefreshDate = new Date();
nextRefreshDate.setMinutes(nextRefreshDate.getMinutes() + 15);
widget.refreshAfterDate = nextRefreshDate;
return widget;
}
// Check if the script is running in widget mode
if (config.runsInWidget) {
// Create and set the widget
let widget = await createWidget();
Script.setWidget(widget);
Script.complete();
} else {
// If not in widget mode, preview the widget
let widget = await createWidget();
widget.presentSmall();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment