ApiV1Controller.php 135 KB

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