ApiV1Controller.php 99 KB

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