1
0

ApiV1Controller.php 87 KB

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