forked from supermamon/scriptable-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ig-latest-post.js
288 lines (246 loc) · 8.34 KB
/
ig-latest-post.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: pink; icon-glyph: camera-retro;
/* -----------------------------------------------
Script : ig-latest-post.js
Author : [email protected]
Version : 1.3.0
Description :
Displays the latest instagram post of a selected
user or users. Tap the widget to open the
Instagram post in the app
Limitations:
* Works only for non-private users.
* Also does not work for some regions like
Switzerland for example. Instagram prevents
viewing user metadata without being
authenticated. So, this script won't work
there.
Changelog:
v1.3.0 - Pick the highest resolution photo
v1.2.0 - Option to pick up to 12 of the most
recent posts
v1.1.0 - Options to show likes and comments count
v1.0.0 - Initial release
----------------------------------------------- */
// The script randomly chooses from this list of
// users. If a list if users is passed as a
// parameter on the widget configuration screen,
// it uses those instead.
const USERS = [
'beautifuldestinations',
'philippines',
'igersmanila',
'palmtraveller'
]
// stuff to display at the bottom of the widget
const SHOW_USERNAME = true
const SHOW_LIKES = true
const SHOW_COMMENTS = true
// pick up to 12 of the most recent posts and
// select randomly between those.
const MAX_RECENT_POSTS = 12
// desired interval in minutes to refresh the
// widget. This will only tell IOS that it's
// ready for a refresh, whether it actually
// refreshes is up to IOS
const REFRESH_INTERVAL = 5 //mins
// DO NOT EDIT BEYOND THIS LINE ------------------
// only show the staus line is any of the
// status items are visible
const SHOW_STATUS_LINE = SHOW_USERNAME ||
SHOW_LIKES ||
SHOW_COMMENTS
// get usernames from the arguments if passed
let usernames = args.widgetParameter || USERS.join(',')
usernames = usernames.split(',')
// choose a random username and fetch for the user
// information
const username = getRandom(usernames)
const post = await getLatestPost(username,
MAX_RECENT_POSTS)
if (config.runsInWidget) {
let widget = post.has_error ?
await createErrorWidget(post) :
await createWidget(post)
Script.setWidget(widget)
} else {
const options = ['Small', 'Medium', 'Large', 'Cancel']
let resp = await presentAlert('Preview Widget', options)
if (resp==options.length-1) return
let size = options[resp]
let widget = post.has_error ?
await createErrorWidget(post) :
await createWidget(post, size.toLowerCase())
await widget[`present${size}`]()
}
Script.complete()
//------------------------------------------------
async function createWidget(data, widgetFamily) {
widgetFamily = widgetFamily || config.widgetFamily
const padd = widgetFamily=='large' ? 12 : 10
const fontSize = widgetFamily=='large' ? 14 : 10
const img = await download('Image', data.display_url)
const url = `https://www.instagram.com/p/${data.shortcode}`
const widget = new ListWidget()
var refreshDate = Date.now() + 1000*60*REFRESH_INTERVAL
widget.refreshAfterDate = new Date(refreshDate)
widget.url = url
widget.setPadding(padd,padd,padd,padd)
widget.backgroundImage = img
if (SHOW_STATUS_LINE) {
// add gradient with a semi-transparent
// dark section at the bottom. this helps
// with the readability of the status line
widget.backgroundGradient = newLinearGradient(
['#ffffff00','#ffffff00','#00000088'],
[0,.75,1])
// top spacer to push the bottom stack down
widget.addSpacer()
// horizontal stack to hold the status line
const stats = widget.addStack()
stats.layoutHorizontally()
stats.centerAlignContent()
stats.spacing = 3
if (SHOW_USERNAME) {
const eUsr = addText(stats, `@${data.username}`,'left', fontSize)
}
// center spacer to push items to the sides
stats.addSpacer()
if (SHOW_LIKES) {
const heart = addSymbol(stats, 'heart.fill', fontSize)
const likes = abbreviateNumber(data.likes)
const eLikes = addText(stats, likes, 'right', fontSize)
}
if (SHOW_COMMENTS) {
const msg = addSymbol(stats, 'message.fill', fontSize)
const comments = abbreviateNumber(data.comments)
const eComm = addText(stats, comments, 'right', fontSize)
}
}
return widget
}
//------------------------------------------------
function addSymbol(container, name, size) {
const sfIcon = SFSymbol.named(name)
const fIcon = sfIcon.image
const icon = container.addImage(fIcon)
icon.tintColor = Color.white()
icon.imageSize = new Size(size,size)
return icon
}
//------------------------------------------------
function addText(container, text, align, size) {
const txt = container.addText(text)
txt[`${align}AlignText`]()
txt.font = Font.systemFont(size)
txt.shadowRadius = 3
txt.textColor = Color.white()
txt.shadowColor = Color.black()
}
//------------------------------------------------
function getRandom(array) {
return array[Math.floor(Math.random() * array.length)];
}
//------------------------------------------------
function newLinearGradient(hexcolors, locations) {
let gradient = new LinearGradient()
gradient.locations = locations
gradient.colors = hexcolors
.map(color=>new Color(color))
return gradient
}
//------------------------------------------------
async function createErrorWidget(data) {
const widget = new ListWidget()
widget.addSpacer()
const text = widget.addText(data.message)
text.textColor = Color.white()
text.centerAlignText()
widget.addSpacer()
return widget
}
//------------------------------------------------
async function download(dType, url) {
const req = new Request(url)
return await req[`load${dType}`](url)
}
//------------------------------------------------
async function getLatestPost(username, maxRecent) {
const url = `https://instagram.com/${username}?__a=1`
const req = new Request(url)
try {
var pj = await req.loadJSON()
} catch(e) {
return {
has_error: true,
message: e.message
}
}
// if there's no data
if (!pj.logging_page_id) {
return {
has_error: true,
message: 'User does not exists.'
}
}
const user = pj.graphql.user
if (user.is_private) {
return {
has_error: true,
message: `${username} is private.`
}
}
maxRecent = maxRecent > 12 ? 12 : maxRecent
let idx = Math.floor(Math.random() * maxRecent)
const rec = user.edge_owner_to_timeline_media.edges[idx].node
const preq = new Request(`https://www.instagram.com/p/${rec.shortcode}?__a=1`)
const resp = await preq.loadJSON()
const post = resp.graphql.shortcode_media;
var caption = ''
if (post.edge_media_to_caption.edges.length) {
caption = post.edge_media_to_caption.edges[0].node.text
}
let media_url = post.display_url
if (post.hasOwnProperty('display_resources')) {
log('has display resources')
media_url = post.display_resources[post.display_resources.length-1].src
}
return {
has_error: false,
username: username,
shortcode: post.shortcode,
display_url: media_url,
is_video: post.is_video,
caption: caption,
comments: post.edge_media_preview_comment.count,
likes: post.edge_media_preview_like.count
}
}
//------------------------------------------------
async function presentAlert(prompt,items,asSheet)
{
let alert = new Alert()
alert.message = prompt
for (const item of items) {
alert.addAction(item)
}
let resp = asSheet ?
await alert.presentSheet() :
await alert.presentAlert()
return resp
}
//------------------------------------------------
// found on : https://stackoverflow.com/a/32638472
// thanks @D.Deriso
function abbreviateNumber(num, fixed) {
if (num === null) { return null; } // terminate early
if (num === 0) { return '0'; } // terminate early
fixed = (!fixed || fixed < 0) ? 0 : fixed; // number of decimal places to show
var b = (num).toPrecision(2).split("e"), // get power
k = b.length === 1 ? 0 : Math.floor(Math.min(b[1].slice(1), 14) / 3), // floor at decimals, ceiling at trillions
c = k < 1 ? num.toFixed(0 + fixed) : (num / Math.pow(10, k * 3) ).toFixed(1 + fixed), // divide by power
d = c < 0 ? c : Math.abs(c), // enforce -0 is 0
e = d + ['', 'K', 'M', 'B', 'T'][k]; // append power
return e;
}