ApiV1Controller.php 89 KB

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