ApiV1Controller.php 127 KB

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