ApiV1Controller.php 88 KB

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