ApiV1Controller.php 79 KB

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