ApiV1Controller.php 71 KB

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