ApiV1Controller.php 93 KB

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