-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathclass_RebrandlyApi.ahk
453 lines (360 loc) · 10.8 KB
/
class_RebrandlyApi.ahk
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/* Dependencies
#Include <functions>
#Include <WinHttpRequest>
#Include <JSON>
#Include <string_things>
#Include <HasVal>
*/
class RebrandlyApi
{
;#
static RebrandlyApiCallDelay := 200 ;number in milliseconds to wait between calls
static RebrandlyApiLastCallTimestamp := 0 ;Timestamp of last returned call, to be used in conjunction with RebrandlyApiCallDelay
static rb := "https://api.rebrandly.com/v1/"
static Account := []
static Brands := []
static Brands_id := []
static apiKey := ""
static tags := []
static tagColors := []
static tagsInit := 0
static workspaces := []
static DefaultWorkspace := []
a
registerApiKey(apiKey,getAccount := 1){
this.apiKey := apiKey
if (getAccount = 1)
this.getAccount(1)
return
}
setCallDelay(delay := ""){ ;adjusts how long in milliseconds the class waits between API calls; default = 200, minimum = 100 ;*[Rebrandly]
Switch delay{
Case !IfIs(delay,"integer"):{ ;defaults to 200ms if the delay isn't anumber
delay := 200
}
Case (delay < 100):{ ;Rebrandly API allows no more than 10 calls per second.
delay := 100
}
}
;if (!IfIs(delay,"integer"))
;delay := 200
;else if (delay < 100)
;delay := 100
return RebrandlyApiCallDelay := delay
}
callDelay(){
;msgbox % this.RebrandlyApiLastCallTimestamp
Loop{
If ((A_NowUTC - this.RebrandlyApiLastCallTimestamp) > this.RebrandlyApiCallDelay)
return
else
Sleep, 0
}
}
call(byref url, byref InOutData := "", byref LoginHeaders := "",byref debug := 0){
this.callDelay() ;wait until sufficient time has elapsed
;msgbox
If !IsObject(LoginHeaders)
LoginHeaders := []
LoginHeaders["Content-Type"] := "application/json"
LoginHeaders["apikey"] := this.apikey
For k,v in LoginHeaders
If !IsObject(v)
InOutHeaders .= k ": " v "`n"
else
InOutHeaders .= k ": " JSON.dump(v) "`n" ;dunno if this is needed, but whatever
;todo - gracefully and incrementally delay in the event of connection failure
if (debug != 3)
r := WinHttpRequest(url, InOutData, InOutHeaders, "Timeout: 1`nNO_AUTO_REDIRECT") ;query api
this.RebrandlyApiLastCallTimestamp := A_TickCount ;update info used in this.callDelay()
return this.errorHandler(InOutData,InOutHeaders,debug)
}
errorHandler(byref jsonStr, byref headers, debug := 0){
HeaderObj := []
headersPreObj := StrSplit(headers,"`n","`r",2)
HeaderObj["Status Code"] := RegExMatchGlobal(headersPreObj[1],"^.+ (\d+)",0)[1,1]
For k,v in StrSplit(headersPreObj[2],"`n","`r")
{
if (v != "")
line := StrSplit(v,":",,2)
HeaderObj[line[1]] := Trim(line[2])
}
;todo - catch e
Try
DataObj := Json.Load(jsonStr)
if (debug = 1)
msgbox % clipboard := st_printarr(DataObj)
else if (debug = 2)
msgbox % clipboard := st_printarr(HeaderObj)
/*
HTTP status Why
200 OK - Successful operations
400 Bad Request - Invalid JSON request
401 Unauthorized - Account does not have permission to perform the operation.
- OAuth token is missing or invalid/expired.
403 Forbidden - Invalid input format
- Missing body
- Limits threshold reached
404 Not Found - Resource not found
- Endpoint not found
406 Not Acceptable - No content-type specified
- Content-Type not accepted
429 Too Many Requests - Rate limit exceeded
500 Server Error - Internal API error
502 Bad Gateway - Failure in our upstream providers
503 Service Unavailable - API is experiencing a downtime
- API is under maintenance
504 Gateway Timeout - Timeout on operation
*/
Switch HeaderObj["Status Code"]
{
Case 200:{
;nothing to do, just here to give a success case
}
Case 400:{
}
Case 401:{
;json
}
Case 403:{ ;two different objects
;json
}
Case 404:{
;json
}
Case 406:{
}
Case 429:{
}
Case 500:{
;json
}
Case 502:{
}
Case 503:{
}
Case 504:{
}
Default:{
}
}
return DataObj
}
/* account
*/
getAccount(associate := 1){
;LoginHeaders := "apikey: " this.apiKey
retObj := this.call(this.rb "account",InOutData,LoginHeaders,0)
if (associate = 1)
This.associateBrands()
return retObj
}
gatherWorkspaces(){
ParamObj := [],retObj := []
Loop
{
tempObj := this.call(this.rb "account/workspaces" this.UrlParams(ParamObj),,LoginHeaders.clone())
If (tempObj.count() = 0)
Break
Loop, % tempObj.count()
{
Record := tempObj[a_index]
retObj.push(Record)
}
ParamObj["last"] := Record["id"] ;used in pagination
}
return retObj
}
/* domain
*/
getDomains(){
;todo - paginate domains
return this.call(this.rb "domains",InOutData,LoginHeaders)
}
associateBrands(){ ;collects the brands->ids into an easy to reference array
;todo - paginate domains
DataObj := this.call(this.rb "domains",InOutData,LoginHeaders)
Loop, % DataObj.count()
{
Record := DataObj[a_index]
this.Brands[Record["fullname"]] := Record["id"]
this.Brands_id[Record["id"]] := Record["fullname"]
}
DataObj := this.gatherWorkspaces()
Loop, % DataObj.count()
{
Record := DataObj[a_index]
If Record["default"]
this.DefaultWorkspace["id"] := Record["name"]
this.Workspaces[Record["id"]] := Record["name"]
}
return
}
/* link
*/
createLink(destination,slashtag := "", domainFullName := "", title := "", description := "",workspace := "", tagObj := "", tagColorObj := ""){
if (domainFullName = "") || (!this.Brands.HasKey(domainFullName))
domainFullName := "rebrand.ly" ;fallback on rebrandly in the event of mismatched keys or other error
If (workspace != "")
LoginHeaders := []
,LoginHeaders["workspace"] := workspace
DestObj := []
,DestObj["domain","id"] := this.Brands[domainFullName]
,DestObj["domain","fullName"] := this.Brands_id[this.Brands[domainFullName]]
,DestObj["slashtag"] := slashtag
,DestObj["title"] := SubStr(title,1,255) ;max 255 characters
,DestObj["description"] := SubStr(description,1,2000) ;max 2000 characters
,DestObj["destination"] := destination
;msgbox % st_printarr(DestObj)
OutObj := this.call(this.rb "links",json.dump(DestObj),LoginHeaders)
if IsObject(tagObj)
this.attachTags(OutObj["id"],tagObj,tagColorObj,workspace)
return OutObj
}
gatherLinks(domainId := "", domainFullName := "", slashtag := "", creatorId := "", orderBy := "",orderDir := "", favourite := "", workspace := "", maxResults := "", last := ""){
;maxResults is NOT limit. maxResults is the maximum amount of results *this* method will return.
retObj := []
If (workspace != "")
LoginHeaders := []
,LoginHeaders["workspace"] := workspace
ParamObj := []
,ParamObj["orderBy"] := orderBy
,ParamObj["orderDir"] := orderDir
,ParamObj["domain.id"] := domainId
,ParamObj["domain.fullName"] := domainFullName
,ParamObj["creator.id"] := creatorId ;accepts comma-delimited list
,ParamObj["favourite"] := favourite
,ParamObj["last"] := last
,ParamObj["slashtag"] := slashtag
;ParamObj["limit"] := 1 ; only for testing
Loop
{
tempObj := this.call(this.rb "links" this.UrlParams(ParamObj),,LoginHeaders.clone())
If (tempObj.count() = 0)
Break
Loop, % tempObj.count()
{
Record := tempObj[a_index]
retObj.push(Record)
;msgbox % retObj.count()
If (retObj.count() = maxResults)
Break 2
}
If (slashtag != "") ;infinite loop if there's a slashtag
return retObj
ParamObj["last"] := Record["id"] ;used in pagination
}
return retObj
}
/* tag
*/
attachTags(linkId,tagObj,tagColorObj := "",workspace := ""){
/*
"tagObj" and "tagColorObj" must be 2D arrays
key names don't matter to tagObj, will use the value
tagColorObj is in the format... tagColorObj[tagName] := FFFFFF
new tag format: ;not final?
[Workspace] ;assumed to be the default
. [name]
. . [id]
. . [color]
*/
If !IsObject(tagObj)
return
If (workspace != "")
LoginHeaders := []
,LoginHeaders["workspace"] := workspace
this.queryLinkTags(linkId, workspace) ;hopefully reduce future issues... I have no idea if it's required.
For k,v in tagObj
{
tagName := v
If !HasVal(this.tags.clone(),tagName) ;want to avoid duplicating names
{
;msgbox,here
this.createTag(tagName,tagColor,workspace)
;tagId := HasVal(this.tags,tagName)
;msgbox % HasVal(this.tags,tagName)
}
tagId := HasVal(this.tags,tagName)
checkObj := this.call(this.rb "links/" linkId "/tags/" HasVal(this.tags,tagName),InOutData,LoginHeaders)
;MsgBox % st_printarr(checkobj)
If (checkObj["Message"] = "Not Found")
checkObj := this.call(this.rb "links/" linkId "/tags/" HasVal(this.tags,tagName),InOutData,LoginHeaders) ;sometimes required... whatever.
;MsgBox % st_printarr(checkobj)
}
}
createTag(tagName, tagColor := "", workspace := ""){
If !tagsInit
this.initTags()
If (HasVal(this.tags,tagName) != 0) ;want to avoid duplicating names
return
If (workspace != "")
LoginHeaders := []
,LoginHeaders["workspace"] := workspace
InOutData := []
InOutData["name"] := tagName
If RegExMatch(tagColor,"[a-fA-F0-9]{6}")
InOutData["color"] := tagColor
newTagObj := this.call(this.rb "tags",Json.dump(InOutData),LoginHeaders)
;add the new tag data to the class's reference object
this.tags[newTagObj["id"]] := newTagObj["name"]
If newTagObj.HasKey("color")
this.tagColors[newTagObj["id"]] := newTagObj["color"]
return newTagObj
}
initTags(){
tagPreObj := this.gatherTags()
Loop, % tagPreObj.count()
{
Record := tagPreObj[a_index]
this.tags[Record["id"]] := Record["name"]
if Record.HasKey("color")
this.tagColors[Record["id"]] := Record["color"]
}
this.initTags := 1
}
queryLinkTags(linkId, workspace := ""){
If (workspace != "")
LoginHeaders := []
,LoginHeaders["workspace"] := workspace
return this.call(this.rb "links/" linkId "/tags/",InOutData,LoginHeaders)
}
gatherTags(orderBy := "",orderDir := "", workspace := "", linkId := ""){
retObj := []
If (workspace != "")
LoginHeaders := []
,LoginHeaders["workspace"] := workspace
ParamObj := []
,ParamObj["orderBy"] := orderBy
,ParamObj["orderDir"] := orderDir
;ParamObj["limit"] := 1 ; only for testing
Loop
{
tempObj := this.call(this.rb "tags" this.UrlParams(ParamObj),,LoginHeaders.clone())
If (tempObj.count() = 0)
Break
Loop, % tempObj.count()
{
Record := tempObj[a_index]
retObj.push(Record)
}
ParamObj["last"] := Record["id"] ;used in pagination
}
return retObj
}
UrlParams(ParamObj){
for k,v in ParamObj
ParamObj[k] := v
for k,v in ParamObj
{
if (k = "") || (v = "")
Continue
if (ParamStr != "")
ParamStr .= "&"
ParamStr .= k "=" v
}
if (ParamStr != "")
ParamStr := "?" ParamStr
return ParamStr
}
}