-
Notifications
You must be signed in to change notification settings - Fork 2
/
TwitterApi.kt
308 lines (265 loc) · 12.7 KB
/
TwitterApi.kt
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
package shibafu.yukari.twitter
import android.os.Handler
import android.os.Looper
import android.preference.PreferenceManager
import android.support.v4.util.LongSparseArray
import android.widget.Toast
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import shibafu.yukari.database.Provider
import shibafu.yukari.entity.ShadowUser
import shibafu.yukari.entity.Status
import shibafu.yukari.entity.StatusDraft
import shibafu.yukari.linkage.PostValidator
import shibafu.yukari.linkage.ProviderApi
import shibafu.yukari.linkage.ProviderApiException
import shibafu.yukari.service.TwitterService
import shibafu.yukari.twitter.entity.TwitterMessage
import shibafu.yukari.twitter.entity.TwitterStatus
import twitter4j.CursorSupport
import twitter4j.StatusUpdate
import twitter4j.Twitter
import twitter4j.TwitterAPIConfiguration
import twitter4j.TwitterException
import twitter4j.TwitterFactory
import twitter4j.UploadedMedia
import java.io.File
import java.util.regex.Pattern
class TwitterApi : ProviderApi {
var apiConfiguration: TwitterAPIConfiguration? = null
private set
private lateinit var service: TwitterService
private lateinit var twitterFactory: TwitterFactory
private val twitterInstances = LongSparseArray<Twitter>()
override fun onCreate(service: TwitterService) {
this.service = service
this.twitterFactory = TwitterUtil.getTwitterFactory(service)
GlobalScope.launch {
// API Configurationの取得
val primaryAccount = service.users.firstOrNull { it.isPrimary && it.Provider.apiType == Provider.API_TWITTER }
?: service.users.firstOrNull { it.Provider.apiType == Provider.API_TWITTER }
if (primaryAccount != null) {
try {
apiConfiguration = (getApiClient(primaryAccount) as Twitter).apiConfiguration
} catch (e: TwitterException) {
e.printStackTrace()
}
}
// Blocks, Mutes, No-Retweetsの取得
val twitterAccounts = service.users.filter { it.Provider.apiType == Provider.API_TWITTER }
val suppressor = service.suppressor
val sp = PreferenceManager.getDefaultSharedPreferences(service)
if (sp.getBoolean("pref_filter_official", true) && suppressor != null) {
twitterAccounts.forEach { userRecord ->
val twitter = getApiClient(userRecord) as? Twitter ?: return@forEach
try {
forEachCursor(twitter::getBlocksIDs) {
suppressor.addBlockedIDs(it.iDs)
}
} catch (ignored: TwitterException) {}
try {
forEachCursor(twitter::getMutesIDs) {
suppressor.addMutedIDs(it.iDs)
}
} catch (ignored: TwitterException) {}
try {
suppressor.addNoRetweetIDs(twitter.noRetweetsFriendships.iDs)
} catch (ignored: TwitterException) {}
}
}
}
}
override fun onDestroy() {
twitterInstances.clear()
}
override fun getApiClient(userRecord: AuthUserRecord?): Any? {
if (userRecord == null) {
return twitterFactory.instance
}
if (userRecord.Provider.apiType != Provider.API_TWITTER) {
return null
}
if (twitterInstances.indexOfKey(userRecord.NumericId) < 0) {
twitterInstances.put(userRecord.NumericId, twitterFactory.getInstance(userRecord.twitterAccessToken))
}
return twitterInstances.get(userRecord.NumericId)
}
override fun getPostValidator(userRecord: AuthUserRecord): PostValidator {
return TweetValidator()
}
override fun getAccountUrl(userRecord: AuthUserRecord): String {
return TwitterUtil.getProfileUrl(userRecord.ScreenName)
}
// 互換用
fun createFavorite(userRecord: AuthUserRecord, id: Long): Boolean {
val twitter = service.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
val status = twitter.createFavorite(id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "ふぁぼりました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
service.timelineHub?.onFavorite(ShadowUser(userRecord), TwitterStatus(status, userRecord))
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "ふぁぼれませんでした (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun createFavorite(userRecord: AuthUserRecord, status: Status): Boolean {
val twitter = service.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
twitter.createFavorite(status.id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "ふぁぼりました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
service.timelineHub?.onFavorite(ShadowUser(userRecord), status)
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "ふぁぼれませんでした (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun destroyFavorite(userRecord: AuthUserRecord, status: Status): Boolean {
val twitter = service.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
twitter.destroyFavorite(status.id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "あんふぁぼしました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
service.timelineHub?.onUnfavorite(ShadowUser(userRecord), status)
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "あんふぁぼに失敗しました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun postStatus(userRecord: AuthUserRecord, draft: StatusDraft, mediaList: List<File>): Status {
val twitter = service.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
if (draft.isDirectMessage) {
val inReplyTo = draft.inReplyTo?.url?.let { TwitterUtil.getUserIdFromUrl(it) } ?: -1
if (inReplyTo == -1L) {
throw ProviderApiException("返信先に不正な値が指定されました。")
}
val users = twitter.lookupUsers(inReplyTo, userRecord.NumericId)
val result = twitter.sendDirectMessage(inReplyTo, draft.text)
return TwitterMessage(result,
users.first { it.id == userRecord.NumericId },
users.first { it.id == inReplyTo },
userRecord)
} else {
var text = draft.text
var attachmentUrl = ""
// 画像添付なしで、ツイートを引用している場合は1つだけattachmentUrlに移動させる
if (mediaList.isEmpty()) {
val matcher = PATTERN_TWITTER.matcher(text)
if (matcher.find()) {
attachmentUrl = matcher.group().trim()
text = matcher.replaceAll(text)
}
}
val update = StatusUpdate(text)
if (attachmentUrl.isNotEmpty()) {
update.attachmentUrl = attachmentUrl
}
// 返信先URLが設定されている場合はin-reply-toに設定する
val inReplyTo = draft.inReplyTo
if (inReplyTo != null) {
val inReplyToId = TwitterUtil.getStatusIdFromUrl(inReplyTo.url)
if (inReplyToId > -1) {
update.inReplyToStatusId = inReplyToId
}
}
// 添付メディアのアップロード
val mediaIds = mediaList.map { file ->
uploadMedia(userRecord, file).mediaId
}
update.setMediaIds(*mediaIds.toLongArray())
// フラグ付きメディアの設定
update.isPossiblySensitive = draft.isPossiblySensitive
val result = twitter.updateStatus(update)
val status = TwitterStatus(result, userRecord)
service.timelineHub?.onStatus("Twitter.PostStatus", status, true)
return status
}
} catch (e: TwitterException) {
throw ProviderApiException("${e.errorCode} ${e.errorMessage}", e)
}
}
override fun repostStatus(userRecord: AuthUserRecord, status: Status): Boolean {
val twitter = service.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
twitter.retweetStatus(status.id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "RTしました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "RTに失敗しました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun destroyStatus(userRecord: AuthUserRecord, status: Status): Boolean {
val twitter = service.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
twitter.destroyStatus(status.id)
service.timelineHub?.onDelete(Provider.TWITTER.host, status.id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "ツイートを削除しました", Toast.LENGTH_SHORT).show()
}
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(service.applicationContext, "ツイート削除に失敗しました", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun showStatus(userRecord: AuthUserRecord, url: String): Status {
val twitter = service.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
val id = url.toLongOrNull()
if (id != null) {
return TwitterStatus(twitter.showStatus(id), userRecord)
}
val matcher = PATTERN_TWITTER.matcher(url)
if (matcher.find()) {
val extractId = matcher.group(1).toLongOrNull()
if (extractId != null) {
return TwitterStatus(twitter.showStatus(extractId), userRecord)
}
}
throw IllegalArgumentException("非対応URLです : $url")
} catch (e: TwitterException) {
throw ProviderApiException(cause = e)
}
}
private fun uploadMedia(userRecord: AuthUserRecord, file: File): UploadedMedia {
val twitter = service.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
return twitter.uploadMedia(file)
}
private inline fun <T : CursorSupport> forEachCursor(cursorSupport: (Long) -> T, action: (T) -> Unit) {
var cursor = -1L
do {
val cs = cursorSupport(cursor)
action(cs)
cursor = cs.nextCursor
} while (cs.hasNext())
}
companion object {
private val PATTERN_TWITTER = Pattern.compile("^https?://(?:www\\.)?(?:mobile\\.)?twitter\\.com/(?:#!/)?[0-9a-zA-Z_]{1,15}/status(?:es)?/([0-9]+)/?(?:\\?.+)?\$")
}
}