1
0

ApiV1Controller.php 82 KB

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