ApiV1Controller.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Support\Str;
  6. use App\Util\ActivityPub\Helpers;
  7. use App\Util\Media\Filter;
  8. use Laravel\Passport\Passport;
  9. use Auth, Cache, DB, URL;
  10. use App\{
  11. Avatar,
  12. Bookmark,
  13. DirectMessage,
  14. Follower,
  15. FollowRequest,
  16. Hashtag,
  17. Instance,
  18. Like,
  19. Media,
  20. Notification,
  21. Profile,
  22. Status,
  23. StatusHashtag,
  24. User,
  25. UserSetting,
  26. UserFilter,
  27. };
  28. use League\Fractal;
  29. use App\Transformer\Api\Mastodon\v1\{
  30. AccountTransformer,
  31. MediaTransformer,
  32. NotificationTransformer,
  33. StatusTransformer,
  34. };
  35. use App\Transformer\Api\{
  36. RelationshipTransformer,
  37. };
  38. use App\Http\Controllers\FollowerController;
  39. use League\Fractal\Serializer\ArraySerializer;
  40. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  41. use App\Http\Controllers\StatusController;
  42. use App\Jobs\AvatarPipeline\AvatarOptimize;
  43. use App\Jobs\CommentPipeline\CommentPipeline;
  44. use App\Jobs\LikePipeline\LikePipeline;
  45. use App\Jobs\SharePipeline\SharePipeline;
  46. use App\Jobs\SharePipeline\UndoSharePipeline;
  47. use App\Jobs\StatusPipeline\NewStatusPipeline;
  48. use App\Jobs\StatusPipeline\StatusDelete;
  49. use App\Jobs\FollowPipeline\FollowPipeline;
  50. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  51. use App\Jobs\VideoPipeline\{
  52. VideoOptimize,
  53. VideoPostProcess,
  54. VideoThumbnail
  55. };
  56. use App\Services\{
  57. AccountService,
  58. FollowerService,
  59. InstanceService,
  60. LikeService,
  61. NotificationService,
  62. MediaPathService,
  63. PublicTimelineService,
  64. ReblogService,
  65. RelationshipService,
  66. SearchApiV2Service,
  67. StatusService,
  68. MediaBlocklistService,
  69. SnowflakeService,
  70. UserFilterService
  71. };
  72. use App\Util\Lexer\Autolink;
  73. use App\Util\Lexer\PrettyNumber;
  74. use App\Util\Localization\Localization;
  75. use App\Util\Media\License;
  76. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  77. use App\Services\DiscoverService;
  78. use App\Services\CustomEmojiService;
  79. class ApiV1Controller extends Controller
  80. {
  81. protected $fractal;
  82. public function __construct()
  83. {
  84. $this->fractal = new Fractal\Manager();
  85. $this->fractal->setSerializer(new ArraySerializer());
  86. }
  87. public function apps(Request $request)
  88. {
  89. abort_if(!config_cache('pixelfed.oauth_enabled'), 404);
  90. $this->validate($request, [
  91. 'client_name' => 'required',
  92. 'redirect_uris' => 'required',
  93. 'scopes' => 'nullable',
  94. 'website' => 'nullable'
  95. ]);
  96. $uris = implode(',', explode('\n', $request->redirect_uris));
  97. $client = Passport::client()->forceFill([
  98. 'user_id' => null,
  99. 'name' => e($request->client_name),
  100. 'secret' => Str::random(40),
  101. 'redirect' => $uris,
  102. 'personal_access_client' => false,
  103. 'password_client' => false,
  104. 'revoked' => false,
  105. ]);
  106. $client->save();
  107. $res = [
  108. 'id' => $client->id,
  109. 'name' => $client->name,
  110. 'website' => null,
  111. 'redirect_uri' => $client->redirect,
  112. 'client_id' => $client->id,
  113. 'client_secret' => $client->secret,
  114. 'vapid_key' => null
  115. ];
  116. return response()->json($res, 200, [
  117. 'Access-Control-Allow-Origin' => '*'
  118. ]);
  119. }
  120. /**
  121. * GET /api/v1/accounts/verify_credentials
  122. *
  123. *
  124. * @return \App\Transformer\Api\AccountTransformer
  125. */
  126. public function verifyCredentials(Request $request)
  127. {
  128. $user = $request->user();
  129. abort_if(!$user, 403);
  130. abort_if($user->status != null, 403);
  131. $res = AccountService::getMastodon($user->profile_id);
  132. $res['source'] = [
  133. 'privacy' => $res['locked'] ? 'private' : 'public',
  134. 'sensitive' => false,
  135. 'language' => $user->language ?? 'en',
  136. 'note' => '',
  137. 'fields' => []
  138. ];
  139. return response()->json($res);
  140. }
  141. /**
  142. * GET /api/v1/accounts/{id}
  143. *
  144. * @param integer $id
  145. *
  146. * @return \App\Transformer\Api\AccountTransformer
  147. */
  148. public function accountById(Request $request, $id)
  149. {
  150. $res = AccountService::getMastodon($id, true);
  151. if(!$res) {
  152. return response()->json(['error' => 'Record not found'], 404);
  153. }
  154. return response()->json($res);
  155. }
  156. /**
  157. * PATCH /api/v1/accounts/update_credentials
  158. *
  159. * @return \App\Transformer\Api\AccountTransformer
  160. */
  161. public function accountUpdateCredentials(Request $request)
  162. {
  163. abort_if(!$request->user(), 403);
  164. $this->validate($request, [
  165. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png|min:10|max:' . config('pixelfed.max_avatar_size'),
  166. 'display_name' => 'nullable|string',
  167. 'note' => 'nullable|string',
  168. 'locked' => 'nullable',
  169. 'website' => 'nullable',
  170. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  171. // 'source.sensitive' => 'nullable|boolean'
  172. ], [
  173. 'required' => 'The :attribute field is required.',
  174. 'avatar.mimetypes' => 'The file must be in jpeg or png format',
  175. 'avatar.max' => 'The :attribute exceeds the file size limit of ' . PrettyNumber::size(config('pixelfed.max_avatar_size'), true, false),
  176. ]);
  177. $user = $request->user();
  178. $profile = $user->profile;
  179. $settings = $user->settings;
  180. $changes = false;
  181. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  182. $syncLicenses = false;
  183. $licenseChanged = false;
  184. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  185. if($request->has('avatar')) {
  186. $av = Avatar::whereProfileId($profile->id)->first();
  187. if($av) {
  188. $currentAvatar = storage_path('app/'.$av->media_path);
  189. $file = $request->file('avatar');
  190. $path = "public/avatars/{$profile->id}";
  191. $name = strtolower(str_random(6)). '.' . $file->guessExtension();
  192. $request->file('avatar')->storeAs($path, $name);
  193. $av->media_path = "{$path}/{$name}";
  194. $av->save();
  195. Cache::forget("avatar:{$profile->id}");
  196. Cache::forget('user:account:id:'.$user->id);
  197. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  198. }
  199. $changes = true;
  200. }
  201. if($request->has('source[language]')) {
  202. $lang = $request->input('source[language]');
  203. if(in_array($lang, Localization::languages())) {
  204. $user->language = $lang;
  205. $changes = true;
  206. $other['language'] = $lang;
  207. }
  208. }
  209. if($request->has('website')) {
  210. $website = $request->input('website');
  211. if($website != $profile->website) {
  212. if($website) {
  213. if(!strpos($website, '.')) {
  214. $website = null;
  215. }
  216. if($website && !strpos($website, '://')) {
  217. $website = 'https://' . $website;
  218. }
  219. $host = parse_url($website, PHP_URL_HOST);
  220. $bannedInstances = InstanceService::getBannedDomains();
  221. if(in_array($host, $bannedInstances)) {
  222. $website = null;
  223. }
  224. }
  225. $profile->website = $website ? $website : null;
  226. $changes = true;
  227. }
  228. }
  229. if($request->has('display_name')) {
  230. $displayName = $request->input('display_name');
  231. if($displayName !== $user->name) {
  232. $user->name = $displayName;
  233. $profile->name = $displayName;
  234. $changes = true;
  235. }
  236. }
  237. if($request->has('note')) {
  238. $note = $request->input('note');
  239. if($note !== strip_tags($profile->bio)) {
  240. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  241. $changes = true;
  242. }
  243. }
  244. if($request->has('locked')) {
  245. $locked = $request->input('locked') == 'true';
  246. if($profile->is_private != $locked) {
  247. $profile->is_private = $locked;
  248. $changes = true;
  249. }
  250. }
  251. if($request->has('reduce_motion')) {
  252. $reduced = $request->input('reduce_motion');
  253. if($settings->reduce_motion != $reduced) {
  254. $settings->reduce_motion = $reduced;
  255. $changes = true;
  256. }
  257. }
  258. if($request->has('high_contrast_mode')) {
  259. $contrast = $request->input('high_contrast_mode');
  260. if($settings->high_contrast_mode != $contrast) {
  261. $settings->high_contrast_mode = $contrast;
  262. $changes = true;
  263. }
  264. }
  265. if($request->has('video_autoplay')) {
  266. $autoplay = $request->input('video_autoplay');
  267. if($settings->video_autoplay != $autoplay) {
  268. $settings->video_autoplay = $autoplay;
  269. $changes = true;
  270. }
  271. }
  272. if($request->has('license')) {
  273. $license = $request->input('license');
  274. abort_if(!in_array($license, License::keys()), 422, 'Invalid media license id');
  275. $syncLicenses = $request->input('sync_licenses') == true;
  276. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  277. if($composeSettings['default_license'] != $license) {
  278. $composeSettings['default_license'] = $license;
  279. $licenseChanged = true;
  280. $changes = true;
  281. }
  282. }
  283. if($request->has('media_descriptions')) {
  284. $md = $request->input('media_descriptions') == true;
  285. if($composeSettings['media_descriptions'] != $md) {
  286. $composeSettings['media_descriptions'] = $md;
  287. $changes = true;
  288. }
  289. }
  290. if($request->has('crawlable')) {
  291. $crawlable = $request->input('crawlable');
  292. if($settings->crawlable != $crawlable) {
  293. $settings->crawlable = $crawlable;
  294. $changes = true;
  295. }
  296. }
  297. if($request->has('show_profile_follower_count')) {
  298. $show_profile_follower_count = $request->input('show_profile_follower_count');
  299. if($settings->show_profile_follower_count != $show_profile_follower_count) {
  300. $settings->show_profile_follower_count = $show_profile_follower_count;
  301. $changes = true;
  302. }
  303. }
  304. if($request->has('show_profile_following_count')) {
  305. $show_profile_following_count = $request->input('show_profile_following_count');
  306. if($settings->show_profile_following_count != $show_profile_following_count) {
  307. $settings->show_profile_following_count = $show_profile_following_count;
  308. $changes = true;
  309. }
  310. }
  311. if($request->has('public_dm')) {
  312. $public_dm = $request->input('public_dm');
  313. if($settings->public_dm != $public_dm) {
  314. $settings->public_dm = $public_dm;
  315. $changes = true;
  316. }
  317. }
  318. if($request->has('source[privacy]')) {
  319. $scope = $request->input('source[privacy]');
  320. if(in_array($scope, ['public', 'private', 'unlisted'])) {
  321. if($composeSettings['default_scope'] != $scope) {
  322. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  323. $changes = true;
  324. }
  325. }
  326. }
  327. if($request->has('disable_embeds')) {
  328. $disabledEmbeds = $request->input('disable_embeds');
  329. if($other['disable_embeds'] != $disabledEmbeds) {
  330. $other['disable_embeds'] = $disabledEmbeds;
  331. $changes = true;
  332. }
  333. }
  334. if($changes) {
  335. $settings->other = $other;
  336. $settings->compose_settings = $composeSettings;
  337. $settings->save();
  338. $user->save();
  339. $profile->save();
  340. Cache::forget('profile:settings:' . $profile->id);
  341. Cache::forget('user:account:id:' . $profile->user_id);
  342. Cache::forget('profile:follower_count:' . $profile->id);
  343. Cache::forget('profile:following_count:' . $profile->id);
  344. Cache::forget('profile:embed:' . $profile->id);
  345. Cache::forget('profile:compose:settings:' . $user->id);
  346. Cache::forget('profile:view:'.$user->username);
  347. AccountService::del($user->profile_id);
  348. }
  349. if($syncLicenses && $licenseChanged) {
  350. $key = 'pf:settings:mls_recently:'.$user->id;
  351. $val = Cache::has($key) ? 2 : 1;
  352. Cache::put($key, $val, 86400);
  353. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  354. }
  355. $res = AccountService::getMastodon($user->profile_id);
  356. $res['bio'] = strip_tags($res['note']);
  357. $res = array_merge($res, $other);
  358. return response()->json($res);
  359. }
  360. /**
  361. * GET /api/v1/accounts/{id}/followers
  362. *
  363. * @param integer $id
  364. *
  365. * @return \App\Transformer\Api\AccountTransformer
  366. */
  367. public function accountFollowersById(Request $request, $id)
  368. {
  369. abort_if(!$request->user(), 403);
  370. $account = AccountService::get($id);
  371. abort_if(!$account, 404);
  372. $pid = $request->user()->profile_id;
  373. if($pid != $account['id']) {
  374. if($account['locked']) {
  375. if(FollowerService::follows($pid, $account['id'])) {
  376. return [];
  377. }
  378. }
  379. if(AccountService::hiddenFollowers($id)) {
  380. return [];
  381. }
  382. if($request->has('page') && $request->page >= 5) {
  383. return [];
  384. }
  385. }
  386. $res = DB::table('followers')
  387. ->select('id', 'profile_id', 'following_id')
  388. ->whereFollowingId($account['id'])
  389. ->orderByDesc('id')
  390. ->simplePaginate(10)
  391. ->map(function($follower) {
  392. return AccountService::getMastodon($follower->profile_id);
  393. })
  394. ->filter(function($account) {
  395. return $account && isset($account['id']);
  396. })
  397. ->values()
  398. ->toArray();
  399. return response()->json($res);
  400. }
  401. /**
  402. * GET /api/v1/accounts/{id}/following
  403. *
  404. * @param integer $id
  405. *
  406. * @return \App\Transformer\Api\AccountTransformer
  407. */
  408. public function accountFollowingById(Request $request, $id)
  409. {
  410. abort_if(!$request->user(), 403);
  411. $account = AccountService::get($id);
  412. abort_if(!$account, 404);
  413. $pid = $request->user()->profile_id;
  414. if($pid != $account['id']) {
  415. if($account['locked']) {
  416. if(FollowerService::follows($pid, $account['id'])) {
  417. return [];
  418. }
  419. }
  420. if(AccountService::hiddenFollowing($id)) {
  421. return [];
  422. }
  423. if($request->has('page') && $request->page >= 5) {
  424. return [];
  425. }
  426. }
  427. $res = DB::table('followers')
  428. ->select('id', 'profile_id', 'following_id')
  429. ->whereProfileId($account['id'])
  430. ->orderByDesc('id')
  431. ->simplePaginate(10)
  432. ->map(function($follower) {
  433. return AccountService::get($follower->following_id);
  434. })
  435. ->filter(function($account) {
  436. return $account && isset($account['id']);
  437. })
  438. ->values()
  439. ->toArray();
  440. return response()->json($res);
  441. }
  442. /**
  443. * GET /api/v1/accounts/{id}/statuses
  444. *
  445. * @param integer $id
  446. *
  447. * @return \App\Transformer\Api\StatusTransformer
  448. */
  449. public function accountStatusesById(Request $request, $id)
  450. {
  451. $user = $request->user();
  452. $this->validate($request, [
  453. 'only_media' => 'nullable',
  454. 'media_type' => 'sometimes|string|in:photo,video',
  455. 'pinned' => 'nullable',
  456. 'exclude_replies' => 'nullable',
  457. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  458. 'since_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  459. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  460. 'limit' => 'nullable|integer|min:1|max:80'
  461. ]);
  462. $profile = AccountService::getMastodon($id);
  463. abort_if(!$profile, 404);
  464. $limit = $request->limit ?? 20;
  465. $max_id = $request->max_id;
  466. $min_id = $request->min_id;
  467. if(!$max_id && !$min_id) {
  468. $min_id = 1;
  469. }
  470. $pid = $request->user()->profile_id;
  471. $scope = $request->only_media == true ?
  472. ['photo', 'photo:album', 'video', 'video:album'] :
  473. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  474. if($request->only_media && $request->has('media_type')) {
  475. $mt = $request->input('media_type');
  476. if($mt == 'video') {
  477. $scope = ['video', 'video:album'];
  478. }
  479. }
  480. if($pid == $profile['id']) {
  481. $visibility = ['public', 'unlisted', 'private'];
  482. } else if($profile['locked']) {
  483. $following = FollowerService::follows($pid, $profile['id']);
  484. abort_unless($following, 403);
  485. $visibility = ['public', 'unlisted', 'private'];
  486. } else {
  487. $following = FollowerService::follows($pid, $profile['id']);
  488. $visibility = $following ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  489. }
  490. $dir = $min_id ? '>' : '<';
  491. $id = $min_id ?? $max_id;
  492. $res = Status::whereProfileId($profile['id'])
  493. ->whereNull('in_reply_to_id')
  494. ->whereNull('reblog_of_id')
  495. ->whereIn('type', $scope)
  496. ->where('id', $dir, $id)
  497. ->whereIn('scope', $visibility)
  498. ->limit($limit)
  499. ->orderByDesc('id')
  500. ->get()
  501. ->map(function($s) use($user) {
  502. try {
  503. $status = StatusService::getMastodon($s->id, false);
  504. } catch (\Exception $e) {
  505. $status = false;
  506. }
  507. if($user && $status) {
  508. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  509. }
  510. return $status;
  511. })
  512. ->filter(function($s) {
  513. return $s;
  514. })
  515. ->values();
  516. return response()->json($res);
  517. }
  518. /**
  519. * POST /api/v1/accounts/{id}/follow
  520. *
  521. * @param integer $id
  522. *
  523. * @return \App\Transformer\Api\RelationshipTransformer
  524. */
  525. public function accountFollowById(Request $request, $id)
  526. {
  527. abort_if(!$request->user(), 403);
  528. $user = $request->user();
  529. $target = Profile::where('id', '!=', $user->profile_id)
  530. ->whereNull('status')
  531. ->findOrFail($id);
  532. $private = (bool) $target->is_private;
  533. $remote = (bool) $target->domain;
  534. $blocked = UserFilter::whereUserId($target->id)
  535. ->whereFilterType('block')
  536. ->whereFilterableId($user->profile_id)
  537. ->whereFilterableType('App\Profile')
  538. ->exists();
  539. if($blocked == true) {
  540. abort(400, 'You cannot follow this user.');
  541. }
  542. $isFollowing = Follower::whereProfileId($user->profile_id)
  543. ->whereFollowingId($target->id)
  544. ->exists();
  545. // Following already, return empty relationship
  546. if($isFollowing == true) {
  547. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  548. return response()->json($res);
  549. }
  550. // Rate limits, max 7500 followers per account
  551. if($user->profile->following()->count() >= Follower::MAX_FOLLOWING) {
  552. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  553. }
  554. // Rate limits, follow 30 accounts per hour max
  555. if($user->profile->following()->where('followers.created_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  556. abort(400, 'You can only follow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  557. }
  558. if($private == true) {
  559. $follow = FollowRequest::firstOrCreate([
  560. 'follower_id' => $user->profile_id,
  561. 'following_id' => $target->id
  562. ]);
  563. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  564. (new FollowerController())->sendFollow($user->profile, $target);
  565. }
  566. } else {
  567. $follower = new Follower();
  568. $follower->profile_id = $user->profile_id;
  569. $follower->following_id = $target->id;
  570. $follower->save();
  571. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  572. (new FollowerController())->sendFollow($user->profile, $target);
  573. }
  574. FollowPipeline::dispatch($follower);
  575. }
  576. RelationshipService::refresh($user->profile_id, $target->id);
  577. Cache::forget('profile:following:'.$target->id);
  578. Cache::forget('profile:followers:'.$target->id);
  579. Cache::forget('profile:following:'.$user->profile_id);
  580. Cache::forget('profile:followers:'.$user->profile_id);
  581. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  582. Cache::forget('user:account:id:'.$target->user_id);
  583. Cache::forget('user:account:id:'.$user->id);
  584. Cache::forget('profile:follower_count:'.$target->id);
  585. Cache::forget('profile:follower_count:'.$user->profile_id);
  586. Cache::forget('profile:following_count:'.$target->id);
  587. Cache::forget('profile:following_count:'.$user->profile_id);
  588. AccountService::del($user->profile_id);
  589. AccountService::del($target->id);
  590. $res = RelationshipService::get($user->profile_id, $target->id);
  591. return response()->json($res);
  592. }
  593. /**
  594. * POST /api/v1/accounts/{id}/unfollow
  595. *
  596. * @param integer $id
  597. *
  598. * @return \App\Transformer\Api\RelationshipTransformer
  599. */
  600. public function accountUnfollowById(Request $request, $id)
  601. {
  602. abort_if(!$request->user(), 403);
  603. $user = $request->user();
  604. $target = Profile::where('id', '!=', $user->profile_id)
  605. ->whereNull('status')
  606. ->findOrFail($id);
  607. $private = (bool) $target->is_private;
  608. $remote = (bool) $target->domain;
  609. $isFollowing = Follower::whereProfileId($user->profile_id)
  610. ->whereFollowingId($target->id)
  611. ->exists();
  612. if($isFollowing == false) {
  613. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  614. $res = $this->fractal->createData($resource)->toArray();
  615. return response()->json($res);
  616. }
  617. // Rate limits, follow 30 accounts per hour max
  618. if($user->profile->following()->where('followers.updated_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  619. abort(400, 'You can only follow or unfollow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  620. }
  621. $user->profile->decrement('following_count');
  622. FollowRequest::whereFollowerId($user->profile_id)
  623. ->whereFollowingId($target->id)
  624. ->delete();
  625. Follower::whereProfileId($user->profile_id)
  626. ->whereFollowingId($target->id)
  627. ->delete();
  628. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  629. (new FollowerController())->sendUndoFollow($user->profile, $target);
  630. }
  631. RelationshipService::refresh($user->profile_id, $target->id);
  632. Cache::forget('profile:following:'.$target->id);
  633. Cache::forget('profile:followers:'.$target->id);
  634. Cache::forget('profile:following:'.$user->profile_id);
  635. Cache::forget('profile:followers:'.$user->profile_id);
  636. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  637. Cache::forget('user:account:id:'.$target->user_id);
  638. Cache::forget('user:account:id:'.$user->id);
  639. Cache::forget('profile:follower_count:'.$target->id);
  640. Cache::forget('profile:follower_count:'.$user->profile_id);
  641. Cache::forget('profile:following_count:'.$target->id);
  642. Cache::forget('profile:following_count:'.$user->profile_id);
  643. AccountService::del($user->profile_id);
  644. AccountService::del($target->id);
  645. $res = RelationshipService::get($user->profile_id, $target->id);
  646. return response()->json($res);
  647. }
  648. /**
  649. * GET /api/v1/accounts/relationships
  650. *
  651. * @param array|integer $id
  652. *
  653. * @return \App\Services\RelationshipService
  654. */
  655. public function accountRelationshipsById(Request $request)
  656. {
  657. abort_if(!$request->user(), 403);
  658. $this->validate($request, [
  659. 'id' => 'required|array|min:1|max:20',
  660. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  661. ]);
  662. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  663. $res = collect($request->input('id'))
  664. ->filter(function($id) use($pid) {
  665. return $id != $pid;
  666. })
  667. ->map(function($id) use($pid) {
  668. return RelationshipService::get($pid, $id);
  669. });
  670. return response()->json($res);
  671. }
  672. /**
  673. * GET /api/v1/accounts/search
  674. *
  675. *
  676. *
  677. * @return \App\Transformer\Api\AccountTransformer
  678. */
  679. public function accountSearch(Request $request)
  680. {
  681. abort_if(!$request->user(), 403);
  682. $this->validate($request, [
  683. 'q' => 'required|string|min:1|max:255',
  684. 'limit' => 'nullable|integer|min:1|max:40',
  685. 'resolve' => 'nullable'
  686. ]);
  687. $user = $request->user();
  688. $query = $request->input('q');
  689. $limit = $request->input('limit') ?? 20;
  690. $resolve = (bool) $request->input('resolve', false);
  691. $q = '%' . $query . '%';
  692. $profiles = Profile::whereNull('status')
  693. ->where('username', 'like', $q)
  694. ->orWhere('name', 'like', $q)
  695. ->limit($limit)
  696. ->get();
  697. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  698. $res = $this->fractal->createData($resource)->toArray();
  699. return response()->json($res);
  700. }
  701. /**
  702. * GET /api/v1/blocks
  703. *
  704. *
  705. *
  706. * @return \App\Transformer\Api\AccountTransformer
  707. */
  708. public function accountBlocks(Request $request)
  709. {
  710. abort_if(!$request->user(), 403);
  711. $this->validate($request, [
  712. 'limit' => 'nullable|integer|min:1|max:40',
  713. 'page' => 'nullable|integer|min:1|max:10'
  714. ]);
  715. $user = $request->user();
  716. $limit = $request->input('limit') ?? 40;
  717. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  718. ->whereUserId($user->profile_id)
  719. ->whereFilterableType('App\Profile')
  720. ->whereFilterType('block')
  721. ->simplePaginate($limit)
  722. ->pluck('filterable_id');
  723. $profiles = Profile::findOrFail($blocked);
  724. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  725. $res = $this->fractal->createData($resource)->toArray();
  726. return response()->json($res);
  727. }
  728. /**
  729. * POST /api/v1/accounts/{id}/block
  730. *
  731. * @param integer $id
  732. *
  733. * @return \App\Transformer\Api\RelationshipTransformer
  734. */
  735. public function accountBlockById(Request $request, $id)
  736. {
  737. abort_if(!$request->user(), 403);
  738. $user = $request->user();
  739. $pid = $user->profile_id ?? $user->profile->id;
  740. if($id == $pid) {
  741. abort(400, 'You cannot block yourself');
  742. }
  743. $profile = Profile::findOrFail($id);
  744. if($profile->user->is_admin == true) {
  745. abort(400, 'You cannot block an admin');
  746. }
  747. Follower::whereProfileId($profile->id)->whereFollowingId($pid)->delete();
  748. Follower::whereProfileId($pid)->whereFollowingId($profile->id)->delete();
  749. Notification::whereProfileId($pid)->whereActorId($profile->id)->delete();
  750. $filter = UserFilter::firstOrCreate([
  751. 'user_id' => $pid,
  752. 'filterable_id' => $profile->id,
  753. 'filterable_type' => 'App\Profile',
  754. 'filter_type' => 'block',
  755. ]);
  756. Cache::forget("user:filter:list:$pid");
  757. Cache::forget("api:local:exp:rec:$pid");
  758. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  759. $res = $this->fractal->createData($resource)->toArray();
  760. return response()->json($res);
  761. }
  762. /**
  763. * POST /api/v1/accounts/{id}/unblock
  764. *
  765. * @param integer $id
  766. *
  767. * @return \App\Transformer\Api\RelationshipTransformer
  768. */
  769. public function accountUnblockById(Request $request, $id)
  770. {
  771. abort_if(!$request->user(), 403);
  772. $user = $request->user();
  773. $pid = $user->profile_id ?? $user->profile->id;
  774. if($id == $pid) {
  775. abort(400, 'You cannot unblock yourself');
  776. }
  777. $profile = Profile::findOrFail($id);
  778. UserFilter::whereUserId($pid)
  779. ->whereFilterableId($profile->id)
  780. ->whereFilterableType('App\Profile')
  781. ->whereFilterType('block')
  782. ->delete();
  783. Cache::forget("user:filter:list:$pid");
  784. Cache::forget("api:local:exp:rec:$pid");
  785. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  786. $res = $this->fractal->createData($resource)->toArray();
  787. return response()->json($res);
  788. }
  789. /**
  790. * GET /api/v1/custom_emojis
  791. *
  792. * Return empty array, we don't support custom emoji
  793. *
  794. * @return array
  795. */
  796. public function customEmojis()
  797. {
  798. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  799. }
  800. /**
  801. * GET /api/v1/domain_blocks
  802. *
  803. * Return empty array
  804. *
  805. * @return array
  806. */
  807. public function accountDomainBlocks(Request $request)
  808. {
  809. abort_if(!$request->user(), 403);
  810. return response()->json([]);
  811. }
  812. /**
  813. * GET /api/v1/endorsements
  814. *
  815. * Return empty array
  816. *
  817. * @return array
  818. */
  819. public function accountEndorsements(Request $request)
  820. {
  821. abort_if(!$request->user(), 403);
  822. return response()->json([]);
  823. }
  824. /**
  825. * GET /api/v1/favourites
  826. *
  827. * Returns collection of liked statuses
  828. *
  829. * @return \App\Transformer\Api\StatusTransformer
  830. */
  831. public function accountFavourites(Request $request)
  832. {
  833. abort_if(!$request->user(), 403);
  834. $this->validate($request, [
  835. 'limit' => 'sometimes|integer|min:1|max:20'
  836. ]);
  837. $user = $request->user();
  838. $maxId = $request->input('max_id');
  839. $minId = $request->input('min_id');
  840. $limit = $request->input('limit') ?? 10;
  841. $res = Like::whereProfileId($user->profile_id)
  842. ->when($maxId, function($q, $maxId) {
  843. return $q->where('id', '<', $maxId);
  844. })
  845. ->when($minId, function($q, $minId) {
  846. return $q->where('id', '>', $minId);
  847. })
  848. ->orderByDesc('id')
  849. ->limit($limit)
  850. ->get()
  851. ->map(function($like) {
  852. $status = StatusService::getMastodon($like['status_id'], false);
  853. $status['like_id'] = $like->id;
  854. $status['liked_at'] = $like->created_at->format('c');
  855. return $status;
  856. })
  857. ->filter(function($status) {
  858. return $status && isset($status['id'], $status['like_id']);
  859. })
  860. ->values();
  861. if($res->count()) {
  862. $ids = $res->map(function($status) {
  863. return $status['like_id'];
  864. });
  865. $max = $ids->max();
  866. $min = $ids->min();
  867. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  868. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  869. return response()
  870. ->json($res)
  871. ->withHeaders([
  872. 'Link' => $link,
  873. ]);
  874. } else {
  875. return response()->json($res);
  876. }
  877. }
  878. /**
  879. * POST /api/v1/statuses/{id}/favourite
  880. *
  881. * @param integer $id
  882. *
  883. * @return \App\Transformer\Api\StatusTransformer
  884. */
  885. public function statusFavouriteById(Request $request, $id)
  886. {
  887. abort_if(!$request->user(), 403);
  888. $user = $request->user();
  889. $status = StatusService::getMastodon($id, false);
  890. abort_unless($status, 400);
  891. $spid = $status['account']['id'];
  892. if($spid !== $user->profile_id) {
  893. if($status['visibility'] == 'private') {
  894. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  895. } else {
  896. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  897. }
  898. }
  899. abort_if(
  900. Like::whereProfileId($user->profile_id)
  901. ->where('created_at', '>', now()->subDay())
  902. ->count() >= 100,
  903. 429
  904. );
  905. $like = Like::firstOrCreate([
  906. 'profile_id' => $user->profile_id,
  907. 'status_id' => $status['id']
  908. ]);
  909. if($like->wasRecentlyCreated == true) {
  910. $like->status_profile_id = $spid;
  911. $like->is_comment = !empty($status['in_reply_to_id']);
  912. $like->save();
  913. Status::findOrFail($status['id'])->update([
  914. 'favourites_count' => ($status['favourites_count'] ?? 0) + 1
  915. ]);
  916. LikePipeline::dispatch($like);
  917. }
  918. $status['favourited'] = true;
  919. $status['favourites_count'] = $status['favourites_count'] + 1;
  920. return response()->json($status);
  921. }
  922. /**
  923. * POST /api/v1/statuses/{id}/unfavourite
  924. *
  925. * @param integer $id
  926. *
  927. * @return \App\Transformer\Api\StatusTransformer
  928. */
  929. public function statusUnfavouriteById(Request $request, $id)
  930. {
  931. abort_if(!$request->user(), 403);
  932. $user = $request->user();
  933. $status = Status::findOrFail($id);
  934. if($status->profile_id !== $user->profile_id) {
  935. if($status->scope == 'private') {
  936. abort_if(!$status->profile->followedBy($user->profile), 403);
  937. } else {
  938. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  939. }
  940. }
  941. $like = Like::whereProfileId($user->profile_id)
  942. ->whereStatusId($status->id)
  943. ->first();
  944. if($like) {
  945. $like->forceDelete();
  946. $status->likes_count = $status->likes()->count();
  947. $status->save();
  948. }
  949. StatusService::del($status->id);
  950. $res = StatusService::getMastodon($status->id, false);
  951. $res['favourited'] = false;
  952. return response()->json($res);
  953. }
  954. /**
  955. * GET /api/v1/filters
  956. *
  957. * Return empty response since we filter server side
  958. *
  959. * @return array
  960. */
  961. public function accountFilters(Request $request)
  962. {
  963. abort_if(!$request->user(), 403);
  964. return response()->json([]);
  965. }
  966. /**
  967. * GET /api/v1/follow_requests
  968. *
  969. * Return array of Accounts that have sent follow requests
  970. *
  971. * @return \App\Transformer\Api\AccountTransformer
  972. */
  973. public function accountFollowRequests(Request $request)
  974. {
  975. abort_if(!$request->user(), 403);
  976. $user = $request->user();
  977. $followRequests = FollowRequest::whereFollowingId($user->profile->id)->pluck('follower_id');
  978. $profiles = Profile::find($followRequests);
  979. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  980. $res = $this->fractal->createData($resource)->toArray();
  981. return response()->json($res);
  982. }
  983. /**
  984. * POST /api/v1/follow_requests/{id}/authorize
  985. *
  986. * @param integer $id
  987. *
  988. * @return null
  989. */
  990. public function accountFollowRequestAccept(Request $request, $id)
  991. {
  992. abort_if(!$request->user(), 403);
  993. // todo
  994. return response()->json([]);
  995. }
  996. /**
  997. * POST /api/v1/follow_requests/{id}/reject
  998. *
  999. * @param integer $id
  1000. *
  1001. * @return null
  1002. */
  1003. public function accountFollowRequestReject(Request $request, $id)
  1004. {
  1005. abort_if(!$request->user(), 403);
  1006. // todo
  1007. return response()->json([]);
  1008. }
  1009. /**
  1010. * GET /api/v1/suggestions
  1011. *
  1012. * Return empty array as we don't support suggestions
  1013. *
  1014. * @return null
  1015. */
  1016. public function accountSuggestions(Request $request)
  1017. {
  1018. abort_if(!$request->user(), 403);
  1019. // todo
  1020. return response()->json([]);
  1021. }
  1022. /**
  1023. * GET /api/v1/instance
  1024. *
  1025. * Information about the server.
  1026. *
  1027. * @return Instance
  1028. */
  1029. public function instance(Request $request)
  1030. {
  1031. $res = Cache::remember('api:v1:instance-data-response-v0', 1800, function () {
  1032. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1033. $admin = User::whereIsAdmin(true)->first();
  1034. return $admin && isset($admin->profile_id) ?
  1035. AccountService::getMastodon($admin->profile_id, true) :
  1036. null;
  1037. });
  1038. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1039. return [
  1040. 'user_count' => User::count(),
  1041. 'status_count' => Status::whereNull('uri')->count(),
  1042. 'domain_count' => Instance::count(),
  1043. ];
  1044. });
  1045. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1046. return config_cache('app.rules') ?
  1047. collect(json_decode(config_cache('app.rules'), true))
  1048. ->map(function($rule, $key) {
  1049. $id = $key + 1;
  1050. return [
  1051. 'id' => "{$id}",
  1052. 'text' => $rule
  1053. ];
  1054. })
  1055. ->toArray() : [];
  1056. });
  1057. return [
  1058. 'uri' => config('pixelfed.domain.app'),
  1059. 'title' => config('app.name'),
  1060. 'short_description' => 'Pixelfed is an image sharing platform, an ethical alternative to centralized platforms',
  1061. 'description' => 'Pixelfed is an image sharing platform, an ethical alternative to centralized platforms',
  1062. 'email' => config('instance.email'),
  1063. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1064. 'urls' => [
  1065. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1066. ],
  1067. 'stats' => $stats,
  1068. 'thumbnail' => url('img/pixelfed-icon-color.png'),
  1069. 'languages' => ['en'],
  1070. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1071. 'approval_required' => false,
  1072. 'contact_account' => $contact,
  1073. 'rules' => $rules
  1074. ];
  1075. });
  1076. return response()->json($res, 200, [], JSON_UNESCAPED_SLASHES);
  1077. }
  1078. /**
  1079. * GET /api/v1/lists
  1080. *
  1081. * Return empty array as we don't support lists
  1082. *
  1083. * @return null
  1084. */
  1085. public function accountLists(Request $request)
  1086. {
  1087. abort_if(!$request->user(), 403);
  1088. return response()->json([]);
  1089. }
  1090. /**
  1091. * GET /api/v1/accounts/{id}/lists
  1092. *
  1093. * @param integer $id
  1094. *
  1095. * @return null
  1096. */
  1097. public function accountListsById(Request $request, $id)
  1098. {
  1099. abort_if(!$request->user(), 403);
  1100. return response()->json([]);
  1101. }
  1102. /**
  1103. * POST /api/v1/media
  1104. *
  1105. *
  1106. * @return MediaTransformer
  1107. */
  1108. public function mediaUpload(Request $request)
  1109. {
  1110. abort_if(!$request->user(), 403);
  1111. $this->validate($request, [
  1112. 'file.*' => function() {
  1113. return [
  1114. 'required',
  1115. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1116. 'max:' . config_cache('pixelfed.max_photo_size'),
  1117. ];
  1118. },
  1119. 'filter_name' => 'nullable|string|max:24',
  1120. 'filter_class' => 'nullable|alpha_dash|max:24',
  1121. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1122. ]);
  1123. $user = $request->user();
  1124. if($user->last_active_at == null) {
  1125. return [];
  1126. }
  1127. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1128. $limitTtl = now()->addMinutes(15);
  1129. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1130. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1131. return $dailyLimit >= 250;
  1132. });
  1133. abort_if($limitReached == true, 429);
  1134. $profile = $user->profile;
  1135. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1136. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1137. return Media::whereUserId($user->id)->sum('size') / 1000;
  1138. });
  1139. $limit = (int) config_cache('pixelfed.max_account_size');
  1140. if ($size >= $limit) {
  1141. abort(403, 'Account size limit reached.');
  1142. }
  1143. }
  1144. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1145. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1146. $photo = $request->file('file');
  1147. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1148. if(in_array($photo->getMimeType(), $mimes) == false) {
  1149. abort(403, 'Invalid or unsupported mime type.');
  1150. }
  1151. $storagePath = MediaPathService::get($user, 2);
  1152. $path = $photo->store($storagePath);
  1153. $hash = \hash_file('sha256', $photo);
  1154. $license = null;
  1155. $mime = $photo->getMimeType();
  1156. // if($photo->getMimeType() == 'image/heic') {
  1157. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1158. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1159. // $oldPath = $path;
  1160. // $path = str_replace('.heic', '.jpg', $path);
  1161. // $mime = 'image/jpeg';
  1162. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1163. // @unlink(storage_path("app/{$oldPath}"));
  1164. // }
  1165. $settings = UserSetting::whereUserId($user->id)->first();
  1166. if($settings && !empty($settings->compose_settings)) {
  1167. $compose = $settings->compose_settings;
  1168. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1169. $license = $compose['default_license'];
  1170. }
  1171. }
  1172. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1173. $media = new Media();
  1174. $media->status_id = null;
  1175. $media->profile_id = $profile->id;
  1176. $media->user_id = $user->id;
  1177. $media->media_path = $path;
  1178. $media->original_sha256 = $hash;
  1179. $media->size = $photo->getSize();
  1180. $media->mime = $mime;
  1181. $media->caption = $request->input('description');
  1182. $media->filter_class = $filterClass;
  1183. $media->filter_name = $filterName;
  1184. if($license) {
  1185. $media->license = $license;
  1186. }
  1187. $media->save();
  1188. switch ($media->mime) {
  1189. case 'image/jpeg':
  1190. case 'image/png':
  1191. ImageOptimize::dispatch($media);
  1192. break;
  1193. case 'video/mp4':
  1194. VideoThumbnail::dispatch($media);
  1195. $preview_url = '/storage/no-preview.png';
  1196. $url = '/storage/no-preview.png';
  1197. break;
  1198. }
  1199. Cache::forget($limitKey);
  1200. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1201. $res = $this->fractal->createData($resource)->toArray();
  1202. $res['preview_url'] = $media->url(). '?cb=1&_v=' . time();
  1203. $res['url'] = $media->url(). '?cb=1&_v=' . time();
  1204. return response()->json($res);
  1205. }
  1206. /**
  1207. * PUT /api/v1/media/{id}
  1208. *
  1209. * @param integer $id
  1210. *
  1211. * @return MediaTransformer
  1212. */
  1213. public function mediaUpdate(Request $request, $id)
  1214. {
  1215. abort_if(!$request->user(), 403);
  1216. $this->validate($request, [
  1217. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1218. ]);
  1219. $user = $request->user();
  1220. $media = Media::whereUserId($user->id)
  1221. ->whereNull('status_id')
  1222. ->findOrFail($id);
  1223. $media->caption = $request->input('description');
  1224. $media->save();
  1225. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1226. $res = $this->fractal->createData($resource)->toArray();
  1227. $res['preview_url'] = url('/storage/no-preview.png');
  1228. $res['url'] = url('/storage/no-preview.png');
  1229. return response()->json($res);
  1230. }
  1231. /**
  1232. * GET /api/v1/media/{id}
  1233. *
  1234. * @param integer $id
  1235. *
  1236. * @return MediaTransformer
  1237. */
  1238. public function mediaGet(Request $request, $id)
  1239. {
  1240. abort_if(!$request->user(), 403);
  1241. $user = $request->user();
  1242. $media = Media::whereUserId($user->id)
  1243. ->whereNull('status_id')
  1244. ->findOrFail($id);
  1245. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1246. $res = $this->fractal->createData($resource)->toArray();
  1247. $res['preview_url'] = url('/storage/no-preview.png');
  1248. $res['url'] = url('/storage/no-preview.png');
  1249. return response()->json($res);
  1250. }
  1251. /**
  1252. * GET /api/v1/mutes
  1253. *
  1254. *
  1255. * @return AccountTransformer
  1256. */
  1257. public function accountMutes(Request $request)
  1258. {
  1259. abort_if(!$request->user(), 403);
  1260. $this->validate($request, [
  1261. 'limit' => 'nullable|integer|min:1|max:40'
  1262. ]);
  1263. $user = $request->user();
  1264. $limit = $request->input('limit') ?? 40;
  1265. $mutes = UserFilter::whereUserId($user->profile_id)
  1266. ->whereFilterableType('App\Profile')
  1267. ->whereFilterType('mute')
  1268. ->simplePaginate($limit)
  1269. ->pluck('filterable_id');
  1270. $accounts = Profile::find($mutes);
  1271. $resource = new Fractal\Resource\Collection($accounts, new AccountTransformer());
  1272. $res = $this->fractal->createData($resource)->toArray();
  1273. return response()->json($res);
  1274. }
  1275. /**
  1276. * POST /api/v1/accounts/{id}/mute
  1277. *
  1278. * @param integer $id
  1279. *
  1280. * @return RelationshipTransformer
  1281. */
  1282. public function accountMuteById(Request $request, $id)
  1283. {
  1284. abort_if(!$request->user(), 403);
  1285. $user = $request->user();
  1286. $pid = $user->profile_id;
  1287. $account = Profile::findOrFail($id);
  1288. $filter = UserFilter::firstOrCreate([
  1289. 'user_id' => $pid,
  1290. 'filterable_id' => $account->id,
  1291. 'filterable_type' => 'App\Profile',
  1292. 'filter_type' => 'mute',
  1293. ]);
  1294. Cache::forget("user:filter:list:$pid");
  1295. Cache::forget("feature:discover:posts:$pid");
  1296. Cache::forget("api:local:exp:rec:$pid");
  1297. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1298. $res = $this->fractal->createData($resource)->toArray();
  1299. return response()->json($res);
  1300. }
  1301. /**
  1302. * POST /api/v1/accounts/{id}/unmute
  1303. *
  1304. * @param integer $id
  1305. *
  1306. * @return RelationshipTransformer
  1307. */
  1308. public function accountUnmuteById(Request $request, $id)
  1309. {
  1310. abort_if(!$request->user(), 403);
  1311. $user = $request->user();
  1312. $pid = $user->profile_id;
  1313. $account = Profile::findOrFail($id);
  1314. $filter = UserFilter::whereUserId($pid)
  1315. ->whereFilterableId($account->id)
  1316. ->whereFilterableType('App\Profile')
  1317. ->whereFilterType('mute')
  1318. ->first();
  1319. if($filter) {
  1320. $filter->delete();
  1321. Cache::forget("user:filter:list:$pid");
  1322. Cache::forget("feature:discover:posts:$pid");
  1323. Cache::forget("api:local:exp:rec:$pid");
  1324. }
  1325. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1326. $res = $this->fractal->createData($resource)->toArray();
  1327. return response()->json($res);
  1328. }
  1329. /**
  1330. * GET /api/v1/notifications
  1331. *
  1332. *
  1333. * @return NotificationTransformer
  1334. */
  1335. public function accountNotifications(Request $request)
  1336. {
  1337. abort_if(!$request->user(), 403);
  1338. $this->validate($request, [
  1339. 'limit' => 'nullable|integer|min:1|max:80',
  1340. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1341. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1342. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1343. ]);
  1344. $pid = $request->user()->profile_id;
  1345. $limit = $request->input('limit', 20);
  1346. $since = $request->input('since_id');
  1347. $min = $request->input('min_id');
  1348. $max = $request->input('max_id');
  1349. if(!$since && !$min && !$max) {
  1350. $min = 1;
  1351. }
  1352. $maxId = null;
  1353. $minId = null;
  1354. if($max) {
  1355. $res = NotificationService::getMax($pid, $max, $limit);
  1356. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1357. if(!empty($ids)) {
  1358. $maxId = max($ids);
  1359. $minId = min($ids);
  1360. }
  1361. } else {
  1362. $res = NotificationService::getMin($pid, $min ?? $since, $limit);
  1363. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1364. if(!empty($ids)) {
  1365. $maxId = max($ids);
  1366. $minId = min($ids);
  1367. }
  1368. }
  1369. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1370. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1371. NotificationService::warmCache($pid, 400, true);
  1372. }
  1373. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1374. if($minId == $maxId) {
  1375. $minId = null;
  1376. }
  1377. if($maxId) {
  1378. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next"';
  1379. }
  1380. if($minId) {
  1381. $link = '<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1382. }
  1383. if($maxId && $minId) {
  1384. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next",<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1385. }
  1386. $res = response()->json($res);
  1387. if(isset($link)) {
  1388. $res->withHeaders([
  1389. 'Link' => $link,
  1390. ]);
  1391. }
  1392. return $res;
  1393. }
  1394. /**
  1395. * GET /api/v1/timelines/home
  1396. *
  1397. *
  1398. * @return StatusTransformer
  1399. */
  1400. public function timelineHome(Request $request)
  1401. {
  1402. $this->validate($request,[
  1403. 'page' => 'nullable|integer|max:40',
  1404. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1405. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1406. 'limit' => 'nullable|integer|max:80'
  1407. ]);
  1408. $page = $request->input('page');
  1409. $min = $request->input('min_id');
  1410. $max = $request->input('max_id');
  1411. $limit = $request->input('limit') ?? 3;
  1412. $pid = $request->user()->profile_id;
  1413. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  1414. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1415. return $following->push($pid)->toArray();
  1416. });
  1417. if($min || $max) {
  1418. $dir = $min ? '>' : '<';
  1419. $id = $min ?? $max;
  1420. $res = Status::select(
  1421. 'id',
  1422. 'profile_id',
  1423. 'type',
  1424. 'visibility',
  1425. 'created_at'
  1426. )
  1427. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1428. ->where('id', $dir, $id)
  1429. ->whereIn('profile_id', $following)
  1430. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1431. ->latest()
  1432. ->take($limit)
  1433. ->get()
  1434. ->map(function($s) use($pid) {
  1435. $status = StatusService::getMastodon($s['id']);
  1436. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1437. return false;
  1438. }
  1439. if($pid) {
  1440. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1441. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1442. }
  1443. return $status;
  1444. })
  1445. ->filter(function($status) {
  1446. return $status && isset($status['account']);
  1447. })
  1448. ->values()
  1449. ->toArray();
  1450. } else {
  1451. $res = Status::select(
  1452. 'id',
  1453. 'profile_id',
  1454. 'type',
  1455. 'visibility',
  1456. 'created_at'
  1457. )
  1458. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1459. ->whereIn('profile_id', $following)
  1460. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1461. ->latest()
  1462. ->take($limit)
  1463. ->get()
  1464. ->map(function($s) use($pid) {
  1465. $status = StatusService::getMastodon($s['id']);
  1466. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1467. return false;
  1468. }
  1469. if($pid) {
  1470. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1471. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1472. }
  1473. return $status;
  1474. })
  1475. ->filter(function($status) {
  1476. return $status && isset($status['account']);
  1477. })
  1478. ->values()
  1479. ->toArray();
  1480. }
  1481. return response()->json($res);
  1482. }
  1483. /**
  1484. * GET /api/v1/conversations
  1485. *
  1486. * Not implemented
  1487. *
  1488. * @return array
  1489. */
  1490. public function conversations(Request $request)
  1491. {
  1492. abort_if(!$request->user(), 403);
  1493. $this->validate($request, [
  1494. 'limit' => 'min:1|max:40',
  1495. 'scope' => 'nullable|in:inbox,sent,requests'
  1496. ]);
  1497. $limit = $request->input('limit', 20);
  1498. $scope = $request->input('scope', 'inbox');
  1499. $pid = $request->user()->profile_id;
  1500. if(config('database.default') == 'pgsql') {
  1501. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1502. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid);
  1503. })
  1504. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1505. return $q->whereFromId($pid);
  1506. })
  1507. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1508. return $q->whereToId($pid)->whereIsHidden(true);
  1509. });
  1510. } else {
  1511. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1512. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid)->groupBy('to_id');
  1513. })
  1514. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1515. return $q->whereFromId($pid)->groupBy('to_id');
  1516. })
  1517. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1518. return $q->whereToId($pid)->whereIsHidden(true);
  1519. });
  1520. }
  1521. $dms = $dms->latest()
  1522. ->simplePaginate($limit)
  1523. ->map(function($dm) use($pid) {
  1524. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  1525. $res = [
  1526. 'id' => $dm->id,
  1527. 'unread' => false,
  1528. 'accounts' => [
  1529. AccountService::getMastodon($from)
  1530. ],
  1531. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  1532. ];
  1533. return $res;
  1534. })
  1535. ->filter(function($dm) {
  1536. return isset($dm['accounts']) && count($dm['accounts']);
  1537. })
  1538. ->unique(function($item, $key) {
  1539. return $item['accounts'][0]['id'];
  1540. })
  1541. ->values();
  1542. return response()->json($dms);
  1543. }
  1544. /**
  1545. * GET /api/v1/timelines/public
  1546. *
  1547. *
  1548. * @return StatusTransformer
  1549. */
  1550. public function timelinePublic(Request $request)
  1551. {
  1552. $this->validate($request,[
  1553. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1554. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1555. 'limit' => 'nullable|integer|max:80'
  1556. ]);
  1557. $min = $request->input('min_id');
  1558. $max = $request->input('max_id');
  1559. $limit = $request->input('limit') ?? 3;
  1560. $user = $request->user();
  1561. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1562. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1563. if(PublicTimelineService::count() == 0) {
  1564. PublicTimelineService::warmCache(true, 400);
  1565. }
  1566. });
  1567. if ($max) {
  1568. $feed = PublicTimelineService::getRankedMaxId($max, $limit);
  1569. } else if ($min) {
  1570. $feed = PublicTimelineService::getRankedMinId($min, $limit);
  1571. } else {
  1572. $feed = PublicTimelineService::get(0, $limit);
  1573. }
  1574. $res = collect($feed)
  1575. ->map(function($k) use($user) {
  1576. $status = StatusService::getMastodon($k);
  1577. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1578. return false;
  1579. }
  1580. if($user) {
  1581. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1582. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1583. }
  1584. return $status;
  1585. })
  1586. ->filter(function($s) use($filtered) {
  1587. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1588. })
  1589. ->values()
  1590. ->toArray();
  1591. return response()->json($res);
  1592. }
  1593. /**
  1594. * GET /api/v1/statuses/{id}
  1595. *
  1596. * @param integer $id
  1597. *
  1598. * @return StatusTransformer
  1599. */
  1600. public function statusById(Request $request, $id)
  1601. {
  1602. abort_if(!$request->user(), 403);
  1603. $user = $request->user();
  1604. $res = StatusService::getMastodon($id, false);
  1605. if(!$res || !isset($res['visibility'])) {
  1606. abort(404);
  1607. }
  1608. $scope = $res['visibility'];
  1609. if(!in_array($scope, ['public', 'unlisted'])) {
  1610. if($scope === 'private') {
  1611. if($res['account']['id'] != $user->profile_id) {
  1612. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  1613. }
  1614. } else {
  1615. abort(400, 'Invalid request');
  1616. }
  1617. }
  1618. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  1619. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  1620. return response()->json($res);
  1621. }
  1622. /**
  1623. * GET /api/v1/statuses/{id}/context
  1624. *
  1625. * @param integer $id
  1626. *
  1627. * @return StatusTransformer
  1628. */
  1629. public function statusContext(Request $request, $id)
  1630. {
  1631. abort_if(!$request->user(), 403);
  1632. $user = $request->user();
  1633. $status = Status::findOrFail($id);
  1634. if($status->profile_id !== $user->profile_id) {
  1635. if($status->scope == 'private') {
  1636. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1637. } else {
  1638. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1639. }
  1640. }
  1641. if($status->comments_disabled) {
  1642. $res = [
  1643. 'ancestors' => [],
  1644. 'descendants' => []
  1645. ];
  1646. } else {
  1647. $ancestors = $status->parent();
  1648. if($ancestors) {
  1649. $ares = new Fractal\Resource\Item($ancestors, new StatusTransformer());
  1650. $ancestors = [
  1651. $this->fractal->createData($ares)->toArray()
  1652. ];
  1653. } else {
  1654. $ancestors = [];
  1655. }
  1656. $descendants = Status::whereInReplyToId($id)->latest()->limit(20)->get();
  1657. $dres = new Fractal\Resource\Collection($descendants, new StatusTransformer());
  1658. $descendants = $this->fractal->createData($dres)->toArray();
  1659. $res = [
  1660. 'ancestors' => $ancestors,
  1661. 'descendants' => $descendants
  1662. ];
  1663. }
  1664. return response()->json($res);
  1665. }
  1666. /**
  1667. * GET /api/v1/statuses/{id}/card
  1668. *
  1669. * @param integer $id
  1670. *
  1671. * @return StatusTransformer
  1672. */
  1673. public function statusCard(Request $request, $id)
  1674. {
  1675. abort_if(!$request->user(), 403);
  1676. $res = [];
  1677. return response()->json($res);
  1678. }
  1679. /**
  1680. * GET /api/v1/statuses/{id}/reblogged_by
  1681. *
  1682. * @param integer $id
  1683. *
  1684. * @return AccountTransformer
  1685. */
  1686. public function statusRebloggedBy(Request $request, $id)
  1687. {
  1688. abort_if(!$request->user(), 403);
  1689. $this->validate($request, [
  1690. 'page' => 'nullable|integer|min:1|max:40',
  1691. 'limit' => 'nullable|integer|min:1|max:80'
  1692. ]);
  1693. $limit = $request->input('limit') ?? 40;
  1694. $user = $request->user();
  1695. $status = Status::findOrFail($id);
  1696. if($status->profile_id !== $user->profile_id) {
  1697. if($status->scope == 'private') {
  1698. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1699. } else {
  1700. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1701. }
  1702. }
  1703. $page = $request->input('page', 1);
  1704. $start = $page == 1 ? 0 : (($page * $limit) - $limit);
  1705. $end = $start + $limit - 1;
  1706. $ids = ReblogService::getPostReblogs($id, $start, $end);
  1707. if(empty($ids)) {
  1708. return [];
  1709. }
  1710. $res = collect($ids)
  1711. ->map(function($id) {
  1712. $status = StatusService::get($id);
  1713. return AccountService::get($status['account']['id']);
  1714. })
  1715. ->filter(function($account) {
  1716. return $account && isset($account['id']);
  1717. })
  1718. ->values();
  1719. $url = $request->url();
  1720. $page = $request->input('page', 1);
  1721. $next = $page < 40 ? $page + 1 : 40;
  1722. $prev = $page > 1 ? $page - 1 : 1;
  1723. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1724. return response()->json($res, 200, ['Link' => $links]);
  1725. }
  1726. /**
  1727. * GET /api/v1/statuses/{id}/favourited_by
  1728. *
  1729. * @param integer $id
  1730. *
  1731. * @return AccountTransformer
  1732. */
  1733. public function statusFavouritedBy(Request $request, $id)
  1734. {
  1735. abort_if(!$request->user(), 403);
  1736. $this->validate($request, [
  1737. 'page' => 'nullable|integer|min:1|max:40',
  1738. 'limit' => 'nullable|integer|min:1|max:80'
  1739. ]);
  1740. $page = $request->input('page', 1);
  1741. $limit = $request->input('limit') ?? 40;
  1742. $user = $request->user();
  1743. $status = Status::findOrFail($id);
  1744. $offset = $page == 1 ? 0 : ($page * $limit - $limit);
  1745. if($offset > 100) {
  1746. if($user->profile_id != $status->profile_id) {
  1747. return [];
  1748. }
  1749. }
  1750. if($status->profile_id !== $user->profile_id) {
  1751. if($status->scope == 'private') {
  1752. abort_if(!$status->profile->followedBy($user->profile), 403);
  1753. } else {
  1754. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1755. }
  1756. }
  1757. $res = DB::table('likes')
  1758. ->select('likes.id', 'likes.profile_id', 'likes.status_id', 'followers.created_at')
  1759. ->leftJoin('followers', function($join) use($user, $status) {
  1760. return $join->on('likes.profile_id', '=', 'followers.following_id')
  1761. ->where('followers.profile_id', $user->profile_id)
  1762. ->where('likes.status_id', $status->id);
  1763. })
  1764. ->whereStatusId($status->id)
  1765. ->orderByDesc('followers.created_at')
  1766. ->offset($offset)
  1767. ->limit($limit)
  1768. ->get()
  1769. ->map(function($like) {
  1770. $account = AccountService::getMastodon($like->profile_id);
  1771. $account['follows'] = isset($like->created_at);
  1772. return $account;
  1773. })
  1774. ->filter(function($account) use($user) {
  1775. return $account && isset($account['id']) && $account['id'] != $user->profile_id;
  1776. })
  1777. ->values();
  1778. $url = $request->url();
  1779. $page = $request->input('page', 1);
  1780. $next = $page < 40 ? $page + 1 : 40;
  1781. $prev = $page > 1 ? $page - 1 : 1;
  1782. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1783. return response()->json($res, 200, ['Link' => $links]);
  1784. }
  1785. /**
  1786. * POST /api/v1/statuses
  1787. *
  1788. *
  1789. * @return StatusTransformer
  1790. */
  1791. public function statusCreate(Request $request)
  1792. {
  1793. abort_if(!$request->user(), 403);
  1794. $this->validate($request, [
  1795. 'status' => 'nullable|string',
  1796. 'in_reply_to_id' => 'nullable|integer',
  1797. 'media_ids' => 'array|max:' . config_cache('pixelfed.max_album_length'),
  1798. 'media_ids.*' => 'integer|min:1',
  1799. 'sensitive' => 'nullable|boolean',
  1800. 'visibility' => 'string|in:private,unlisted,public',
  1801. ]);
  1802. if(config('costar.enabled') == true) {
  1803. $blockedKeywords = config('costar.keyword.block');
  1804. if($blockedKeywords !== null && $request->status) {
  1805. $keywords = config('costar.keyword.block');
  1806. foreach($keywords as $kw) {
  1807. if(Str::contains($request->status, $kw) == true) {
  1808. abort(400, 'Invalid object. Contains banned keyword.');
  1809. }
  1810. }
  1811. }
  1812. }
  1813. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  1814. abort(403, 'Empty statuses are not allowed');
  1815. }
  1816. $ids = $request->input('media_ids');
  1817. $in_reply_to_id = $request->input('in_reply_to_id');
  1818. $user = $request->user();
  1819. $profile = $user->profile;
  1820. $limitKey = 'compose:rate-limit:store:' . $user->id;
  1821. $limitTtl = now()->addMinutes(15);
  1822. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1823. $dailyLimit = Status::whereProfileId($user->profile_id)
  1824. ->whereNull('in_reply_to_id')
  1825. ->whereNull('reblog_of_id')
  1826. ->where('created_at', '>', now()->subDays(1))
  1827. ->count();
  1828. return $dailyLimit >= 100;
  1829. });
  1830. abort_if($limitReached == true, 429);
  1831. $visibility = $profile->is_private ? 'private' : (
  1832. $profile->unlisted == true &&
  1833. $request->input('visibility', 'public') == 'public' ?
  1834. 'unlisted' :
  1835. $request->input('visibility', 'public'));
  1836. if($user->last_active_at == null) {
  1837. return [];
  1838. }
  1839. $content = strip_tags($request->input('status'));
  1840. $rendered = Autolink::create()->autolink($content);
  1841. if($in_reply_to_id) {
  1842. $parent = Status::findOrFail($in_reply_to_id);
  1843. $status = new Status;
  1844. $status->caption = $content;
  1845. $status->rendered = $rendered;
  1846. $status->scope = $visibility;
  1847. $status->visibility = $visibility;
  1848. $status->profile_id = $user->profile_id;
  1849. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1850. $status->in_reply_to_id = $parent->id;
  1851. $status->in_reply_to_profile_id = $parent->profile_id;
  1852. $status->save();
  1853. StatusService::del($parent->id);
  1854. Cache::forget('status:replies:all:' . $parent->id);
  1855. }
  1856. if($ids) {
  1857. if(Media::whereUserId($user->id)
  1858. ->whereNull('status_id')
  1859. ->find($ids)
  1860. ->count() == 0
  1861. ) {
  1862. abort(400, 'Invalid media_ids');
  1863. }
  1864. if(!$in_reply_to_id) {
  1865. $status = new Status;
  1866. $status->caption = $content;
  1867. $status->rendered = $rendered;
  1868. $status->profile_id = $user->profile_id;
  1869. $status->scope = 'draft';
  1870. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1871. $status->save();
  1872. }
  1873. $mimes = [];
  1874. foreach($ids as $k => $v) {
  1875. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  1876. continue;
  1877. }
  1878. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  1879. if($m->profile_id !== $user->profile_id || $m->status_id) {
  1880. abort(403, 'Invalid media id');
  1881. }
  1882. $m->status_id = $status->id;
  1883. $m->save();
  1884. array_push($mimes, $m->mime);
  1885. }
  1886. if(empty($mimes)) {
  1887. $status->delete();
  1888. abort(400, 'Invalid media ids');
  1889. }
  1890. $status->scope = $visibility;
  1891. $status->visibility = $visibility;
  1892. $status->type = StatusController::mimeTypeCheck($mimes);
  1893. $status->save();
  1894. }
  1895. if(!$status) {
  1896. abort(500, 'An error occured.');
  1897. }
  1898. NewStatusPipeline::dispatch($status);
  1899. if($status->in_reply_to_id) {
  1900. CommentPipeline::dispatch($parent, $status);
  1901. }
  1902. Cache::forget('user:account:id:'.$user->id);
  1903. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  1904. Cache::forget('profile:status_count:'.$user->profile_id);
  1905. Cache::forget($user->storageUsedKey());
  1906. Cache::forget('profile:embed:' . $status->profile_id);
  1907. Cache::forget($limitKey);
  1908. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1909. $res = $this->fractal->createData($resource)->toArray();
  1910. return response()->json($res);
  1911. }
  1912. /**
  1913. * DELETE /api/v1/statuses
  1914. *
  1915. * @param integer $id
  1916. *
  1917. * @return null
  1918. */
  1919. public function statusDelete(Request $request, $id)
  1920. {
  1921. abort_if(!$request->user(), 403);
  1922. $status = Status::whereProfileId($request->user()->profile->id)
  1923. ->findOrFail($id);
  1924. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1925. Cache::forget('profile:status_count:'.$status->profile_id);
  1926. StatusDelete::dispatch($status);
  1927. $res = $this->fractal->createData($resource)->toArray();
  1928. $res['text'] = $res['content'];
  1929. unset($res['content']);
  1930. return response()->json($res);
  1931. }
  1932. /**
  1933. * POST /api/v1/statuses/{id}/reblog
  1934. *
  1935. * @param integer $id
  1936. *
  1937. * @return StatusTransformer
  1938. */
  1939. public function statusShare(Request $request, $id)
  1940. {
  1941. abort_if(!$request->user(), 403);
  1942. $user = $request->user();
  1943. $status = Status::whereScope('public')->findOrFail($id);
  1944. if($status->profile_id !== $user->profile_id) {
  1945. if($status->scope == 'private') {
  1946. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1947. } else {
  1948. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1949. }
  1950. }
  1951. $share = Status::firstOrCreate([
  1952. 'profile_id' => $user->profile_id,
  1953. 'reblog_of_id' => $status->id,
  1954. 'type' => 'share',
  1955. 'in_reply_to_profile_id' => $status->profile_id,
  1956. 'scope' => 'public',
  1957. 'visibility' => 'public'
  1958. ]);
  1959. if($share->wasRecentlyCreated == true) {
  1960. SharePipeline::dispatch($share);
  1961. }
  1962. StatusService::del($status->id);
  1963. ReblogService::add($user->profile_id, $status->id);
  1964. $res = StatusService::getMastodon($status->id);
  1965. $res['reblogged'] = true;
  1966. return response()->json($res);
  1967. }
  1968. /**
  1969. * POST /api/v1/statuses/{id}/unreblog
  1970. *
  1971. * @param integer $id
  1972. *
  1973. * @return StatusTransformer
  1974. */
  1975. public function statusUnshare(Request $request, $id)
  1976. {
  1977. abort_if(!$request->user(), 403);
  1978. $user = $request->user();
  1979. $status = Status::whereScope('public')->findOrFail($id);
  1980. if($status->profile_id !== $user->profile_id) {
  1981. if($status->scope == 'private') {
  1982. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1983. } else {
  1984. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1985. }
  1986. }
  1987. $reblog = Status::whereProfileId($user->profile_id)
  1988. ->whereReblogOfId($status->id)
  1989. ->first();
  1990. if(!$reblog) {
  1991. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1992. $res = $this->fractal->createData($resource)->toArray();
  1993. return response()->json($res);
  1994. }
  1995. UndoSharePipeline::dispatch($reblog);
  1996. ReblogService::del($user->profile_id, $status->id);
  1997. $res = StatusService::getMastodon($status->id);
  1998. $res['reblogged'] = true;
  1999. return response()->json($res);
  2000. }
  2001. /**
  2002. * GET /api/v1/timelines/tag/{hashtag}
  2003. *
  2004. * @param string $hashtag
  2005. *
  2006. * @return StatusTransformer
  2007. */
  2008. public function timelineHashtag(Request $request, $hashtag)
  2009. {
  2010. $this->validate($request,[
  2011. 'page' => 'nullable|integer|max:40',
  2012. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2013. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2014. 'limit' => 'nullable|integer|max:40'
  2015. ]);
  2016. $tag = Hashtag::whereName($hashtag)
  2017. ->orWhere('slug', $hashtag)
  2018. ->first();
  2019. if(!$tag) {
  2020. return response()->json([]);
  2021. }
  2022. $min = $request->input('min_id');
  2023. $max = $request->input('max_id');
  2024. $limit = $request->input('limit', 20);
  2025. if(!$min && !$max) {
  2026. $id = 1;
  2027. $dir = '>';
  2028. } else {
  2029. $dir = $min ? '>' : '<';
  2030. $id = $min ?? $max;
  2031. }
  2032. $res = StatusHashtag::whereHashtagId($tag->id)
  2033. ->whereStatusVisibility('public')
  2034. ->whereHas('media')
  2035. ->where('status_id', $dir, $id)
  2036. ->latest()
  2037. ->limit($limit)
  2038. ->pluck('status_id')
  2039. ->filter(function($i) {
  2040. return StatusService::getMastodon($i);
  2041. })
  2042. ->map(function ($i) {
  2043. return StatusService::getMastodon($i);
  2044. })
  2045. ->filter()
  2046. ->values()
  2047. ->toArray();
  2048. return response()->json($res, 200, [], JSON_PRETTY_PRINT);
  2049. }
  2050. /**
  2051. * GET /api/v1/bookmarks
  2052. *
  2053. *
  2054. *
  2055. * @return StatusTransformer
  2056. */
  2057. public function bookmarks(Request $request)
  2058. {
  2059. abort_if(!$request->user(), 403);
  2060. $this->validate($request, [
  2061. 'limit' => 'nullable|integer|min:1|max:40',
  2062. 'max_id' => 'nullable|integer|min:0',
  2063. 'since_id' => 'nullable|integer|min:0',
  2064. 'min_id' => 'nullable|integer|min:0'
  2065. ]);
  2066. $pid = $request->user()->profile_id;
  2067. $limit = $request->input('limit') ?? 20;
  2068. $max_id = $request->input('max_id');
  2069. $since_id = $request->input('since_id');
  2070. $min_id = $request->input('min_id');
  2071. $dir = $min_id ? '>' : '<';
  2072. $id = $min_id ?? $max_id;
  2073. if($id) {
  2074. $bookmarks = Bookmark::whereProfileId($pid)
  2075. ->where('status_id', $dir, $id)
  2076. ->limit($limit)
  2077. ->pluck('status_id');
  2078. } else {
  2079. $bookmarks = Bookmark::whereProfileId($pid)
  2080. ->latest()
  2081. ->limit($limit)
  2082. ->pluck('status_id');
  2083. }
  2084. $res = [];
  2085. foreach($bookmarks as $id) {
  2086. $res[] = \App\Services\StatusService::getMastodon($id);
  2087. }
  2088. return $res;
  2089. }
  2090. /**
  2091. * POST /api/v1/statuses/{id}/bookmark
  2092. *
  2093. *
  2094. *
  2095. * @return StatusTransformer
  2096. */
  2097. public function bookmarkStatus(Request $request, $id)
  2098. {
  2099. abort_if(!$request->user(), 403);
  2100. $status = Status::whereNull('uri')
  2101. ->whereScope('public')
  2102. ->findOrFail($id);
  2103. Bookmark::firstOrCreate([
  2104. 'status_id' => $status->id,
  2105. 'profile_id' => $request->user()->profile_id
  2106. ]);
  2107. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2108. $res = $this->fractal->createData($resource)->toArray();
  2109. return response()->json($res);
  2110. }
  2111. /**
  2112. * POST /api/v1/statuses/{id}/unbookmark
  2113. *
  2114. *
  2115. *
  2116. * @return StatusTransformer
  2117. */
  2118. public function unbookmarkStatus(Request $request, $id)
  2119. {
  2120. abort_if(!$request->user(), 403);
  2121. $status = Status::whereNull('uri')
  2122. ->whereScope('public')
  2123. ->findOrFail($id);
  2124. Bookmark::firstOrCreate([
  2125. 'status_id' => $status->id,
  2126. 'profile_id' => $request->user()->profile_id
  2127. ]);
  2128. $bookmark = Bookmark::whereStatusId($status->id)
  2129. ->whereProfileId($request->user()->profile_id)
  2130. ->firstOrFail();
  2131. $bookmark->delete();
  2132. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2133. $res = $this->fractal->createData($resource)->toArray();
  2134. return response()->json($res);
  2135. }
  2136. /**
  2137. * GET /api/v2/search
  2138. *
  2139. *
  2140. * @return array
  2141. */
  2142. public function searchV2(Request $request)
  2143. {
  2144. abort_if(!$request->user(), 403);
  2145. $this->validate($request, [
  2146. 'q' => 'required|string|min:1|max:80',
  2147. 'account_id' => 'nullable|string',
  2148. 'max_id' => 'nullable|string',
  2149. 'min_id' => 'nullable|string',
  2150. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2151. 'exclude_unreviewed' => 'nullable',
  2152. 'resolve' => 'nullable',
  2153. 'limit' => 'nullable|integer|max:40',
  2154. 'offset' => 'nullable|integer',
  2155. 'following' => 'nullable'
  2156. ]);
  2157. return SearchApiV2Service::query($request);
  2158. }
  2159. /**
  2160. * GET /api/v1/discover/posts
  2161. *
  2162. *
  2163. * @return array
  2164. */
  2165. public function discoverPosts(Request $request)
  2166. {
  2167. abort_if(!$request->user(), 403);
  2168. $this->validate($request, [
  2169. 'limit' => 'integer|min:1|max:40'
  2170. ]);
  2171. $limit = $request->input('limit', 40);
  2172. $pid = $request->user()->profile_id;
  2173. $filters = UserFilterService::filters($pid);
  2174. $forYou = DiscoverService::getForYou();
  2175. $posts = $forYou->take(50)->map(function($post) {
  2176. return StatusService::getMastodon($post);
  2177. })
  2178. ->filter(function($post) use($filters) {
  2179. return $post &&
  2180. isset($post['account']) &&
  2181. isset($post['account']['id']) &&
  2182. !in_array($post['account']['id'], $filters);
  2183. })
  2184. ->take(12)
  2185. ->values();
  2186. return response()->json(compact('posts'));
  2187. }
  2188. /**
  2189. * GET /api/v2/statuses/{id}/replies
  2190. *
  2191. *
  2192. * @return array
  2193. */
  2194. public function statusReplies(Request $request, $id)
  2195. {
  2196. abort_if(!$request->user(), 403);
  2197. $this->validate($request, [
  2198. 'limit' => 'int|min:1|max:10',
  2199. 'sort' => 'in:all,newest,popular'
  2200. ]);
  2201. $limit = $request->input('limit', 3);
  2202. $pid = $request->user()->profile_id;
  2203. $status = StatusService::getMastodon($id, false);
  2204. abort_if(!$status, 404);
  2205. if($status['visibility'] == 'private') {
  2206. if($pid != $status['account']['id']) {
  2207. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2208. }
  2209. }
  2210. $sortBy = $request->input('sort', 'all');
  2211. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  2212. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2213. Cache::forget('status:replies:all:' . $id);
  2214. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2215. }
  2216. }
  2217. if($sortBy == 'all' && !$request->has('cursor')) {
  2218. $ids = Cache::remember('status:replies:all:' . $id, 86400, function() use($id) {
  2219. return DB::table('statuses')
  2220. ->where('in_reply_to_id', $id)
  2221. ->orderBy('id')
  2222. ->cursorPaginate(3);
  2223. });
  2224. } else {
  2225. $ids = DB::table('statuses')
  2226. ->where('in_reply_to_id', $id)
  2227. ->when($sortBy, function($q, $sortBy) {
  2228. if($sortBy === 'all') {
  2229. return $q->orderBy('id');
  2230. }
  2231. if($sortBy === 'newest') {
  2232. return $q->orderByDesc('created_at');
  2233. }
  2234. if($sortBy === 'popular') {
  2235. return $q->orderByDesc('likes_count');
  2236. }
  2237. })
  2238. ->cursorPaginate($limit);
  2239. }
  2240. $data = $ids->map(function($post) use($pid) {
  2241. $status = StatusService::get($post->id, false);
  2242. if(!$status || !isset($status['id'])) {
  2243. return false;
  2244. }
  2245. $status['favourited'] = LikeService::liked($pid, $post->id);
  2246. return $status;
  2247. })
  2248. ->filter(function($post) {
  2249. return $post && isset($post['id']) && isset($post['account']);
  2250. })
  2251. ->values();
  2252. $res = [
  2253. 'data' => $data,
  2254. 'next' => $ids->nextPageUrl()
  2255. ];
  2256. return $res;
  2257. }
  2258. /**
  2259. * GET /api/v2/statuses/{id}/state
  2260. *
  2261. *
  2262. * @return array
  2263. */
  2264. public function statusState(Request $request, $id)
  2265. {
  2266. abort_if(!$request->user(), 403);
  2267. $status = Status::findOrFail($id);
  2268. $pid = $request->user()->profile_id;
  2269. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2270. return StatusService::getState($status->id, $pid);
  2271. }
  2272. /**
  2273. * GET /api/v1/discover/accounts/popular
  2274. *
  2275. *
  2276. * @return array
  2277. */
  2278. public function discoverAccountsPopular(Request $request)
  2279. {
  2280. abort_if(!$request->user(), 403);
  2281. $pid = $request->user()->profile_id;
  2282. $ids = DB::table('profiles')
  2283. ->where('is_private', false)
  2284. ->whereNull('status')
  2285. ->orderByDesc('profiles.followers_count')
  2286. ->limit(20)
  2287. ->get();
  2288. $ids = $ids->map(function($profile) {
  2289. return AccountService::getMastodon($profile->id);
  2290. })
  2291. ->filter(function($profile) use($pid) {
  2292. return $profile &&
  2293. isset($profile['id']) &&
  2294. !FollowerService::follows($pid, $profile['id']) &&
  2295. $profile['id'] != $pid;
  2296. })
  2297. ->take(6)
  2298. ->values();
  2299. return response()->json($ids, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  2300. }
  2301. }