ApiV1Controller.php 68 KB

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