-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlibodon.js
More file actions
221 lines (206 loc) · 7.42 KB
/
libodon.js
File metadata and controls
221 lines (206 loc) · 7.42 KB
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
(function(){
class Libodon {
constructor(appname, redirect_url, scope){
this.appname = appname
this.redirect_url = redirect_url
this.scope = scope
}
connect(server, username){
let connection_resolve, connection_reject, registration;
connections.push(new Promise((resolve,reject)=>{
connection_resolve=resolve
connection_reject=reject
}))
active_connection = connections.length-1
return get_registration(server, this)
.then(reg=>{
registration = reg
return get_token(server, reg)
})
.then(
token=>{
connection_resolve({server:server,token:token})
return {result:'success'}
},
error=>{
active_connection = undefined
connection_reject({error:'failed connection'})
return {result:'redirect',target:get_authorization_url(server, registration, this)}
})
}
timeline(target, options){
let endpoint = ''
switch(target){
case 'home': endpoint = '/api/v1/timelines/home'; break
case 'mentions': endpoint = '/api/v1/timelines/mentions'; break
case 'public': endpoint = '/api/v1/timelines/public'; break
default:
if(target.substring(0,1)=='#')
endpoint = '/api/v1/timelines/tag/'+target.substring(1)
break
}
if(endpoint=='') return Promise.reject('invalid timeline target')
return get_request(endpoint+timeline_options(options))
}
status(id){return get_request('/api/v1/statuses/'+id)}
account(id){return get_request('/api/v1/accounts/'+id)}
account_self(){return get_request('/api/v1/accounts/verify_credentials')}
account_statuses(id,options){
return get_request('/api/v1/accounts/'+id+'/statuses'+timeline_options(options))
}
followers(id){return get_request('/api/v1/accounts/'+id+'/followers')}
relationships(...ids){
if(!ids.length) return Promise.reject('no id given')
let query_parameters = '?'
if(ids.length == 1) query_parameters += 'id='+ids[0]
else query_parameters += 'id[]='+ids.join('&id[]=')
return get_request('/api/v1/accounts/relationships'+query_parameters)
}
suggestions(){return get_request('/api/v1/accounts/suggestions')}
context(id){return get_request('/api/v1/statuses/'+id+'/context')}
reblogged_by(id){return get_request('/api/v1/statuses/'+id+'/reblogged_by')}
favourited_by(id){return get_request('/api/v1/statuses/'+id+'/favourited_by')}
follow_remote(url){return post_request('/api/v1/follows',{uri:url})}
reblog(id){return post_request('/api/v1/statuses/'+id+'/reblog')}
unreblog(id){return post_request('/api/v1/statuses/'+id+'/unreblog')}
favourite(id){return post_request('/api/v1/statuses/'+id+'/favourite')}
unfavourite(id){return post_request('/api/v1/statuses/'+id+'/unfavourite')}
follow(id){return post_request('/api/v1/accounts/'+id+'/follow')}
unfollow(id){return post_request('/api/v1/accounts/'+id+'/unfollow')}
block(id){return post_request('/api/v1/accounts/'+id+'/block')}
unblock(id){return post_request('/api/v1/accounts/'+id+'/unblock')}
use_errorlog(){log_errors=true}
use_actionlog(){log_actions=true}
}
this.Libodon = Libodon
const connections = []
let active_connection = undefined;
const prefix = 'libodon'
let log_errors = false
let log_actions = false
function timeline_options(options){
if(typeof options == 'object'){
const params = []
if(options.max_id) params.push('max_id='+options.max_id)
if(options.since_id) params.push('since_id='+options.since_id)
if(options.limit) params.push('limit='+options.limit)
if(options.only_media) params.push('only_media=1')
if(options.local) params.push('local=1')
if(params.length) return '?'+params.join('&')
}
return ''
}
function get_request(endpoint){
if(connections.length == 0
|| typeof active_connection=='undefined'
|| typeof connections[active_connection]=='undefined'){
return Promise.reject('not connected')
}
return connections[active_connection].then(conn=>{
if(conn.error) return Promise.reject('not connected')
const server = conn.server;
const token = conn.token.access_token;
const fetchHeaders = new Headers();
fetchHeaders.set('Authorization','Bearer '+token);
const fetchInit = {
method:'GET',
mode:'cors',
headers: fetchHeaders
}
return fetch(server+endpoint, fetchInit).then(res=>res.json());
})
}
function post_request(endpoint,data){
if(connections.length == 0
|| typeof active_connection=='undefined'
|| typeof connections[active_connection]=='undefined'){
return Promise.reject('not connected')
}
return connections[active_connection].then(conn=>{
if(conn.error) return Promise.reject('not connected')
const server = conn.server;
const token = conn.token.access_token;
const fetchHeaders = new Headers();
fetchHeaders.set('Authorization','Bearer '+token);
const body = new URLSearchParams()
for(var key in data) body.set(key,data[key])
const fetchInit = {
method:'POST',
mode:'cors',
headers: fetchHeaders,
body: body
}
return fetch(server+endpoint, fetchInit).then(res=>res.json());
})
}
function get_token(server, registration){
const token = localStorage.getItem(prefix+'_token_'+server)
if(typeof token != 'string'){
const re_match = /[?&]code=([^&]+)/.exec(window.location.search)
if(!re_match){
if(log_errors) console.error("Failed to find token in storage & no code found in URL parameters.")
throw('no_token_or_code')
}
if(log_actions) console.log('fetching new token')
const code = re_match[1]
const endpoint = server+'/oauth/token'
const data = new URLSearchParams()
data.set('grant_type','authorization_code')
data.set('client_id',registration.client_id)
data.set('client_secret',registration.client_secret)
data.set('redirect_uri',registration.redirect_uri)
data.set('code',code)
const fetchInit = {
method:'POST',
mode:'cors',
body: data
}
return fetch(endpoint,fetchInit).then(res=>res.json()).then(obj=>{
if(obj.error=='invalid_grant'){
if(log_errors) console.error(obj.error_description)
throw obj.error
}
localStorage.setItem(prefix+'_token_'+server,JSON.stringify(obj))
return obj
})
} else {
if(log_actions) console.log('reading token from storage')
return new Promise(resolve=>resolve(JSON.parse(token)))
}
}
function get_authorization_url(server, registration, libodon){
let endpoint = server+'/oauth/authorize?response_type=code'
endpoint += '&client_id='+registration.client_id
endpoint += '&redirect_uri='+registration.redirect_uri
if(libodon.scope) endpoint += '&scope='+encodeURI(libodon.scope)
return endpoint
}
function get_registration(server, libodon){
const reg = localStorage.getItem(prefix+'_registration_'+server)
if(typeof reg != 'string'){
if(log_actions) console.log('registering new app')
const promise = register_application(server, libodon)
return promise.then(reg=>{
localStorage.setItem(prefix+'_registration_'+server,JSON.stringify(reg))
return reg
})
} else {
if(log_actions) console.log('reading registration from storage')
return new Promise(resolve=>resolve(JSON.parse(reg)))
}
}
function register_application(server, libodon){
const endpoint = server+'/api/v1/apps'
const data = new URLSearchParams()
data.set('response_type','code')
data.set('client_name',libodon.appname)
data.set('redirect_uris',libodon.redirect_url)
data.set('scopes',libodon.scope)
const fetchInit = {
method:'POST',
mode:'cors',
body: data
}
return fetch(endpoint,fetchInit).then(res=>res.json())
}
})()