ApiV1Controller.php 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642
  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 = Status::findOrFail($id);
  890. if($status->profile_id !== $user->profile_id) {
  891. if($status->scope == 'private') {
  892. abort_if(!$status->profile->followedBy($user->profile), 403);
  893. } else {
  894. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  895. }
  896. }
  897. $like = Like::firstOrCreate([
  898. 'profile_id' => $user->profile_id,
  899. 'status_id' => $status->id
  900. ]);
  901. if($like->wasRecentlyCreated == true) {
  902. $like->status_profile_id = $status->profile_id;
  903. $like->is_comment = !empty($status->in_reply_to_id);
  904. $like->save();
  905. $status->likes_count = $status->likes()->count();
  906. $status->save();
  907. LikePipeline::dispatch($like);
  908. }
  909. $res = StatusService::getMastodon($status->id, false);
  910. $res['favourited'] = true;
  911. return response()->json($res);
  912. }
  913. /**
  914. * POST /api/v1/statuses/{id}/unfavourite
  915. *
  916. * @param integer $id
  917. *
  918. * @return \App\Transformer\Api\StatusTransformer
  919. */
  920. public function statusUnfavouriteById(Request $request, $id)
  921. {
  922. abort_if(!$request->user(), 403);
  923. $user = $request->user();
  924. $status = Status::findOrFail($id);
  925. if($status->profile_id !== $user->profile_id) {
  926. if($status->scope == 'private') {
  927. abort_if(!$status->profile->followedBy($user->profile), 403);
  928. } else {
  929. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  930. }
  931. }
  932. $like = Like::whereProfileId($user->profile_id)
  933. ->whereStatusId($status->id)
  934. ->first();
  935. if($like) {
  936. $like->forceDelete();
  937. $status->likes_count = $status->likes()->count();
  938. $status->save();
  939. }
  940. StatusService::del($status->id);
  941. $res = StatusService::getMastodon($status->id, false);
  942. $res['favourited'] = false;
  943. return response()->json($res);
  944. }
  945. /**
  946. * GET /api/v1/filters
  947. *
  948. * Return empty response since we filter server side
  949. *
  950. * @return array
  951. */
  952. public function accountFilters(Request $request)
  953. {
  954. abort_if(!$request->user(), 403);
  955. return response()->json([]);
  956. }
  957. /**
  958. * GET /api/v1/follow_requests
  959. *
  960. * Return array of Accounts that have sent follow requests
  961. *
  962. * @return \App\Transformer\Api\AccountTransformer
  963. */
  964. public function accountFollowRequests(Request $request)
  965. {
  966. abort_if(!$request->user(), 403);
  967. $user = $request->user();
  968. $followRequests = FollowRequest::whereFollowingId($user->profile->id)->pluck('follower_id');
  969. $profiles = Profile::find($followRequests);
  970. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  971. $res = $this->fractal->createData($resource)->toArray();
  972. return response()->json($res);
  973. }
  974. /**
  975. * POST /api/v1/follow_requests/{id}/authorize
  976. *
  977. * @param integer $id
  978. *
  979. * @return null
  980. */
  981. public function accountFollowRequestAccept(Request $request, $id)
  982. {
  983. abort_if(!$request->user(), 403);
  984. // todo
  985. return response()->json([]);
  986. }
  987. /**
  988. * POST /api/v1/follow_requests/{id}/reject
  989. *
  990. * @param integer $id
  991. *
  992. * @return null
  993. */
  994. public function accountFollowRequestReject(Request $request, $id)
  995. {
  996. abort_if(!$request->user(), 403);
  997. // todo
  998. return response()->json([]);
  999. }
  1000. /**
  1001. * GET /api/v1/suggestions
  1002. *
  1003. * Return empty array as we don't support suggestions
  1004. *
  1005. * @return null
  1006. */
  1007. public function accountSuggestions(Request $request)
  1008. {
  1009. abort_if(!$request->user(), 403);
  1010. // todo
  1011. return response()->json([]);
  1012. }
  1013. /**
  1014. * GET /api/v1/instance
  1015. *
  1016. * Information about the server.
  1017. *
  1018. * @return Instance
  1019. */
  1020. public function instance(Request $request)
  1021. {
  1022. $res = Cache::remember('api:v1:instance-data-response-v0', 1800, function () {
  1023. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1024. $admin = User::whereIsAdmin(true)->first();
  1025. return $admin && isset($admin->profile_id) ?
  1026. AccountService::getMastodon($admin->profile_id, true) :
  1027. null;
  1028. });
  1029. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1030. return [
  1031. 'user_count' => User::count(),
  1032. 'status_count' => Status::whereNull('uri')->count(),
  1033. 'domain_count' => Instance::count(),
  1034. ];
  1035. });
  1036. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1037. return config_cache('app.rules') ?
  1038. collect(json_decode(config_cache('app.rules'), true))
  1039. ->map(function($rule, $key) {
  1040. $id = $key + 1;
  1041. return [
  1042. 'id' => "{$id}",
  1043. 'text' => $rule
  1044. ];
  1045. })
  1046. ->toArray() : [];
  1047. });
  1048. return [
  1049. 'uri' => config('pixelfed.domain.app'),
  1050. 'title' => config('app.name'),
  1051. 'short_description' => 'Pixelfed is an image sharing platform, an ethical alternative to centralized platforms',
  1052. 'description' => 'Pixelfed is an image sharing platform, an ethical alternative to centralized platforms',
  1053. 'email' => config('instance.email'),
  1054. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1055. 'urls' => [],
  1056. 'stats' => $stats,
  1057. 'thumbnail' => url('headers/default.jpg'),
  1058. 'languages' => ['en'],
  1059. 'registrations' => (bool) config('pixelfed.open_registration'),
  1060. 'approval_required' => false,
  1061. 'contact_account' => $contact,
  1062. 'rules' => $rules
  1063. ];
  1064. });
  1065. return response()->json($res);
  1066. }
  1067. /**
  1068. * GET /api/v1/lists
  1069. *
  1070. * Return empty array as we don't support lists
  1071. *
  1072. * @return null
  1073. */
  1074. public function accountLists(Request $request)
  1075. {
  1076. abort_if(!$request->user(), 403);
  1077. return response()->json([]);
  1078. }
  1079. /**
  1080. * GET /api/v1/accounts/{id}/lists
  1081. *
  1082. * @param integer $id
  1083. *
  1084. * @return null
  1085. */
  1086. public function accountListsById(Request $request, $id)
  1087. {
  1088. abort_if(!$request->user(), 403);
  1089. return response()->json([]);
  1090. }
  1091. /**
  1092. * POST /api/v1/media
  1093. *
  1094. *
  1095. * @return MediaTransformer
  1096. */
  1097. public function mediaUpload(Request $request)
  1098. {
  1099. abort_if(!$request->user(), 403);
  1100. $this->validate($request, [
  1101. 'file.*' => function() {
  1102. return [
  1103. 'required',
  1104. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1105. 'max:' . config_cache('pixelfed.max_photo_size'),
  1106. ];
  1107. },
  1108. 'filter_name' => 'nullable|string|max:24',
  1109. 'filter_class' => 'nullable|alpha_dash|max:24',
  1110. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1111. ]);
  1112. $user = $request->user();
  1113. if($user->last_active_at == null) {
  1114. return [];
  1115. }
  1116. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1117. $limitTtl = now()->addMinutes(15);
  1118. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1119. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1120. return $dailyLimit >= 250;
  1121. });
  1122. abort_if($limitReached == true, 429);
  1123. $profile = $user->profile;
  1124. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1125. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1126. return Media::whereUserId($user->id)->sum('size') / 1000;
  1127. });
  1128. $limit = (int) config_cache('pixelfed.max_account_size');
  1129. if ($size >= $limit) {
  1130. abort(403, 'Account size limit reached.');
  1131. }
  1132. }
  1133. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1134. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1135. $photo = $request->file('file');
  1136. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1137. if(in_array($photo->getMimeType(), $mimes) == false) {
  1138. abort(403, 'Invalid or unsupported mime type.');
  1139. }
  1140. $storagePath = MediaPathService::get($user, 2);
  1141. $path = $photo->store($storagePath);
  1142. $hash = \hash_file('sha256', $photo);
  1143. $license = null;
  1144. $mime = $photo->getMimeType();
  1145. // if($photo->getMimeType() == 'image/heic') {
  1146. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1147. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1148. // $oldPath = $path;
  1149. // $path = str_replace('.heic', '.jpg', $path);
  1150. // $mime = 'image/jpeg';
  1151. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1152. // @unlink(storage_path("app/{$oldPath}"));
  1153. // }
  1154. $settings = UserSetting::whereUserId($user->id)->first();
  1155. if($settings && !empty($settings->compose_settings)) {
  1156. $compose = $settings->compose_settings;
  1157. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1158. $license = $compose['default_license'];
  1159. }
  1160. }
  1161. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1162. $media = new Media();
  1163. $media->status_id = null;
  1164. $media->profile_id = $profile->id;
  1165. $media->user_id = $user->id;
  1166. $media->media_path = $path;
  1167. $media->original_sha256 = $hash;
  1168. $media->size = $photo->getSize();
  1169. $media->mime = $mime;
  1170. $media->caption = $request->input('description');
  1171. $media->filter_class = $filterClass;
  1172. $media->filter_name = $filterName;
  1173. if($license) {
  1174. $media->license = $license;
  1175. }
  1176. $media->save();
  1177. switch ($media->mime) {
  1178. case 'image/jpeg':
  1179. case 'image/png':
  1180. ImageOptimize::dispatch($media);
  1181. break;
  1182. case 'video/mp4':
  1183. VideoThumbnail::dispatch($media);
  1184. $preview_url = '/storage/no-preview.png';
  1185. $url = '/storage/no-preview.png';
  1186. break;
  1187. }
  1188. Cache::forget($limitKey);
  1189. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1190. $res = $this->fractal->createData($resource)->toArray();
  1191. $res['preview_url'] = $media->url(). '?cb=1&_v=' . time();
  1192. $res['url'] = $media->url(). '?cb=1&_v=' . time();
  1193. return response()->json($res);
  1194. }
  1195. /**
  1196. * PUT /api/v1/media/{id}
  1197. *
  1198. * @param integer $id
  1199. *
  1200. * @return MediaTransformer
  1201. */
  1202. public function mediaUpdate(Request $request, $id)
  1203. {
  1204. abort_if(!$request->user(), 403);
  1205. $this->validate($request, [
  1206. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1207. ]);
  1208. $user = $request->user();
  1209. $media = Media::whereUserId($user->id)
  1210. ->whereNull('status_id')
  1211. ->findOrFail($id);
  1212. $media->caption = $request->input('description');
  1213. $media->save();
  1214. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1215. $res = $this->fractal->createData($resource)->toArray();
  1216. $res['preview_url'] = url('/storage/no-preview.png');
  1217. $res['url'] = url('/storage/no-preview.png');
  1218. return response()->json($res);
  1219. }
  1220. /**
  1221. * GET /api/v1/mutes
  1222. *
  1223. *
  1224. * @return AccountTransformer
  1225. */
  1226. public function accountMutes(Request $request)
  1227. {
  1228. abort_if(!$request->user(), 403);
  1229. $this->validate($request, [
  1230. 'limit' => 'nullable|integer|min:1|max:40'
  1231. ]);
  1232. $user = $request->user();
  1233. $limit = $request->input('limit') ?? 40;
  1234. $mutes = UserFilter::whereUserId($user->profile_id)
  1235. ->whereFilterableType('App\Profile')
  1236. ->whereFilterType('mute')
  1237. ->simplePaginate($limit)
  1238. ->pluck('filterable_id');
  1239. $accounts = Profile::find($mutes);
  1240. $resource = new Fractal\Resource\Collection($accounts, new AccountTransformer());
  1241. $res = $this->fractal->createData($resource)->toArray();
  1242. return response()->json($res);
  1243. }
  1244. /**
  1245. * POST /api/v1/accounts/{id}/mute
  1246. *
  1247. * @param integer $id
  1248. *
  1249. * @return RelationshipTransformer
  1250. */
  1251. public function accountMuteById(Request $request, $id)
  1252. {
  1253. abort_if(!$request->user(), 403);
  1254. $user = $request->user();
  1255. $pid = $user->profile_id;
  1256. $account = Profile::findOrFail($id);
  1257. $filter = UserFilter::firstOrCreate([
  1258. 'user_id' => $pid,
  1259. 'filterable_id' => $account->id,
  1260. 'filterable_type' => 'App\Profile',
  1261. 'filter_type' => 'mute',
  1262. ]);
  1263. Cache::forget("user:filter:list:$pid");
  1264. Cache::forget("feature:discover:posts:$pid");
  1265. Cache::forget("api:local:exp:rec:$pid");
  1266. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1267. $res = $this->fractal->createData($resource)->toArray();
  1268. return response()->json($res);
  1269. }
  1270. /**
  1271. * POST /api/v1/accounts/{id}/unmute
  1272. *
  1273. * @param integer $id
  1274. *
  1275. * @return RelationshipTransformer
  1276. */
  1277. public function accountUnmuteById(Request $request, $id)
  1278. {
  1279. abort_if(!$request->user(), 403);
  1280. $user = $request->user();
  1281. $pid = $user->profile_id;
  1282. $account = Profile::findOrFail($id);
  1283. $filter = UserFilter::whereUserId($pid)
  1284. ->whereFilterableId($account->id)
  1285. ->whereFilterableType('App\Profile')
  1286. ->whereFilterType('mute')
  1287. ->first();
  1288. if($filter) {
  1289. $filter->delete();
  1290. Cache::forget("user:filter:list:$pid");
  1291. Cache::forget("feature:discover:posts:$pid");
  1292. Cache::forget("api:local:exp:rec:$pid");
  1293. }
  1294. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1295. $res = $this->fractal->createData($resource)->toArray();
  1296. return response()->json($res);
  1297. }
  1298. /**
  1299. * GET /api/v1/notifications
  1300. *
  1301. *
  1302. * @return NotificationTransformer
  1303. */
  1304. public function accountNotifications(Request $request)
  1305. {
  1306. abort_if(!$request->user(), 403);
  1307. $this->validate($request, [
  1308. 'limit' => 'nullable|integer|min:1|max:80',
  1309. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1310. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1311. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1312. ]);
  1313. $pid = $request->user()->profile_id;
  1314. $limit = $request->input('limit', 20);
  1315. $since = $request->input('since_id');
  1316. $min = $request->input('min_id');
  1317. $max = $request->input('max_id');
  1318. if(!$since && !$min && !$max) {
  1319. $min = 1;
  1320. }
  1321. $maxId = null;
  1322. $minId = null;
  1323. if($max) {
  1324. $res = NotificationService::getMax($pid, $max, $limit);
  1325. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1326. if(!empty($ids)) {
  1327. $maxId = max($ids);
  1328. $minId = min($ids);
  1329. }
  1330. } else {
  1331. $res = NotificationService::getMin($pid, $min ?? $since, $limit);
  1332. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1333. if(!empty($ids)) {
  1334. $maxId = max($ids);
  1335. $minId = min($ids);
  1336. }
  1337. }
  1338. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1339. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1340. NotificationService::warmCache($pid, 400, true);
  1341. }
  1342. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1343. if($minId == $maxId) {
  1344. $minId = null;
  1345. }
  1346. if($maxId) {
  1347. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next"';
  1348. }
  1349. if($minId) {
  1350. $link = '<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1351. }
  1352. if($maxId && $minId) {
  1353. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next",<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1354. }
  1355. $res = response()->json($res);
  1356. if(isset($link)) {
  1357. $res->withHeaders([
  1358. 'Link' => $link,
  1359. ]);
  1360. }
  1361. return $res;
  1362. }
  1363. /**
  1364. * GET /api/v1/timelines/home
  1365. *
  1366. *
  1367. * @return StatusTransformer
  1368. */
  1369. public function timelineHome(Request $request)
  1370. {
  1371. $this->validate($request,[
  1372. 'page' => 'nullable|integer|max:40',
  1373. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1374. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1375. 'limit' => 'nullable|integer|max:80'
  1376. ]);
  1377. $page = $request->input('page');
  1378. $min = $request->input('min_id');
  1379. $max = $request->input('max_id');
  1380. $limit = $request->input('limit') ?? 3;
  1381. $pid = $request->user()->profile_id;
  1382. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  1383. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1384. return $following->push($pid)->toArray();
  1385. });
  1386. if($min || $max) {
  1387. $dir = $min ? '>' : '<';
  1388. $id = $min ?? $max;
  1389. $res = Status::select(
  1390. 'id',
  1391. 'profile_id',
  1392. 'type',
  1393. 'visibility',
  1394. 'created_at'
  1395. )
  1396. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1397. ->where('id', $dir, $id)
  1398. ->whereIn('profile_id', $following)
  1399. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1400. ->latest()
  1401. ->take($limit)
  1402. ->get()
  1403. ->map(function($s) use($pid) {
  1404. $status = StatusService::getMastodon($s['id']);
  1405. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1406. return false;
  1407. }
  1408. if($pid) {
  1409. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1410. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1411. }
  1412. return $status;
  1413. })
  1414. ->filter(function($status) {
  1415. return $status && isset($status['account']);
  1416. })
  1417. ->values()
  1418. ->toArray();
  1419. } else {
  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. ->whereIn('profile_id', $following)
  1429. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1430. ->latest()
  1431. ->take($limit)
  1432. ->get()
  1433. ->map(function($s) use($pid) {
  1434. $status = StatusService::getMastodon($s['id']);
  1435. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1436. return false;
  1437. }
  1438. if($pid) {
  1439. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1440. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1441. }
  1442. return $status;
  1443. })
  1444. ->filter(function($status) {
  1445. return $status && isset($status['account']);
  1446. })
  1447. ->values()
  1448. ->toArray();
  1449. }
  1450. return response()->json($res);
  1451. }
  1452. /**
  1453. * GET /api/v1/conversations
  1454. *
  1455. * Not implemented
  1456. *
  1457. * @return array
  1458. */
  1459. public function conversations(Request $request)
  1460. {
  1461. abort_if(!$request->user(), 403);
  1462. $this->validate($request, [
  1463. 'limit' => 'min:1|max:40',
  1464. 'scope' => 'nullable|in:inbox,sent,requests'
  1465. ]);
  1466. $limit = $request->input('limit', 20);
  1467. $scope = $request->input('scope', 'inbox');
  1468. $pid = $request->user()->profile_id;
  1469. if(config('database.default') == 'pgsql') {
  1470. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1471. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid);
  1472. })
  1473. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1474. return $q->whereFromId($pid);
  1475. })
  1476. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1477. return $q->whereToId($pid)->whereIsHidden(true);
  1478. });
  1479. } else {
  1480. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1481. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid)->groupBy('to_id');
  1482. })
  1483. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1484. return $q->whereFromId($pid)->groupBy('to_id');
  1485. })
  1486. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1487. return $q->whereToId($pid)->whereIsHidden(true);
  1488. });
  1489. }
  1490. $dms = $dms->latest()
  1491. ->simplePaginate($limit)
  1492. ->map(function($dm) use($pid) {
  1493. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  1494. $res = [
  1495. 'id' => $dm->id,
  1496. 'unread' => false,
  1497. 'accounts' => [
  1498. AccountService::getMastodon($from)
  1499. ],
  1500. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  1501. ];
  1502. return $res;
  1503. })
  1504. ->filter(function($dm) {
  1505. return isset($dm['accounts']) && count($dm['accounts']);
  1506. })
  1507. ->unique(function($item, $key) {
  1508. return $item['accounts'][0]['id'];
  1509. })
  1510. ->values();
  1511. return response()->json($dms);
  1512. }
  1513. /**
  1514. * GET /api/v1/timelines/public
  1515. *
  1516. *
  1517. * @return StatusTransformer
  1518. */
  1519. public function timelinePublic(Request $request)
  1520. {
  1521. $this->validate($request,[
  1522. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1523. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1524. 'limit' => 'nullable|integer|max:80'
  1525. ]);
  1526. $min = $request->input('min_id');
  1527. $max = $request->input('max_id');
  1528. $limit = $request->input('limit') ?? 3;
  1529. $user = $request->user();
  1530. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1531. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1532. if(PublicTimelineService::count() == 0) {
  1533. PublicTimelineService::warmCache(true, 400);
  1534. }
  1535. });
  1536. if ($max) {
  1537. $feed = PublicTimelineService::getRankedMaxId($max, $limit);
  1538. } else if ($min) {
  1539. $feed = PublicTimelineService::getRankedMinId($min, $limit);
  1540. } else {
  1541. $feed = PublicTimelineService::get(0, $limit);
  1542. }
  1543. $res = collect($feed)
  1544. ->map(function($k) use($user) {
  1545. $status = StatusService::getMastodon($k);
  1546. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1547. return false;
  1548. }
  1549. if($user) {
  1550. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1551. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1552. }
  1553. return $status;
  1554. })
  1555. ->filter(function($s) use($filtered) {
  1556. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1557. })
  1558. ->values()
  1559. ->toArray();
  1560. return response()->json($res);
  1561. }
  1562. /**
  1563. * GET /api/v1/statuses/{id}
  1564. *
  1565. * @param integer $id
  1566. *
  1567. * @return StatusTransformer
  1568. */
  1569. public function statusById(Request $request, $id)
  1570. {
  1571. abort_if(!$request->user(), 403);
  1572. $user = $request->user();
  1573. $res = StatusService::getMastodon($id, false);
  1574. if(!$res || !isset($res['visibility'])) {
  1575. abort(404);
  1576. }
  1577. $scope = $res['visibility'];
  1578. if(!in_array($scope, ['public', 'unlisted'])) {
  1579. if($scope === 'private') {
  1580. if($res['account']['id'] != $user->profile_id) {
  1581. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  1582. }
  1583. } else {
  1584. abort(400, 'Invalid request');
  1585. }
  1586. }
  1587. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  1588. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  1589. return response()->json($res);
  1590. }
  1591. /**
  1592. * GET /api/v1/statuses/{id}/context
  1593. *
  1594. * @param integer $id
  1595. *
  1596. * @return StatusTransformer
  1597. */
  1598. public function statusContext(Request $request, $id)
  1599. {
  1600. abort_if(!$request->user(), 403);
  1601. $user = $request->user();
  1602. $status = Status::findOrFail($id);
  1603. if($status->profile_id !== $user->profile_id) {
  1604. if($status->scope == 'private') {
  1605. abort_if(!$status->profile->followedBy($user->profile), 403);
  1606. } else {
  1607. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1608. }
  1609. }
  1610. if($status->comments_disabled) {
  1611. $res = [
  1612. 'ancestors' => [],
  1613. 'descendants' => []
  1614. ];
  1615. } else {
  1616. $ancestors = $status->parent();
  1617. if($ancestors) {
  1618. $ares = new Fractal\Resource\Item($ancestors, new StatusTransformer());
  1619. $ancestors = [
  1620. $this->fractal->createData($ares)->toArray()
  1621. ];
  1622. } else {
  1623. $ancestors = [];
  1624. }
  1625. $descendants = Status::whereInReplyToId($id)->latest()->limit(20)->get();
  1626. $dres = new Fractal\Resource\Collection($descendants, new StatusTransformer());
  1627. $descendants = $this->fractal->createData($dres)->toArray();
  1628. $res = [
  1629. 'ancestors' => $ancestors,
  1630. 'descendants' => $descendants
  1631. ];
  1632. }
  1633. return response()->json($res);
  1634. }
  1635. /**
  1636. * GET /api/v1/statuses/{id}/card
  1637. *
  1638. * @param integer $id
  1639. *
  1640. * @return StatusTransformer
  1641. */
  1642. public function statusCard(Request $request, $id)
  1643. {
  1644. abort_if(!$request->user(), 403);
  1645. $user = $request->user();
  1646. $status = Status::findOrFail($id);
  1647. if($status->profile_id !== $user->profile_id) {
  1648. if($status->scope == 'private') {
  1649. abort_if(!$status->profile->followedBy($user->profile), 403);
  1650. } else {
  1651. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1652. }
  1653. }
  1654. // Return empty response since we don't handle support cards
  1655. $res = [];
  1656. return response()->json($res);
  1657. }
  1658. /**
  1659. * GET /api/v1/statuses/{id}/reblogged_by
  1660. *
  1661. * @param integer $id
  1662. *
  1663. * @return AccountTransformer
  1664. */
  1665. public function statusRebloggedBy(Request $request, $id)
  1666. {
  1667. abort_if(!$request->user(), 403);
  1668. $this->validate($request, [
  1669. 'page' => 'nullable|integer|min:1|max:40',
  1670. 'limit' => 'nullable|integer|min:1|max:80'
  1671. ]);
  1672. $limit = $request->input('limit') ?? 40;
  1673. $user = $request->user();
  1674. $status = Status::findOrFail($id);
  1675. if($status->profile_id !== $user->profile_id) {
  1676. if($status->scope == 'private') {
  1677. abort_if(!$status->profile->followedBy($user->profile), 403);
  1678. } else {
  1679. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1680. }
  1681. }
  1682. $shared = $status->sharedBy()->latest()->simplePaginate($limit);
  1683. $resource = new Fractal\Resource\Collection($shared, new AccountTransformer());
  1684. $res = $this->fractal->createData($resource)->toArray();
  1685. $url = $request->url();
  1686. $page = $request->input('page', 1);
  1687. $next = $page < 40 ? $page + 1 : 40;
  1688. $prev = $page > 1 ? $page - 1 : 1;
  1689. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1690. return response()->json($res, 200, ['Link' => $links]);
  1691. }
  1692. /**
  1693. * GET /api/v1/statuses/{id}/favourited_by
  1694. *
  1695. * @param integer $id
  1696. *
  1697. * @return AccountTransformer
  1698. */
  1699. public function statusFavouritedBy(Request $request, $id)
  1700. {
  1701. abort_if(!$request->user(), 403);
  1702. $this->validate($request, [
  1703. 'page' => 'nullable|integer|min:1|max:40',
  1704. 'limit' => 'nullable|integer|min:1|max:80'
  1705. ]);
  1706. $page = $request->input('page', 1);
  1707. $limit = $request->input('limit') ?? 40;
  1708. $user = $request->user();
  1709. $status = Status::findOrFail($id);
  1710. $offset = $page == 1 ? 0 : ($page * $limit - $limit);
  1711. if($offset > 100) {
  1712. if($user->profile_id != $status->profile_id) {
  1713. return [];
  1714. }
  1715. }
  1716. if($status->profile_id !== $user->profile_id) {
  1717. if($status->scope == 'private') {
  1718. abort_if(!$status->profile->followedBy($user->profile), 403);
  1719. } else {
  1720. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1721. }
  1722. }
  1723. $res = DB::table('likes')
  1724. ->select('likes.id', 'likes.profile_id', 'likes.status_id', 'followers.created_at')
  1725. ->leftJoin('followers', function($join) use($user, $status) {
  1726. return $join->on('likes.profile_id', '=', 'followers.following_id')
  1727. ->where('followers.profile_id', $user->profile_id)
  1728. ->where('likes.status_id', $status->id);
  1729. })
  1730. ->whereStatusId($status->id)
  1731. ->orderByDesc('followers.created_at')
  1732. ->offset($offset)
  1733. ->limit($limit)
  1734. ->get()
  1735. ->map(function($like) {
  1736. $account = AccountService::getMastodon($like->profile_id);
  1737. $account['follows'] = isset($like->created_at);
  1738. return $account;
  1739. })
  1740. ->filter(function($account) use($user) {
  1741. return $account && isset($account['id']) && $account['id'] != $user->profile_id;
  1742. })
  1743. ->values();
  1744. $url = $request->url();
  1745. $page = $request->input('page', 1);
  1746. $next = $page < 40 ? $page + 1 : 40;
  1747. $prev = $page > 1 ? $page - 1 : 1;
  1748. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1749. return response()->json($res, 200, ['Link' => $links]);
  1750. }
  1751. /**
  1752. * POST /api/v1/statuses
  1753. *
  1754. *
  1755. * @return StatusTransformer
  1756. */
  1757. public function statusCreate(Request $request)
  1758. {
  1759. abort_if(!$request->user(), 403);
  1760. $this->validate($request, [
  1761. 'status' => 'nullable|string',
  1762. 'in_reply_to_id' => 'nullable|integer',
  1763. 'media_ids' => 'array|max:' . config_cache('pixelfed.max_album_length'),
  1764. 'media_ids.*' => 'integer|min:1',
  1765. 'sensitive' => 'nullable|boolean',
  1766. 'visibility' => 'string|in:private,unlisted,public',
  1767. ]);
  1768. if(config('costar.enabled') == true) {
  1769. $blockedKeywords = config('costar.keyword.block');
  1770. if($blockedKeywords !== null && $request->status) {
  1771. $keywords = config('costar.keyword.block');
  1772. foreach($keywords as $kw) {
  1773. if(Str::contains($request->status, $kw) == true) {
  1774. abort(400, 'Invalid object. Contains banned keyword.');
  1775. }
  1776. }
  1777. }
  1778. }
  1779. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  1780. abort(403, 'Empty statuses are not allowed');
  1781. }
  1782. $ids = $request->input('media_ids');
  1783. $in_reply_to_id = $request->input('in_reply_to_id');
  1784. $user = $request->user();
  1785. $profile = $user->profile;
  1786. $limitKey = 'compose:rate-limit:store:' . $user->id;
  1787. $limitTtl = now()->addMinutes(15);
  1788. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1789. $dailyLimit = Status::whereProfileId($user->profile_id)
  1790. ->whereNull('in_reply_to_id')
  1791. ->whereNull('reblog_of_id')
  1792. ->where('created_at', '>', now()->subDays(1))
  1793. ->count();
  1794. return $dailyLimit >= 100;
  1795. });
  1796. abort_if($limitReached == true, 429);
  1797. $visibility = $profile->is_private ? 'private' : (
  1798. $profile->unlisted == true &&
  1799. $request->input('visibility', 'public') == 'public' ?
  1800. 'unlisted' :
  1801. $request->input('visibility', 'public'));
  1802. if($user->last_active_at == null) {
  1803. return [];
  1804. }
  1805. $content = strip_tags($request->input('status'));
  1806. $rendered = Autolink::create()->autolink($content);
  1807. if($in_reply_to_id) {
  1808. $parent = Status::findOrFail($in_reply_to_id);
  1809. $status = new Status;
  1810. $status->caption = $content;
  1811. $status->rendered = $rendered;
  1812. $status->scope = $visibility;
  1813. $status->visibility = $visibility;
  1814. $status->profile_id = $user->profile_id;
  1815. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1816. $status->in_reply_to_id = $parent->id;
  1817. $status->in_reply_to_profile_id = $parent->profile_id;
  1818. $status->save();
  1819. StatusService::del($parent->id);
  1820. Cache::forget('status:replies:all:' . $parent->id);
  1821. }
  1822. if($ids) {
  1823. if(Media::whereUserId($user->id)
  1824. ->whereNull('status_id')
  1825. ->find($ids)
  1826. ->count() == 0
  1827. ) {
  1828. abort(400, 'Invalid media_ids');
  1829. }
  1830. if(!$in_reply_to_id) {
  1831. $status = new Status;
  1832. $status->caption = $content;
  1833. $status->rendered = $rendered;
  1834. $status->profile_id = $user->profile_id;
  1835. $status->scope = 'draft';
  1836. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1837. $status->save();
  1838. }
  1839. $mimes = [];
  1840. foreach($ids as $k => $v) {
  1841. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  1842. continue;
  1843. }
  1844. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  1845. if($m->profile_id !== $user->profile_id || $m->status_id) {
  1846. abort(403, 'Invalid media id');
  1847. }
  1848. $m->status_id = $status->id;
  1849. $m->save();
  1850. array_push($mimes, $m->mime);
  1851. }
  1852. if(empty($mimes)) {
  1853. $status->delete();
  1854. abort(400, 'Invalid media ids');
  1855. }
  1856. $status->scope = $visibility;
  1857. $status->visibility = $visibility;
  1858. $status->type = StatusController::mimeTypeCheck($mimes);
  1859. $status->save();
  1860. }
  1861. if(!$status) {
  1862. abort(500, 'An error occured.');
  1863. }
  1864. NewStatusPipeline::dispatch($status);
  1865. if($status->in_reply_to_id) {
  1866. CommentPipeline::dispatch($parent, $status);
  1867. }
  1868. Cache::forget('user:account:id:'.$user->id);
  1869. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  1870. Cache::forget('profile:status_count:'.$user->profile_id);
  1871. Cache::forget($user->storageUsedKey());
  1872. Cache::forget('profile:embed:' . $status->profile_id);
  1873. Cache::forget($limitKey);
  1874. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1875. $res = $this->fractal->createData($resource)->toArray();
  1876. return response()->json($res);
  1877. }
  1878. /**
  1879. * DELETE /api/v1/statuses
  1880. *
  1881. * @param integer $id
  1882. *
  1883. * @return null
  1884. */
  1885. public function statusDelete(Request $request, $id)
  1886. {
  1887. abort_if(!$request->user(), 403);
  1888. $status = Status::whereProfileId($request->user()->profile->id)
  1889. ->findOrFail($id);
  1890. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1891. Cache::forget('profile:status_count:'.$status->profile_id);
  1892. StatusDelete::dispatch($status);
  1893. $res = $this->fractal->createData($resource)->toArray();
  1894. $res['text'] = $res['content'];
  1895. unset($res['content']);
  1896. return response()->json($res);
  1897. }
  1898. /**
  1899. * POST /api/v1/statuses/{id}/reblog
  1900. *
  1901. * @param integer $id
  1902. *
  1903. * @return StatusTransformer
  1904. */
  1905. public function statusShare(Request $request, $id)
  1906. {
  1907. abort_if(!$request->user(), 403);
  1908. $user = $request->user();
  1909. $status = Status::whereScope('public')->findOrFail($id);
  1910. if($status->profile_id !== $user->profile_id) {
  1911. if($status->scope == 'private') {
  1912. abort_if(!$status->profile->followedBy($user->profile), 403);
  1913. } else {
  1914. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1915. }
  1916. }
  1917. $share = Status::firstOrCreate([
  1918. 'profile_id' => $user->profile_id,
  1919. 'reblog_of_id' => $status->id,
  1920. 'in_reply_to_profile_id' => $status->profile_id,
  1921. 'scope' => 'public',
  1922. 'visibility' => 'public'
  1923. ]);
  1924. if($share->wasRecentlyCreated == true) {
  1925. SharePipeline::dispatch($share);
  1926. }
  1927. StatusService::del($status->id);
  1928. ReblogService::add($user->profile_id, $status->id);
  1929. $res = StatusService::getMastodon($status->id);
  1930. $res['reblogged'] = true;
  1931. return response()->json($res);
  1932. }
  1933. /**
  1934. * POST /api/v1/statuses/{id}/unreblog
  1935. *
  1936. * @param integer $id
  1937. *
  1938. * @return StatusTransformer
  1939. */
  1940. public function statusUnshare(Request $request, $id)
  1941. {
  1942. abort_if(!$request->user(), 403);
  1943. $user = $request->user();
  1944. $status = Status::whereScope('public')->findOrFail($id);
  1945. if($status->profile_id !== $user->profile_id) {
  1946. if($status->scope == 'private') {
  1947. abort_if(!$status->profile->followedBy($user->profile), 403);
  1948. } else {
  1949. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1950. }
  1951. }
  1952. $reblog = Status::whereProfileId($user->profile_id)
  1953. ->whereReblogOfId($status->id)
  1954. ->first();
  1955. if(!$reblog) {
  1956. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1957. $res = $this->fractal->createData($resource)->toArray();
  1958. return response()->json($res);
  1959. }
  1960. UndoSharePipeline::dispatch($reblog);
  1961. ReblogService::del($user->profile_id, $status->id);
  1962. $res = StatusService::getMastodon($status->id);
  1963. $res['reblogged'] = true;
  1964. return response()->json($res);
  1965. }
  1966. /**
  1967. * GET /api/v1/timelines/tag/{hashtag}
  1968. *
  1969. * @param string $hashtag
  1970. *
  1971. * @return StatusTransformer
  1972. */
  1973. public function timelineHashtag(Request $request, $hashtag)
  1974. {
  1975. $this->validate($request,[
  1976. 'page' => 'nullable|integer|max:40',
  1977. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1978. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1979. 'limit' => 'nullable|integer|max:40'
  1980. ]);
  1981. $tag = Hashtag::whereName($hashtag)
  1982. ->orWhere('slug', $hashtag)
  1983. ->first();
  1984. if(!$tag) {
  1985. return response()->json([]);
  1986. }
  1987. $min = $request->input('min_id');
  1988. $max = $request->input('max_id');
  1989. $limit = $request->input('limit', 20);
  1990. if(!$min && !$max) {
  1991. $id = 1;
  1992. $dir = '>';
  1993. } else {
  1994. $dir = $min ? '>' : '<';
  1995. $id = $min ?? $max;
  1996. }
  1997. $res = StatusHashtag::whereHashtagId($tag->id)
  1998. ->whereStatusVisibility('public')
  1999. ->whereHas('media')
  2000. ->where('status_id', $dir, $id)
  2001. ->latest()
  2002. ->limit($limit)
  2003. ->pluck('status_id')
  2004. ->filter(function($i) {
  2005. return StatusService::getMastodon($i);
  2006. })
  2007. ->map(function ($i) {
  2008. return StatusService::getMastodon($i);
  2009. })
  2010. ->filter()
  2011. ->values()
  2012. ->toArray();
  2013. return response()->json($res, 200, [], JSON_PRETTY_PRINT);
  2014. }
  2015. /**
  2016. * GET /api/v1/bookmarks
  2017. *
  2018. *
  2019. *
  2020. * @return StatusTransformer
  2021. */
  2022. public function bookmarks(Request $request)
  2023. {
  2024. abort_if(!$request->user(), 403);
  2025. $this->validate($request, [
  2026. 'limit' => 'nullable|integer|min:1|max:40',
  2027. 'max_id' => 'nullable|integer|min:0',
  2028. 'since_id' => 'nullable|integer|min:0',
  2029. 'min_id' => 'nullable|integer|min:0'
  2030. ]);
  2031. $pid = $request->user()->profile_id;
  2032. $limit = $request->input('limit') ?? 20;
  2033. $max_id = $request->input('max_id');
  2034. $since_id = $request->input('since_id');
  2035. $min_id = $request->input('min_id');
  2036. $dir = $min_id ? '>' : '<';
  2037. $id = $min_id ?? $max_id;
  2038. if($id) {
  2039. $bookmarks = Bookmark::whereProfileId($pid)
  2040. ->where('status_id', $dir, $id)
  2041. ->limit($limit)
  2042. ->pluck('status_id');
  2043. } else {
  2044. $bookmarks = Bookmark::whereProfileId($pid)
  2045. ->latest()
  2046. ->limit($limit)
  2047. ->pluck('status_id');
  2048. }
  2049. $res = [];
  2050. foreach($bookmarks as $id) {
  2051. $res[] = \App\Services\StatusService::getMastodon($id);
  2052. }
  2053. return $res;
  2054. }
  2055. /**
  2056. * POST /api/v1/statuses/{id}/bookmark
  2057. *
  2058. *
  2059. *
  2060. * @return StatusTransformer
  2061. */
  2062. public function bookmarkStatus(Request $request, $id)
  2063. {
  2064. abort_if(!$request->user(), 403);
  2065. $status = Status::whereNull('uri')
  2066. ->whereScope('public')
  2067. ->findOrFail($id);
  2068. Bookmark::firstOrCreate([
  2069. 'status_id' => $status->id,
  2070. 'profile_id' => $request->user()->profile_id
  2071. ]);
  2072. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2073. $res = $this->fractal->createData($resource)->toArray();
  2074. return response()->json($res);
  2075. }
  2076. /**
  2077. * POST /api/v1/statuses/{id}/unbookmark
  2078. *
  2079. *
  2080. *
  2081. * @return StatusTransformer
  2082. */
  2083. public function unbookmarkStatus(Request $request, $id)
  2084. {
  2085. abort_if(!$request->user(), 403);
  2086. $status = Status::whereNull('uri')
  2087. ->whereScope('public')
  2088. ->findOrFail($id);
  2089. Bookmark::firstOrCreate([
  2090. 'status_id' => $status->id,
  2091. 'profile_id' => $request->user()->profile_id
  2092. ]);
  2093. $bookmark = Bookmark::whereStatusId($status->id)
  2094. ->whereProfileId($request->user()->profile_id)
  2095. ->firstOrFail();
  2096. $bookmark->delete();
  2097. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2098. $res = $this->fractal->createData($resource)->toArray();
  2099. return response()->json($res);
  2100. }
  2101. /**
  2102. * GET /api/v2/search
  2103. *
  2104. *
  2105. * @return array
  2106. */
  2107. public function searchV2(Request $request)
  2108. {
  2109. abort_if(!$request->user(), 403);
  2110. $this->validate($request, [
  2111. 'q' => 'required|string|min:1|max:80',
  2112. 'account_id' => 'nullable|string',
  2113. 'max_id' => 'nullable|string',
  2114. 'min_id' => 'nullable|string',
  2115. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2116. 'exclude_unreviewed' => 'nullable',
  2117. 'resolve' => 'nullable',
  2118. 'limit' => 'nullable|integer|max:40',
  2119. 'offset' => 'nullable|integer',
  2120. 'following' => 'nullable'
  2121. ]);
  2122. return SearchApiV2Service::query($request);
  2123. }
  2124. /**
  2125. * GET /api/v1/discover/posts
  2126. *
  2127. *
  2128. * @return array
  2129. */
  2130. public function discoverPosts(Request $request)
  2131. {
  2132. abort_if(!$request->user(), 403);
  2133. $this->validate($request, [
  2134. 'limit' => 'integer|min:1|max:40'
  2135. ]);
  2136. $limit = $request->input('limit', 40);
  2137. $pid = $request->user()->profile_id;
  2138. $filters = UserFilterService::filters($pid);
  2139. $forYou = DiscoverService::getForYou();
  2140. $posts = $forYou->take(50)->map(function($post) {
  2141. return StatusService::getMastodon($post);
  2142. })
  2143. ->filter(function($post) use($filters) {
  2144. return $post &&
  2145. isset($post['account']) &&
  2146. isset($post['account']['id']) &&
  2147. !in_array($post['account']['id'], $filters);
  2148. })
  2149. ->take(12)
  2150. ->values();
  2151. return response()->json(compact('posts'));
  2152. }
  2153. /**
  2154. * GET /api/v2/statuses/{id}/replies
  2155. *
  2156. *
  2157. * @return array
  2158. */
  2159. public function statusReplies(Request $request, $id)
  2160. {
  2161. abort_if(!$request->user(), 403);
  2162. $this->validate($request, [
  2163. 'limit' => 'int|min:1|max:10',
  2164. 'sort' => 'in:all,newest,popular'
  2165. ]);
  2166. $limit = $request->input('limit', 3);
  2167. $pid = $request->user()->profile_id;
  2168. $status = StatusService::getMastodon($id, false);
  2169. abort_if(!$status, 404);
  2170. if($status['visibility'] == 'private') {
  2171. if($pid != $status['account']['id']) {
  2172. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2173. }
  2174. }
  2175. $sortBy = $request->input('sort', 'all');
  2176. if($sortBy == 'all' && $status['replies_count'] && $request->has('refresh_cache')) {
  2177. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2178. Cache::forget('status:replies:all:' . $id);
  2179. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2180. }
  2181. }
  2182. if($sortBy == 'all' && !$request->has('cursor')) {
  2183. $ids = Cache::remember('status:replies:all:' . $id, 86400, function() use($id) {
  2184. return DB::table('statuses')
  2185. ->where('in_reply_to_id', $id)
  2186. ->orderBy('id')
  2187. ->cursorPaginate(3);
  2188. });
  2189. } else {
  2190. $ids = DB::table('statuses')
  2191. ->where('in_reply_to_id', $id)
  2192. ->when($sortBy, function($q, $sortBy) {
  2193. if($sortBy === 'all') {
  2194. return $q->orderBy('id');
  2195. }
  2196. if($sortBy === 'newest') {
  2197. return $q->orderByDesc('created_at');
  2198. }
  2199. if($sortBy === 'popular') {
  2200. return $q->orderByDesc('likes_count');
  2201. }
  2202. })
  2203. ->cursorPaginate($limit);
  2204. }
  2205. $data = $ids->map(function($post) use($pid) {
  2206. $status = StatusService::get($post->id);
  2207. if(!$status || !isset($status['id'])) {
  2208. return false;
  2209. }
  2210. $status['favourited'] = LikeService::liked($pid, $post->id);
  2211. return $status;
  2212. })
  2213. ->filter(function($post) {
  2214. return $post && isset($post['id']) && isset($post['account']);
  2215. })
  2216. ->values();
  2217. $res = [
  2218. 'data' => $data,
  2219. 'next' => $ids->nextPageUrl()
  2220. ];
  2221. return $res;
  2222. }
  2223. /**
  2224. * GET /api/v2/statuses/{id}/state
  2225. *
  2226. *
  2227. * @return array
  2228. */
  2229. public function statusState(Request $request, $id)
  2230. {
  2231. abort_if(!$request->user(), 403);
  2232. $status = Status::findOrFail($id);
  2233. $pid = $request->user()->profile_id;
  2234. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2235. return StatusService::getState($status->id, $pid);
  2236. }
  2237. /**
  2238. * GET /api/v1/discover/accounts/popular
  2239. *
  2240. *
  2241. * @return array
  2242. */
  2243. public function discoverAccountsPopular(Request $request)
  2244. {
  2245. abort_if(!$request->user(), 403);
  2246. $pid = $request->user()->profile_id;
  2247. $ids = DB::table('profiles')
  2248. ->where('is_private', false)
  2249. ->whereNull('status')
  2250. ->orderByDesc('profiles.followers_count')
  2251. ->limit(20)
  2252. ->get();
  2253. $ids = $ids->map(function($profile) {
  2254. return AccountService::getMastodon($profile->id);
  2255. })
  2256. ->filter(function($profile) use($pid) {
  2257. return $profile &&
  2258. isset($profile['id']) &&
  2259. !FollowerService::follows($pid, $profile['id']) &&
  2260. $profile['id'] != $pid;
  2261. })
  2262. ->take(6)
  2263. ->values();
  2264. return response()->json($ids, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  2265. }
  2266. }