1
0

ApiV1Controller.php 69 KB

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