ApiV1Controller.php 92 KB

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