all repos — underbbs @ 7a2eb99eb6d60d23c034f6255d5b52aea08e24d5

decentralized social media client

adapter/misskey.go (raw)

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
package adapter

import (
	"fmt"
	. "forge.lightcrystal.systems/lightcrystal/underbbs/models"
	"github.com/yitsushi/go-misskey"
	mkcore "github.com/yitsushi/go-misskey/core"
	mkm "github.com/yitsushi/go-misskey/models"
	n "github.com/yitsushi/go-misskey/services/notes"
	tl "github.com/yitsushi/go-misskey/services/notes/timeline"
	users "github.com/yitsushi/go-misskey/services/users"
	"strings"
	"sync"
	"time"
)

type MisskeyAdapter struct {
	data     chan SocketData
	nickname string
	server   string
	apiKey   string

	mk *misskey.Client

	// unlike the mastodon client, we have to manage combining resources
	// from different API calls instead of streaming them in a single channel

	cache map[string]time.Time
	mtx   sync.RWMutex

	stop chan bool
}

func (self *MisskeyAdapter) Name() string {
	return self.nickname
}

func (self *MisskeyAdapter) Init(settings Settings, data chan SocketData) error {
	fmt.Println("initializing misskey adapter")

	self.nickname = settings.Nickname
	self.server = *settings.Server
	self.apiKey = *settings.ApiKey
	self.data = data

	fmt.Println("getting ready to initialize internal client")

	client, err := misskey.NewClientWithOptions(
		misskey.WithAPIToken(self.apiKey),
		misskey.WithBaseURL("https", self.server, ""),
	)

	if err != nil {
		fmt.Println(err.Error())
		return err
	}
	fmt.Println("misskey client initialized")
	self.mk = client

	self.cache = make(map[string]time.Time)

	return nil
}

func (self *MisskeyAdapter) Subscribe(filter string) []error {
	// misskey streaming API is undocumented....
	// we could try to reverse engineer it by directly connecting to the websocket???
	// alternatively, we can poll timelines, mentions, etc with a cancellation channel,
	// keep a cache of IDs in memory, and send new objects on the data channel

	// TODO: decode the filter so we can send data to the mk services

	// same as in masto, we will want to close and reopen the stop channel
	if self.stop != nil {
		close(self.stop)
	}
	self.stop = make(chan bool)

	// in the background, continuously read data from these API endpoints
	// if they are newer than the cache, convert them to UnderBBS objects
	// and send them on the data channel

	go self.poll()

	return nil
}

func (self *MisskeyAdapter) poll() {

	var latest *time.Time

	var notesService *n.Service
	var timelineService *tl.Service

	for {
		select {
		case _, ok := <-self.stop:
			if !ok {
				return
			}
		default:
			notesService = self.mk.Notes()
			timelineService = notesService.Timeline()
			// TODO: we have to actually decode and pass our filter criteria

			// probe for new notes
			probenote, err := timelineService.Get(tl.GetRequest{
				Limit: 1,
			})
			if err == nil && len(probenote) > 0 && self.isNew(probenote[0]) {
				if latest == nil {
					latest = &probenote[0].CreatedAt
					// this is the first fetch of notes, we can just grab them
					notes, err := timelineService.Get(tl.GetRequest{
						Limit: 100,
					})
					// if latest is nil also get mentions history
					mentions, merr := notesService.Mentions(n.MentionsRequest{
						Limit: 100,
					})
					if err != nil {
						fmt.Println(err.Error())
					}
					if merr != nil {
						fmt.Println(merr.Error())
					}

					// check the cache for everything we just collected
					// if anything is newer or as of yet not in the cache, add it
					// and convert it to a SocketData implementation before sending on data channel
					for _, n := range notes {
						msg := self.toMessageIfNew(n)
						if msg != nil {
							self.data <- msg
						}
					}
					for _, n := range mentions {
						msg := self.toMessageIfNew(n)
						if msg != nil {
							self.data <- msg
						}
					}

				} else {
					for {
						// get notes since latest, until the probe
						notes, err := timelineService.Get(tl.GetRequest{
							SinceDate: uint64(latest.Unix()),
							UntilDate: uint64(probenote[0].CreatedAt.Unix()),
							Limit:     100,
						})
						if err != nil {
							fmt.Println(err.Error())
						}
						for _, n := range notes {
							msg := self.toMessageIfNew(n)
							if msg == nil {
								latest = &probenote[0].CreatedAt
								break
							}
							self.data <- msg
						}
						if *latest == probenote[0].CreatedAt {
							break
						}
					}
				}
			}

			time.Sleep(5 * time.Second)
		}
	}
}

func (self *MisskeyAdapter) isNew(n mkm.Note) bool {
	self.mtx.RLock()
	timestamp, exists := self.cache[n.ID]
	self.mtx.RUnlock()
	return !exists || timestamp.Before(n.CreatedAt)
}

func (self *MisskeyAdapter) toMessageIfNew(n mkm.Note) *Message {
	return self.toMessage(n, false)
}

func (self *MisskeyAdapter) toMessage(n mkm.Note, bustCache bool) *Message {
	self.mtx.RLock()
	timestamp, exists := self.cache[n.ID]
	self.mtx.RUnlock()
	if bustCache || !exists || timestamp.Before(n.CreatedAt) {
		host := mkcore.StringValue(n.User.Host)
		authorId := ""
		if host != "" {
			authorId = fmt.Sprintf("@%s@%s", n.User.Username, host)
		} else {
			authorId = fmt.Sprintf("@%s", n.User.Username)
		}

		self.mtx.Lock()
		self.cache[n.ID] = n.CreatedAt
		self.mtx.Unlock()
		msg := Message{
			Datagram: Datagram{
				Id:       n.ID,
				Uri:      n.URI,
				Protocol: "misskey",
				Adapter:  self.nickname,
				Type:     "message",
				Created:  n.CreatedAt.UnixMilli(),
			},

			Author:      authorId,
			Content:     n.Text,
			Attachments: []Attachment{},
			Visibility:  n.Visibility,
			ReplyTo:     n.ReplyID,
			ReplyCount:  int(n.RepliesCount),
			Replies:     []string{},
		}

		for _, f := range n.Files {
			msg.Attachments = append(msg.Attachments, Attachment{
				Src:      f.URL,
				ThumbSrc: f.ThumbnailURL,
				Size:     f.Size,
				Desc:     f.Comment,
				Created:  f.CreatedAt.UnixMilli(),
			})
		}
		return &msg
	}
	return nil
}

func (self *MisskeyAdapter) toAuthor(usr mkm.User, bustCache bool) *Author {

	host := mkcore.StringValue(usr.Host)
	authorId := ""
	if host != "" {
		authorId = fmt.Sprintf("@%s@%s", usr.Username, host)
	} else {
		authorId = fmt.Sprintf("@%s", usr.Username)
	}

	self.mtx.RLock()
	timestamp, exists := self.cache[authorId]
	self.mtx.RUnlock()

	var updated *int64 = nil
	if usr.UpdatedAt != nil {
		updatedTmp := usr.UpdatedAt.UnixMilli()
		updated = &updatedTmp
	}

	if bustCache || !exists || (updated != nil && timestamp.Before(time.UnixMilli(*updated))) || timestamp.Before(*usr.CreatedAt) {
		fmt.Println("converting author: " + usr.ID)
		if usr.UpdatedAt != nil {
			self.cache[authorId] = *usr.UpdatedAt
		} else {
			self.cache[authorId] = *usr.CreatedAt
		}

		author := Author{
			Datagram: Datagram{
				Id:       authorId,
				Uri:      mkcore.StringValue(usr.URL),
				Protocol: "misskey",
				Adapter:  self.nickname,
				Type:     "author",
				Created:  usr.CreatedAt.UnixMilli(),
				Updated:  updated,
			},
			Name:        usr.Name,
			ProfilePic:  usr.AvatarURL,
			ProfileData: usr.Description,
		}

		return &author
	}
	return nil
}

func (self *MisskeyAdapter) Fetch(etype string, ids []string) error {
	for _, id := range ids {
		switch etype {
		case "message":
			data, err := self.mk.Notes().Show(id)
			if err != nil {
				return err
			} else {
				msg := self.toMessage(data, true)
				if msg != nil {
					self.data <- msg
				}
			}
		case "children":
			data, err := self.mk.Notes().Children(n.ChildrenRequest{
				NoteID: id,
				Limit:  100,
			})
			if err != nil {
				return err
			} else {
				for _, n := range data {
					msg := self.toMessage(n, true)
					if msg != nil {
						self.data <- msg
					}
				}
			}
		case "convoy":
			data, err := self.mk.Notes().Conversation(n.ConversationRequest{
				NoteID: id,
				Limit:  100,
			})
			if err != nil {
				return err
			} else {
				for _, n := range data {
					msg := self.toMessage(n, true)
					if msg != nil {
						self.data <- msg
					}
				}
			}
		case "author":
			user := ""
			host := ""
			idParts := strings.Split(id, "@")
			user = idParts[1]
			if len(idParts) == 3 {
				host = idParts[2]
			}

			var hostPtr *string = nil
			if len(host) > 0 {
				hostPtr = &host
			}

			// fmt.Printf("attempting user resolution: @%s@%s\n", user, host)
			data, err := self.mk.Users().Show(users.ShowRequest{
				Username: &user,
				Host:     hostPtr,
			})
			if err != nil {
				return err
			} else {
				a := self.toAuthor(data, false)
				if a != nil {
					self.data <- a
				}
			}

		}
	}
	return nil
}

func (self *MisskeyAdapter) Do(action string) error {
	return nil
}

func (self *MisskeyAdapter) DefaultSubscriptionFilter() string {
	return ""
}