ApiV1Controller.php 94 KB

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