ApiV1Controller.php 106 KB

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