forked from jkjoy/FediverseSyncForTypecho
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAction.php
More file actions
268 lines (229 loc) · 11 KB
/
Copy pathAction.php
File metadata and controls
268 lines (229 loc) · 11 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
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
<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
class FediverseSync_Action extends Typecho_Widget implements Widget_Interface_Do
{
/**
* @var Widget_Security
*/
private $security;
/**
* @var Typecho_Db
*/
private $db;
public function __construct($request, $response, $params = NULL)
{
parent::__construct($request, $response, $params);
$this->db = Typecho_Db::get();
}
protected function init()
{
parent::init();
$this->security = Typecho_Widget::widget('Widget_Security');
}
public function action()
{
$user = Typecho_Widget::widget('Widget_User');
if (!$user->hasLogin()) {
throw new Typecho_Widget_Exception(_t('未登录'));
}
if (!$user->pass('administrator', true)) {
throw new Typecho_Widget_Exception(_t('权限不足'));
}
if ($this->request->is('do=sync')) {
$this->security->protect();
$this->sync();
}
}
public function sync()
{
$cids = $this->request->getArray('cid');
if (empty($cids)) {
$this->widget('Widget_Notice')->set(_t('请选择要同步的文章'), 'error');
$this->response->goBack();
return;
}
$options = Helper::options();
$pluginOptions = $options->plugin('FediverseSync');
if (empty($pluginOptions->instance_url) || empty($pluginOptions->access_token)) {
$this->widget('Widget_Notice')->set(_t('请先配置 Fediverse 实例地址和访问令牌'), 'error');
$this->response->goBack();
return;
}
$successes = $failures = 0;
foreach ($cids as $cid) {
try {
// 获取文章信息
$post = $this->db->fetchRow($this->db->select()
->from('table.contents')
->where('cid = ?', $cid)
->where('type = ?', 'post')
->where('status = ?', 'publish')
->limit(1));
if ($post) {
// 用 Widget_Archive 获取 permalink
$archive = Typecho_Widget::widget('Widget_Archive@sync_' . $cid, 'pageSize=1&type=post', 'cid=' . $cid);
if ($archive->have()) {
$archive->next();
// 获取站点名称
$siteName = FediverseSync_Utils_Template::decodeHtmlEntities($options->title);
// 使用模板工具类处理内容(是否包含原文由模板是否包含 {content} 决定)
$template = $pluginOptions->content_template ?? FediverseSync_Utils_Template::getDefaultTemplate();
if (empty($template)) {
$template = FediverseSync_Utils_Template::getDefaultTemplate();
}
// 获取文章内容
$postContent = '';
if (strpos($template, '{content}') !== false) {
$contentLength = intval($pluginOptions->content_length ?? 500);
$rawContent = $archive->text ?? ($archive->content ?? ($post['text'] ?? ''));
$postContent = FediverseSync_Utils_Template::processMarkdownContent($rawContent, $contentLength);
}
// 获取作者信息
$author = $archive->author->screenName ?? '';
if ($author === '') {
$authorId = $post['authorId'] ?? null;
if (!empty($authorId)) {
$authorRow = $this->db->fetchRow($this->db->select('screenName')
->from('table.users')
->where('uid = ?', $authorId)
->limit(1));
$author = $authorRow['screenName'] ?? '';
}
}
$author = FediverseSync_Utils_Template::decodeHtmlEntities($author);
$templateData = [
'title' => FediverseSync_Utils_Template::decodeHtmlEntities($archive->title),
'permalink' => $archive->permalink,
'content' => $postContent,
'author' => $author,
'created' => date('Y-m-d H:i', $archive->created),
'site_name' => $siteName
];
$content = FediverseSync_Utils_Template::parse($template, $templateData);
// Mastodon/GoToSocial:避免超长导致同步失败,优先缩短 {content}
if ($pluginOptions->instance_type !== 'misskey') {
$maxCharacters = 500;
if (mb_strlen($content) > $maxCharacters) {
if (strpos($template, '{content}') !== false) {
$baseMessage = FediverseSync_Utils_Template::parse($template, array_merge($templateData, ['content' => '']));
$available = $maxCharacters - mb_strlen($baseMessage);
if ($available > 0) {
$templateData['content'] = FediverseSync_Utils_Template::processMarkdownContent($rawContent ?? '', $available);
$content = FediverseSync_Utils_Template::parse($template, $templateData);
}
}
if (mb_strlen($content) > $maxCharacters) {
$content = FediverseSync_Utils_Template::truncate($content, $maxCharacters, '...');
}
}
}
// 发送到 Fediverse
$response = $this->postToFediverse($pluginOptions->instance_url, $pluginOptions->access_token, $content);
$tootData = json_decode($response, true);
if ($pluginOptions->instance_type === 'misskey') {
if (isset($tootData['createdNote']['id'])) {
$tootData = [
'id' => $tootData['createdNote']['id'],
'url' => $pluginOptions->instance_url . '/notes/' . $tootData['createdNote']['id']
];
}
}
if (!isset($tootData['id']) || !isset($tootData['url'])) {
throw new Exception(_t('发送到 Fediverse 失败:无效的响应'));
}
// 更新或插入绑定关系
$binding = $this->db->fetchRow($this->db->select()
->from('table.fediverse_bindings')
->where('post_id = ?', $cid)
->limit(1));
$data = [
'post_id' => $cid,
'toot_id' => $tootData['id'],
'toot_url' => $tootData['url'],
'instance_url' => rtrim($pluginOptions->instance_url, '/')
];
if ($binding) {
$this->db->query($this->db->update('table.fediverse_bindings')
->rows($data)
->where('post_id = ?', $cid));
} else {
$this->db->query($this->db->insert('table.fediverse_bindings')
->rows($data));
}
$successes++;
}
}
} catch (Exception $e) {
FediverseSync_Plugin::log($cid, 'sync', 'error', '手动同步失败:' . $e->getMessage());
$failures++;
}
}
// 设置提示消息
$msg = '';
if ($successes > 0) {
$msg .= _t('成功同步 %d 篇文章。', $successes);
}
if ($failures > 0) {
$msg .= _t('同步失败 %d 篇文章。', $failures);
}
// 返回面板页面
$this->widget('Widget_Notice')->set($msg, $failures > 0 ? 'error' : 'success');
$this->response->goBack();
}
private function postToFediverse($instance, $token, $content)
{
$options = Helper::options();
$pluginOptions = $options->plugin('FediverseSync');
$instance_type = $pluginOptions->instance_type;
$instance = rtrim($instance, '/');
// 根据实例类型选择不同的API端点和参数
if ($instance_type === 'misskey') {
$url = $instance . '/api/notes/create';
// Misskey的可见性设置与Mastodon不同
$visibility = 'public';
switch ($pluginOptions->visibility) {
case 'private':
$visibility = 'followers';
break;
case 'unlisted':
$visibility = 'home';
break;
default:
$visibility = 'public';
}
$data = array(
'i' => $token, // Misskey使用i参数传递访问令牌
'text' => $content,
'visibility' => $visibility
);
$headers = array(
'Content-Type: application/json'
);
} else {
// Mastodon/GoToSocial API
$url = $instance . '/api/v1/statuses';
$data = array(
'status' => $content,
'visibility' => $pluginOptions->visibility ?? 'public'
);
$headers = array(
'Authorization: Bearer ' . $token,
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
'Accept: application/json',
'User-Agent: FediverseSync/1.6.4'
);
}
$http = new FediverseSync_Utils_Http();
if ($instance_type === 'misskey') {
$result = $http->post($url, $data, $headers);
} else {
$result = $http->postForm($url, $data, $headers);
}
$httpCode = FediverseSync_Utils_Http::getLastHttpCode();
$response = FediverseSync_Utils_Http::getRawResponse();
if ($result === null) {
throw new Exception('HTTP Error: ' . $httpCode . ' Response: ' . $response);
}
return $response;
}
}